@@ -94,30 +94,42 @@ static void usage(void)
9494 */
9595static int prepare (char * dir , char * filename )
9696{
97- char buf [512 ];
97+ char buf [UTIL_PATH_SIZE + 1 ];
9898 int r , fd ;
9999
100100 r = mkdir (dir , 0700 );
101101 if (r < 0 && errno != EEXIST )
102102 return - errno ;
103103
104+ /* Refuse to write to a truncated file path */
105+ if (strlen (buf ) + 1 + strlen (filename ) > sizeof (buf ) - 1 )
106+ return -1 ;
107+
104108 snprintf (buf , sizeof (buf ), "%s/%s" , dir , filename );
105109
106- fd = open (buf ,O_RDWR |O_CREAT |O_CLOEXEC , S_IRUSR |S_IWUSR );
107- if (fd < 0 )
110+ fd = open (buf , O_RDWR |O_CREAT |O_CLOEXEC , S_IRUSR |S_IWUSR );
111+ if (fd < 0 ) {
108112 fprintf (stderr , "Cannot open %s: %m\n" , buf );
113+ return fd ;
114+ }
109115
110- if (lockf (fd ,F_TLOCK ,0 ) < 0 ) {
116+ if (lockf (fd , F_TLOCK , 0 ) < 0 ) {
111117 if (debug )
112118 fprintf (stderr , "Lock taken, wait for %d seconds\n" , UDEV_ALARM_TIMEOUT );
113119 if (errno == EAGAIN || errno == EACCES ) {
114120 alarm (UDEV_ALARM_TIMEOUT );
115- lockf (fd , F_LOCK , 0 );
121+ if (lockf (fd , F_LOCK , 0 )) { /* Blocking lock also failed, cancel the alarm and fail */
122+ fprintf (stderr , "Cannot lock %s: %m\n" , buf );
123+ alarm (0 );
124+ close (fd );
125+ return -1 ;
126+ }
116127 if (debug )
117128 fprintf (stderr , "Acquired lock on %s\n" , buf );
118129 } else {
119- if (debug )
120- fprintf (stderr , "Could not get lock on %s: %m\n" , buf );
130+ fprintf (stderr , "Could not get lock on %s: %m\n" , buf );
131+ close (fd );
132+ return -1 ;
121133 }
122134 }
123135
@@ -483,11 +495,16 @@ int main(int argc, char **argv)
483495 }
484496 kickout ();
485497
486- lseek (fd , 0 , SEEK_SET );
487- ftruncate (fd , 0 );
498+ if (lseek (fd , 0 , SEEK_SET ) < 0 || ftruncate (fd , 0 ) < 0 ) { /* in the unlikely event lseek/ftruncate fail */
499+ fprintf (stderr , "lseek/ftruncate %s/%s failed: %m\n" , tmpdir , checkpoint );
500+ close (fd );
501+ return -1 ;
502+ }
488503 ret = missing (fd );
489504
490- lockf (fd , F_ULOCK , 0 );
505+ if (lockf (fd , F_ULOCK , 0 )) {
506+ /* this error can be safely ignored */
507+ }
491508 close (fd );
492509out :
493510 if (debug )
0 commit comments