Whamcloud - gitweb
e2freefrag: Clarify e2freefrag's messages
[tools/e2fsprogs.git] / misc / uuidd.c
1 /*
2  * uuidd.c --- UUID-generation daemon
3  *
4  * Copyright (C) 2007  Theodore Ts'o
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 #define _GNU_SOURCE /* for setres[ug]id() */
13
14 #include <stdio.h>
15 #ifdef HAVE_STDLIB_H
16 #include <stdlib.h>
17 #endif
18 #include <unistd.h>
19 #include <inttypes.h>
20 #include <errno.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/socket.h>
24 #include <sys/un.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <string.h>
28 #ifdef HAVE_GETOPT_H
29 #include <getopt.h>
30 #else
31 extern int getopt(int argc, char * const argv[], const char *optstring);
32 extern char *optarg;
33 extern int optind;
34 #endif
35 #include "uuid/uuid.h"
36 #include "uuid/uuidd.h"
37 #include "nls-enable.h"
38
39 #ifdef __GNUC__
40 #define CODE_ATTR(x) __attribute__(x)
41 #else
42 #define CODE_ATTR(x)
43 #endif
44
45 static void usage(const char *progname)
46 {
47         fprintf(stderr, _("Usage: %s [-d] [-p pidfile] [-s socketpath] "
48                           "[-T timeout]\n"), progname);
49         fprintf(stderr, _("       %s [-r|t] [-n num] [-s socketpath]\n"),
50                 progname);
51         fprintf(stderr, _("       %s -k\n"), progname);
52         exit(1);
53 }
54
55 static void die(const char *msg)
56 {
57         perror(msg);
58         exit(1);
59 }
60
61 static void create_daemon(void)
62 {
63         pid_t pid;
64         uid_t euid;
65
66         pid = fork();
67         if (pid == -1) {
68                 perror("fork");
69                 exit(1);
70         } else if (pid != 0) {
71             exit(0);
72         }
73
74         close(0);
75         close(1);
76         close(2);
77         open("/dev/null", O_RDWR);
78         open("/dev/null", O_RDWR);
79         open("/dev/null", O_RDWR);
80
81         if (chdir("/")) {}      /* Silence warn_unused_result warning */
82         (void) setsid();
83         euid = geteuid();
84         if (setreuid(euid, euid) < 0)
85                 die("setreuid");
86 }
87
88 static ssize_t read_all(int fd, char *buf, size_t count)
89 {
90         ssize_t ret;
91         ssize_t c = 0;
92         int tries = 0;
93
94         memset(buf, 0, count);
95         while (count > 0) {
96                 ret = read(fd, buf, count);
97                 if (ret <= 0) {
98                         if ((errno == EAGAIN || errno == EINTR || ret == 0) &&
99                             (tries++ < 5))
100                                 continue;
101                         return c ? c : -1;
102                 }
103                 if (ret > 0)
104                         tries = 0;
105                 count -= ret;
106                 buf += ret;
107                 c += ret;
108         }
109         return c;
110 }
111
112 static int write_all(int fd, char *buf, size_t count)
113 {
114         ssize_t ret;
115         int c = 0;
116
117         while (count > 0) {
118                 ret = write(fd, buf, count);
119                 if (ret < 0) {
120                         if ((errno == EAGAIN) || (errno == EINTR))
121                                 continue;
122                         return -1;
123                 }
124                 count -= ret;
125                 buf += ret;
126                 c += ret;
127         }
128         return c;
129 }
130
131 static const char *cleanup_pidfile, *cleanup_socket;
132
133 static void terminate_intr(int signo CODE_ATTR((unused)))
134 {
135         (void) unlink(cleanup_pidfile);
136         if (cleanup_socket)
137                 (void) unlink(cleanup_socket);
138         exit(0);
139 }
140
141 static int call_daemon(const char *socket_path, int op, char *buf,
142                        int buflen, int *num, const char **err_context)
143 {
144         char op_buf[8];
145         int op_len;
146         int s;
147         ssize_t ret;
148         int32_t reply_len = 0;
149         struct sockaddr_un srv_addr;
150
151         if (((op == 4) || (op == 5)) && !num) {
152                 if (err_context)
153                         *err_context = _("bad arguments");
154                 errno = EINVAL;
155                 return -1;
156         }
157
158         if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
159                 if (err_context)
160                         *err_context = _("socket");
161                 return -1;
162         }
163
164         srv_addr.sun_family = AF_UNIX;
165         strncpy(srv_addr.sun_path, socket_path, sizeof(srv_addr.sun_path));
166         srv_addr.sun_path[sizeof(srv_addr.sun_path)-1] = '\0';
167
168         if (connect(s, (const struct sockaddr *) &srv_addr,
169                     sizeof(struct sockaddr_un)) < 0) {
170                 if (err_context)
171                         *err_context = _("connect");
172                 close(s);
173                 return -1;
174         }
175
176         if (op == 5) {
177                 if ((*num)*16 > buflen-4)
178                         *num = (buflen-4) / 16;
179         }
180         op_buf[0] = op;
181         op_len = 1;
182         if ((op == 4) || (op == 5)) {
183                 memcpy(op_buf+1, num, sizeof(int));
184                 op_len += sizeof(int);
185         }
186
187         ret = write_all(s, op_buf, op_len);
188         if (ret < op_len) {
189                 if (err_context)
190                         *err_context = _("write");
191                 close(s);
192                 return -1;
193         }
194
195         ret = read_all(s, (char *) &reply_len, sizeof(reply_len));
196         if (ret < 0) {
197                 if (err_context)
198                         *err_context = _("read count");
199                 close(s);
200                 return -1;
201         }
202         if (reply_len < 0 || reply_len > buflen) {
203                 if (err_context)
204                         *err_context = _("bad response length");
205                 close(s);
206                 return -1;
207         }
208         ret = read_all(s, (char *) buf, reply_len);
209
210         if ((ret > 0) && (op == 4)) {
211                 if (reply_len >= (int) (16+sizeof(int)))
212                         memcpy(buf+16, num, sizeof(int));
213                 else
214                         *num = -1;
215         }
216         if ((ret > 0) && (op == 5)) {
217                 if (*num >= (int) sizeof(int))
218                         memcpy(buf, num, sizeof(int));
219                 else
220                         *num = -1;
221         }
222
223         close(s);
224
225         return ret;
226 }
227
228 static void server_loop(const char *socket_path, const char *pidfile_path,
229                         int debug, int timeout, int quiet)
230 {
231         struct sockaddr_un      my_addr, from_addr;
232         struct flock            fl;
233         socklen_t               fromlen;
234         int32_t                 reply_len = 0;
235         uuid_t                  uu;
236         mode_t                  save_umask;
237         char                    reply_buf[1024], *cp;
238         char                    op, str[37];
239         int                     i, s, ns, len, num;
240         int                     fd_pidfile, ret;
241
242         fd_pidfile = open(pidfile_path, O_CREAT | O_RDWR, 0664);
243         if (fd_pidfile < 0) {
244                 if (!quiet)
245                         fprintf(stderr, "Failed to open/create %s: %s\n",
246                                 pidfile_path, strerror(errno));
247                 exit(1);
248         }
249         cleanup_pidfile = pidfile_path;
250         cleanup_socket = 0;
251         signal(SIGALRM, terminate_intr);
252         alarm(30);
253         fl.l_type = F_WRLCK;
254         fl.l_whence = SEEK_SET;
255         fl.l_start = 0;
256         fl.l_len = 0;
257         fl.l_pid = 0;
258         while (fcntl(fd_pidfile, F_SETLKW, &fl) < 0) {
259                 if ((errno == EAGAIN) || (errno == EINTR))
260                         continue;
261                 if (!quiet)
262                         fprintf(stderr, "Failed to lock %s: %s\n",
263                                 pidfile_path, strerror(errno));
264                 exit(1);
265         }
266         ret = call_daemon(socket_path, 0, reply_buf, sizeof(reply_buf), 0, 0);
267         if (ret > 0) {
268                 if (!quiet)
269                         printf(_("uuidd daemon already running at pid %s\n"),
270                                reply_buf);
271                 exit(1);
272         }
273         alarm(0);
274
275         if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
276                 if (!quiet)
277                         fprintf(stderr, _("Couldn't create unix stream "
278                                           "socket: %s"), strerror(errno));
279                 exit(1);
280         }
281
282         /*
283          * Make sure the socket isn't using fd numbers 0-2 to avoid it
284          * getting closed by create_daemon()
285          */
286         while (!debug && s <= 2) {
287                 s = dup(s);
288                 if (s < 0) {
289                         perror("dup");
290                         exit(1);
291                 }
292         }
293
294         /*
295          * Create the address we will be binding to.
296          */
297         my_addr.sun_family = AF_UNIX;
298         strncpy(my_addr.sun_path, socket_path, sizeof(my_addr.sun_path));
299         my_addr.sun_path[sizeof(my_addr.sun_path)-1] = '\0';
300         (void) unlink(socket_path);
301         save_umask = umask(0);
302         if (bind(s, (const struct sockaddr *) &my_addr,
303                  sizeof(struct sockaddr_un)) < 0) {
304                 if (!quiet)
305                         fprintf(stderr,
306                                 _("Couldn't bind unix socket %s: %s\n"),
307                                 socket_path, strerror(errno));
308                 exit(1);
309         }
310         (void) umask(save_umask);
311
312         if (listen(s, 5) < 0) {
313                 if (!quiet)
314                         fprintf(stderr, _("Couldn't listen on unix "
315                                           "socket %s: %s\n"), socket_path,
316                                 strerror(errno));
317                 exit(1);
318         }
319
320         cleanup_socket = socket_path;
321         if (!debug)
322                 create_daemon();
323         signal(SIGHUP, terminate_intr);
324         signal(SIGINT, terminate_intr);
325         signal(SIGTERM, terminate_intr);
326         signal(SIGALRM, terminate_intr);
327         signal(SIGPIPE, SIG_IGN);
328
329         sprintf(reply_buf, "%8d\n", getpid());
330         if (ftruncate(fd_pidfile, 0)) {} /* Silence warn_unused_result */
331         write_all(fd_pidfile, reply_buf, strlen(reply_buf));
332         if (fd_pidfile > 1)
333                 close(fd_pidfile); /* Unlock the pid file */
334
335         while (1) {
336                 fromlen = sizeof(from_addr);
337                 if (timeout > 0)
338                         alarm(timeout);
339                 ns = accept(s, (struct sockaddr *) &from_addr, &fromlen);
340                 alarm(0);
341                 if (ns < 0) {
342                         if ((errno == EAGAIN) || (errno == EINTR))
343                                 continue;
344                         perror("accept");
345                         exit(1);
346                 }
347                 len = read(ns, &op, 1);
348                 if (len != 1) {
349                         if (len < 0)
350                                 perror("read");
351                         else
352                                 printf(_("Error reading from client, "
353                                          "len = %d\n"), len);
354                         goto shutdown_socket;
355                 }
356                 if ((op == 4) || (op == 5)) {
357                         if (read_all(ns, (char *) &num, sizeof(num)) != 4)
358                                 goto shutdown_socket;
359                         if (debug)
360                                 printf(_("operation %d, incoming num = %d\n"),
361                                        op, num);
362                 } else if (debug)
363                         printf("operation %d\n", op);
364
365                 switch(op) {
366                 case UUIDD_OP_GETPID:
367                         sprintf(reply_buf, "%d", getpid());
368                         reply_len = strlen(reply_buf)+1;
369                         break;
370                 case UUIDD_OP_GET_MAXOP:
371                         sprintf(reply_buf, "%d", UUIDD_MAX_OP);
372                         reply_len = strlen(reply_buf)+1;
373                         break;
374                 case UUIDD_OP_TIME_UUID:
375                         num = 1;
376                         uuid__generate_time(uu, &num);
377                         if (debug) {
378                                 uuid_unparse(uu, str);
379                                 printf(_("Generated time UUID: %s\n"), str);
380                         }
381                         memcpy(reply_buf, uu, sizeof(uu));
382                         reply_len = sizeof(uu);
383                         break;
384                 case UUIDD_OP_RANDOM_UUID:
385                         num = 1;
386                         uuid__generate_random(uu, &num);
387                         if (debug) {
388                                 uuid_unparse(uu, str);
389                                 printf(_("Generated random UUID: %s\n"), str);
390                         }
391                         memcpy(reply_buf, uu, sizeof(uu));
392                         reply_len = sizeof(uu);
393                         break;
394                 case UUIDD_OP_BULK_TIME_UUID:
395                         uuid__generate_time(uu, &num);
396                         if (debug) {
397                                 uuid_unparse(uu, str);
398                                 printf(_("Generated time UUID %s and %d "
399                                          "following\n"), str, num);
400                         }
401                         memcpy(reply_buf, uu, sizeof(uu));
402                         reply_len = sizeof(uu);
403                         memcpy(reply_buf+reply_len, &num, sizeof(num));
404                         reply_len += sizeof(num);
405                         break;
406                 case UUIDD_OP_BULK_RANDOM_UUID:
407                         if (num < 0)
408                                 num = 1;
409                         if (num > 1000)
410                                 num = 1000;
411                         if (num*16 > (int) (sizeof(reply_buf)-sizeof(num)))
412                                 num = (sizeof(reply_buf)-sizeof(num)) / 16;
413                         uuid__generate_random((unsigned char *) reply_buf +
414                                               sizeof(num), &num);
415                         if (debug) {
416                                 printf(_("Generated %d UUID's:\n"), num);
417                                 for (i=0, cp=reply_buf+sizeof(num);
418                                      i < num; i++, cp+=16) {
419                                         uuid_unparse((unsigned char *)cp, str);
420                                         printf("\t%s\n", str);
421                                 }
422                         }
423                         reply_len = (num*16) + sizeof(num);
424                         memcpy(reply_buf, &num, sizeof(num));
425                         break;
426                 default:
427                         if (debug)
428                                 printf(_("Invalid operation %d\n"), op);
429                         goto shutdown_socket;
430                 }
431                 write_all(ns, (char *) &reply_len, sizeof(reply_len));
432                 write_all(ns, reply_buf, reply_len);
433         shutdown_socket:
434                 close(ns);
435         }
436 }
437
438 int main(int argc, char **argv)
439 {
440         const char      *socket_path = UUIDD_SOCKET_PATH;
441         const char      *pidfile_path = UUIDD_PIDFILE_PATH;
442         const char      *err_context;
443         char            buf[1024], *cp;
444         char            str[37], *tmp;
445         uuid_t          uu;
446         uid_t           uid;
447         gid_t           gid;
448         int             i, c, ret;
449         int             debug = 0, do_type = 0, do_kill = 0, num = 0;
450         int             timeout = 0, quiet = 0, drop_privs = 0;
451
452 #ifdef ENABLE_NLS
453         setlocale(LC_MESSAGES, "");
454         setlocale(LC_CTYPE, "");
455         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
456         textdomain(NLS_CAT_NAME);
457 #endif
458
459         while ((c = getopt (argc, argv, "dkn:qp:s:tT:r")) != EOF) {
460                 switch (c) {
461                 case 'd':
462                         debug++;
463                         drop_privs = 1;
464                         break;
465                 case 'k':
466                         do_kill++;
467                         drop_privs = 1;
468                         break;
469                 case 'n':
470                         num = strtol(optarg, &tmp, 0);
471                         if ((num < 0) || *tmp) {
472                                 fprintf(stderr, _("Bad number: %s\n"), optarg);
473                                 exit(1);
474                         }
475                 case 'p':
476                         pidfile_path = optarg;
477                         drop_privs = 1;
478                         break;
479                 case 'q':
480                         quiet++;
481                         break;
482                 case 's':
483                         socket_path = optarg;
484                         drop_privs = 1;
485                         break;
486                 case 't':
487                         do_type = UUIDD_OP_TIME_UUID;
488                         drop_privs = 1;
489                         break;
490                 case 'T':
491                         timeout = strtol(optarg, &tmp, 0);
492                         if ((timeout < 0) || *tmp) {
493                                 fprintf(stderr, _("Bad number: %s\n"), optarg);
494                                 exit(1);
495                         }
496                         break;
497                 case 'r':
498                         do_type = UUIDD_OP_RANDOM_UUID;
499                         drop_privs = 1;
500                         break;
501                 default:
502                         usage(argv[0]);
503                 }
504         }
505         uid = getuid();
506         if (uid && drop_privs) {
507                 gid = getgid();
508 #ifdef HAVE_SETRESGID
509                 if (setresgid(gid, gid, gid) < 0)
510                         die("setresgid");
511 #else
512                 if (setregid(gid, gid) < 0)
513                         die("setregid");
514 #endif
515
516 #ifdef HAVE_SETRESUID
517                 if (setresuid(uid, uid, uid) < 0)
518                         die("setresuid");
519 #else
520                 if (setreuid(uid, uid) < 0)
521                         die("setreuid");
522 #endif
523         }
524         if (num && do_type) {
525                 ret = call_daemon(socket_path, do_type+2, buf,
526                                   sizeof(buf), &num, &err_context);
527                 if (ret < 0) {
528                         printf(_("Error calling uuidd daemon (%s): %s\n"),
529                                err_context, strerror(errno));
530                         exit(1);
531                 }
532                 if (do_type == UUIDD_OP_TIME_UUID) {
533                         if (ret != sizeof(uu) + sizeof(num))
534                                 goto unexpected_size;
535
536                         uuid_unparse((unsigned char *) buf, str);
537
538                         printf(_("%s and subsequent %d UUID's\n"), str, num);
539                 } else {
540                         printf(_("List of UUID's:\n"));
541                         cp = buf + 4;
542                         if (ret != (int) (sizeof(num) + num*sizeof(uu)))
543                                 goto unexpected_size;
544                         for (i=0; i < num; i++, cp+=16) {
545                                 uuid_unparse((unsigned char *) cp, str);
546                                 printf("\t%s\n", str);
547                         }
548                 }
549                 exit(0);
550         }
551         if (do_type) {
552                 ret = call_daemon(socket_path, do_type, (char *) &uu,
553                                   sizeof(uu), 0, &err_context);
554                 if (ret < 0) {
555                         printf(_("Error calling uuidd daemon (%s): %s\n"),
556                                err_context, strerror(errno));
557                         exit(1);
558                 }
559                 if (ret != sizeof(uu)) {
560                 unexpected_size:
561                         printf(_("Unexpected reply length from server %d\n"),
562                                ret);
563                         exit(1);
564                 }
565                 uuid_unparse(uu, str);
566
567                 printf("%s\n", str);
568                 exit(0);
569         }
570
571         if (do_kill) {
572                 ret = call_daemon(socket_path, 0, buf, sizeof(buf), 0, 0);
573                 if ((ret > 0) && ((do_kill = atoi((char *) buf)) > 0)) {
574                         ret = kill(do_kill, SIGTERM);
575                         if (ret < 0) {
576                                 if (!quiet)
577                                         fprintf(stderr,
578                                                 _("Couldn't kill uuidd running "
579                                                   "at pid %d: %s\n"), do_kill,
580                                                 strerror(errno));
581                                 exit(1);
582                         }
583                         if (!quiet)
584                                 printf(_("Killed uuidd running at pid %d\n"),
585                                        do_kill);
586                 }
587                 exit(0);
588         }
589
590         server_loop(socket_path, pidfile_path, debug, timeout, quiet);
591         return 0;
592 }