]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
Enhanced machine type
[netatalk.git] / etc / cnid_dbd / cnid_metad.c
1 /*
2  * Copyright (C) Joerg Lenneis 2003
3  * Copyright (C) Frank Lahm 2010
4  * All Rights Reserved.  See COPYING.
5  */
6
7 /* 
8    cnid_dbd metadaemon to start up cnid_dbd upon request from afpd.
9    Here is how it works:
10    
11                        via TCP socket
12    1.       afpd          ------->        cnid_metad
13
14                    via UNIX domain socket
15    2.   cnid_metad        ------->         cnid_dbd
16
17                     passes afpd client fd
18    3.   cnid_metad        ------->         cnid_dbd
19
20    Result:
21                        via TCP socket
22    4.       afpd          ------->         cnid_dbd
23  */
24
25
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif /* HAVE_CONFIG_H */
29
30 #include <unistd.h>
31 #undef __USE_GNU
32
33 #include <stdlib.h>
34 #include <sys/param.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <signal.h>
38 #ifdef HAVE_SYS_TYPES_H
39 #include <sys/types.h>
40 #endif
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
47 #ifdef HAVE_SYS_UIO_H
48 #include <sys/uio.h>
49 #endif
50 #include <sys/un.h>
51 #define _XPG4_2 1
52 #include <sys/socket.h>
53 #include <stdio.h>
54 #include <time.h>
55 #include <sys/ioctl.h>
56
57 #ifndef WEXITSTATUS
58 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
59 #endif /* ! WEXITSTATUS */
60 #ifndef WIFEXITED
61 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
62 #endif /* ! WIFEXITED */
63 #ifndef WIFSTOPPED
64 #define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
65 #endif
66
67 #ifndef WIFSIGNALED
68 #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
69 #endif
70 #ifndef WTERMSIG
71 #define WTERMSIG(status)      ((status) & 0x7f)
72 #endif
73
74 /* functions for username and group */
75 #include <pwd.h>
76 #include <grp.h>
77
78 /* FIXME */
79 #ifdef linux
80 #ifndef USE_SETRESUID
81 #define USE_SETRESUID 1
82 #define SWITCH_TO_GID(gid)  ((setresgid(gid,gid,gid) < 0 || setgid(gid) < 0) ? -1 : 0)
83 #define SWITCH_TO_UID(uid)  ((setresuid(uid,uid,uid) < 0 || setuid(uid) < 0) ? -1 : 0)
84 #endif  /* USE_SETRESUID */
85 #else   /* ! linux */
86 #ifndef USE_SETEUID
87 #define USE_SETEUID 1
88 #define SWITCH_TO_GID(gid)  ((setegid(gid) < 0 || setgid(gid) < 0) ? -1 : 0)
89 #define SWITCH_TO_UID(uid)  ((setuid(uid) < 0 || seteuid(uid) < 0 || setuid(uid) < 0) ? -1 : 0)
90 #endif  /* USE_SETEUID */
91 #endif  /* linux */
92
93 #include <atalk/util.h>
94 #include <atalk/logger.h>
95 #include <atalk/cnid_dbd_private.h>
96 #include <atalk/paths.h>
97
98 #include "db_param.h"
99 #include "usockfd.h"
100
101 #define DBHOME        ".AppleDB"
102 #define DBHOMELEN    8
103
104 static int srvfd;
105 static int rqstfd;
106 static volatile sig_atomic_t sigchild = 0;
107
108 #define MAXSPAWN   3                   /* Max times respawned in.. */
109 #define TESTTIME   42                  /* this much seconds apfd client tries to  *
110                                         * to reconnect every 5 secondes, catch it */
111 #define MAXVOLS    512
112 #define DEFAULTHOST  "localhost"
113 #define DEFAULTPORT  "4700"
114
115 struct server {
116     char  *name;
117     pid_t pid;
118     time_t tm;                    /* When respawned last */
119     int count;                    /* Times respawned in the last TESTTIME secondes */
120     int control_fd;               /* file descriptor to child cnid_dbd process */
121 };
122
123 static struct server srv[MAXVOLS];
124
125 /* Default logging config: log to syslog with level log_note */
126 static char logconfig[MAXPATHLEN + 21 + 1] = "default log_note";
127
128 static void daemon_exit(int i)
129 {
130     server_unlock(_PATH_CNID_METAD_LOCK);
131     exit(i);
132 }
133
134 /* ------------------ */
135 static void sigterm_handler(int sig)
136 {
137     switch( sig ) {
138     case SIGTERM :
139         LOG(log_info, logtype_afpd, "shutting down on signal %d", sig );
140         break;
141     default :
142         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
143     }
144     daemon_exit(0);
145 }
146
147 static struct server *test_usockfn(char *dir)
148 {
149     int i;
150     for (i = 0; i < MAXVOLS; i++) {
151         if (srv[i].name && !strcmp(srv[i].name, dir)) {
152             return &srv[i];
153         }
154     }
155     return NULL;
156 }
157
158 /* -------------------- */
159 static int send_cred(int socket, int fd)
160 {
161     int ret;
162     struct msghdr msgh;
163     struct iovec iov[1];
164     struct cmsghdr *cmsgp = NULL;
165     char *buf;
166     size_t size;
167     int er=0;
168
169     size = CMSG_SPACE(sizeof fd);
170     buf = malloc(size);
171     if (!buf) {
172         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
173         return -1;
174     }
175
176     memset(&msgh,0,sizeof (msgh));
177     memset(buf,0, size);
178
179     msgh.msg_name = NULL;
180     msgh.msg_namelen = 0;
181
182     msgh.msg_iov = iov;
183     msgh.msg_iovlen = 1;
184
185     iov[0].iov_base = &er;
186     iov[0].iov_len = sizeof(er);
187
188     msgh.msg_control = buf;
189     msgh.msg_controllen = size;
190
191     cmsgp = CMSG_FIRSTHDR(&msgh);
192     cmsgp->cmsg_level = SOL_SOCKET;
193     cmsgp->cmsg_type = SCM_RIGHTS;
194     cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
195
196     *((int *)CMSG_DATA(cmsgp)) = fd;
197     msgh.msg_controllen = cmsgp->cmsg_len;
198
199     do  {
200         ret = sendmsg(socket,&msgh, 0);
201     } while ( ret == -1 && errno == EINTR );
202     if (ret == -1) {
203         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
204         free(buf);
205         return -1;
206     }
207     free(buf);
208     return 0;
209 }
210
211 /* -------------------- */
212 static int maybe_start_dbd(char *dbdpn, char *dbdir, char *usockfn)
213 {
214     pid_t pid;
215     struct server *up;
216     int sv[2];
217     int i;
218     time_t t;
219     char buf1[8];
220     char buf2[8];
221
222     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: dbdir: '%s', UNIX socket file: '%s'", 
223         dbdir, usockfn);
224
225     up = test_usockfn(dbdir);
226     if (up && up->pid) {
227         /* we already have a process, send our fd */
228         if (send_cred(up->control_fd, rqstfd) < 0) {
229             /* FIXME */
230             return -1;
231         }
232         return 0;
233     }
234
235     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: no cnid_dbd for that volume yet. Starting one ...");
236
237     time(&t);
238     if (!up) {
239         /* find an empty slot */
240         for (i = 0; i < MAXVOLS; i++) {
241             if ( !srv[i].name ) {
242                 up = &srv[i];
243                 up->tm = t;
244                 up->count = 0;
245                 up->name = strdup(dbdir);
246                 break;
247             }
248         }
249         if (!up) {
250             LOG(log_error, logtype_cnid, "no free slot for cnid_dbd child. Configured maximum: %d. Do you have so many volumes?", MAXVOLS);
251             return -1;
252         }
253     }
254     else {
255         /* we have a slot but no process, check for respawn too fast */
256         if ( (t < (up->tm + TESTTIME)) /* We're in the respawn time window */
257              &&
258              (up->count > MAXSPAWN) ) { /* ...and already tried to fork too often */
259             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn too fast just exiting");
260             return -1; /* just exit, dont sleep, because we might have work to do for another client  */
261         }
262         if ( t >= (up->tm + TESTTIME) ) { /* out of respawn too fast windows reset the count */
263             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn window ended");
264             up->tm = t;
265             up->count = 0;
266         }
267         up->count++;
268         LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn count now is: %u", up->count);
269         if (up->count > MAXSPAWN) {
270             /* We spawned too fast. From now until the first time we tried + TESTTIME seconds
271                we will just return -1 above */
272             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: reached MAXSPAWN threshhold");
273         }
274     }
275
276     /* 
277        Create socketpair for comm between parent and child.
278        We use it to pass fds from connecting afpd processes to our
279        cnid_dbd child via fd passing.
280     */
281     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
282         LOG(log_error, logtype_cnid, "error in socketpair: %s", strerror(errno));
283         return -1;
284     }
285
286     if ((pid = fork()) < 0) {
287         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
288         return -1;
289     }
290     if (pid == 0) {
291         int ret;
292         /*
293          *  Child. Close descriptors and start the daemon. If it fails
294          *  just log it. The client process will fail connecting
295          *  afterwards anyway.
296          */
297
298         close(srvfd);
299         close(sv[0]);
300
301         for (i = 0; i < MAXVOLS; i++) {
302             if (srv[i].pid && up != &srv[i]) {
303                 close(srv[i].control_fd);
304             }
305         }
306
307         sprintf(buf1, "%i", sv[1]);
308         sprintf(buf2, "%i", rqstfd);
309
310         if (up->count == MAXSPAWN) {
311             /* there's a pb with the db inform child
312              * it will run recover, delete the db whatever
313              */
314             LOG(log_error, logtype_cnid, "try with -d %s", up->name);
315             ret = execlp(dbdpn, dbdpn, "-d", dbdir, buf1, buf2, logconfig, NULL);
316         }
317         else {
318             ret = execlp(dbdpn, dbdpn, dbdir, buf1, buf2, logconfig, NULL);
319         }
320         /* Yikes! We're still here, so exec failed... */
321         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
322         daemon_exit(0);
323     }
324     /*
325      *  Parent.
326      */
327     up->pid = pid;
328     close(sv[1]);
329     up->control_fd = sv[0];
330     return 0;
331 }
332
333 /* ------------------ */
334 static int set_dbdir(char *dbdir, int len)
335 {
336     struct stat st;
337
338     if (!len)
339         return -1;
340
341     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
342         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
343         return -1;
344     }
345
346     if (dbdir[len - 1] != '/') {
347         strcat(dbdir, "/");
348         len++;
349     }
350     strcpy(dbdir + len, DBHOME);
351     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
352         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
353         return -1;
354     }
355     return 0;
356 }
357
358 /* ------------------ */
359 static uid_t user_to_uid (char *username)
360 {
361     struct passwd *this_passwd;
362
363     /* check for anything */
364     if ( !username || strlen ( username ) < 1 ) return 0;
365
366     /* grab the /etc/passwd record relating to username */
367     this_passwd = getpwnam ( username );
368
369     /* return false if there is no structure returned */
370     if (this_passwd == NULL) return 0;
371
372     /* return proper uid */
373     return this_passwd->pw_uid;
374
375 }
376
377 /* ------------------ */
378 static gid_t group_to_gid ( char *group)
379 {
380     struct group *this_group;
381
382     /* check for anything */
383     if ( !group || strlen ( group ) < 1 ) return 0;
384
385     /* grab the /etc/groups record relating to group */
386     this_group = getgrnam ( group );
387
388     /* return false if there is no structure returned */
389     if (this_group == NULL) return 0;
390
391     /* return proper gid */
392     return this_group->gr_gid;
393
394 }
395
396 /* ------------------ */
397 static void catch_child(int sig _U_) 
398 {
399     sigchild = 1;
400 }
401
402 /* ----------------------- */
403 static void set_signal(void)
404 {
405     struct sigaction sv;
406     sigset_t set;
407
408     memset(&sv, 0, sizeof(sv));
409
410     /* Catch SIGCHLD */
411     sv.sa_handler = catch_child;
412     sv.sa_flags = SA_NOCLDSTOP;
413     sigemptyset(&sv.sa_mask);
414     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
415         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
416         daemon_exit(EXITERR_SYS);
417     }
418
419     /* Catch SIGTERM */
420     sv.sa_handler = sigterm_handler;
421     sigfillset(&sv.sa_mask );
422     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
423         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
424         daemon_exit(EXITERR_SYS);
425     }
426
427     /* Ignore the rest */
428     sv.sa_handler = SIG_IGN;
429     sigemptyset(&sv.sa_mask );
430     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
431         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
432         daemon_exit(EXITERR_SYS);
433     }
434     sv.sa_handler = SIG_IGN;
435     sigemptyset(&sv.sa_mask );
436     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
437         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
438         daemon_exit(EXITERR_SYS);
439     }
440     sv.sa_handler = SIG_IGN;
441     sigemptyset(&sv.sa_mask );
442     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
443         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
444         daemon_exit(EXITERR_SYS);
445     }
446     sv.sa_handler = SIG_IGN;
447     sigemptyset(&sv.sa_mask );
448     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
449         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
450         daemon_exit(EXITERR_SYS);
451     }
452     sv.sa_handler = SIG_IGN;
453     sigemptyset(&sv.sa_mask );
454     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
455         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
456         daemon_exit(EXITERR_SYS);
457     }
458
459     /* block everywhere but in pselect */
460     sigemptyset(&set);
461     sigaddset(&set, SIGCHLD);
462     sigprocmask(SIG_BLOCK, &set, NULL);
463 }
464
465 /* ------------------ */
466 int main(int argc, char *argv[])
467 {
468     char  dbdir[MAXPATHLEN + 1];
469     int   len, actual_len;
470     pid_t pid;
471     int   status;
472     char  *dbdpn = _PATH_CNID_DBD;
473     char  *host = DEFAULTHOST;
474     char  *port = DEFAULTPORT;
475     struct db_param *dbp;
476     int    i;
477     int    cc;
478     uid_t  uid = 0;
479     gid_t  gid = 0;
480     int    err = 0;
481     int    debug = 0;
482     int    ret;
483     char   *loglevel = NULL;
484     char   *logfile  = NULL;
485     sigset_t set;
486
487     set_processname("cnid_metad");
488
489     while (( cc = getopt( argc, argv, "ds:p:h:u:g:l:f:")) != -1 ) {
490         switch (cc) {
491         case 'd':
492             debug = 1;
493             break;
494         case 'h':
495             host = strdup(optarg);
496             break;
497         case 'u':
498             uid = user_to_uid (optarg);
499             if (!uid) {
500                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
501                 err++;
502             }
503             break;
504         case 'g':
505             gid =group_to_gid (optarg);
506             if (!gid) {
507                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
508                 err++;
509             }
510             break;
511         case 'p':
512             port = strdup(optarg);
513             break;
514         case 's':
515             dbdpn = strdup(optarg);
516             break;
517         case 'l':
518             loglevel = strdup(optarg);
519             break;
520         case 'f':
521             logfile = strdup(optarg);
522             break;
523         default:
524             err++;
525             break;
526         }
527     }
528
529     if (loglevel) {
530         strlcpy(logconfig + 8, loglevel, 13);
531         free(loglevel);
532         strcat(logconfig, " ");
533     }
534     if (logfile) {
535         strlcat(logconfig, logfile, MAXPATHLEN);
536         free(logfile);
537     }
538     setuplog(logconfig);
539
540     if (err) {
541         LOG(log_error, logtype_cnid, "main: bad arguments");
542         daemon_exit(1);
543     }
544
545     /* Check PID lockfile and become a daemon */
546     switch(server_lock("cnid_metad", _PATH_CNID_METAD_LOCK, 0)) {
547     case -1: /* error */
548         daemon_exit(EXITERR_SYS);
549     case 0: /* child */
550         break;
551     default: /* server */
552         exit(0);
553     }
554
555     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
556         daemon_exit(1);
557
558     /* switch uid/gid */
559     if (uid || gid) {
560         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
561         if (gid) {
562             if (SWITCH_TO_GID(gid) < 0) {
563                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
564                 daemon_exit(1);
565             }
566         }
567         if (uid) {
568             if (SWITCH_TO_UID(uid) < 0) {
569                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
570                 daemon_exit(1);
571             }
572         }
573     }
574
575     set_signal();
576
577     sigemptyset(&set);
578     sigprocmask(SIG_SETMASK, NULL, &set);
579     sigdelset(&set, SIGCHLD);
580
581     while (1) {
582         rqstfd = usockfd_check(srvfd, &set);
583         /* Collect zombie processes and log what happened to them */
584         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
585             for (i = 0; i < MAXVOLS; i++) {
586                 if (srv[i].pid == pid) {
587                     srv[i].pid = 0;
588                     close(srv[i].control_fd);
589                     break;
590                 }
591             }
592             if (WIFEXITED(status)) {
593                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
594                     pid, WEXITSTATUS(status));
595             }
596             else if (WIFSIGNALED(status)) {
597                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i",
598                     pid, WTERMSIG(status));
599             }
600             sigchild = 0;
601         }
602         if (rqstfd <= 0)
603             continue;
604
605         /* TODO: Check out read errors, broken pipe etc. in libatalk. Is
606            SIGIPE ignored there? Answer: Ignored for dsi, but not for asp ... */
607         ret = readt(rqstfd, &len, sizeof(int), 1, 5);
608         if (!ret) {
609             /* already close */
610             goto loop_end;
611         }
612         else if (ret < 0) {
613             LOG(log_severe, logtype_cnid, "error read: %s", strerror(errno));
614             goto loop_end;
615         }
616         else if (ret != sizeof(int)) {
617             LOG(log_error, logtype_cnid, "short read: got %d", ret);
618             goto loop_end;
619         }
620         /*
621          *  checks for buffer overruns. The client libatalk side does it too
622          *  before handing the dir path over but who trusts clients?
623          */
624         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
625             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
626             goto loop_end;
627         }
628
629         actual_len = readt(rqstfd, dbdir, len, 1, 5);
630         if (actual_len < 0) {
631             LOG(log_severe, logtype_cnid, "Read(2) error : %s", strerror(errno));
632             goto loop_end;
633         }
634         if (actual_len != len) {
635             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
636             goto loop_end;
637         }
638         dbdir[len] = '\0';
639
640         if (set_dbdir(dbdir, len) < 0) {
641             goto loop_end;
642         }
643
644         if ((dbp = db_param_read(dbdir, METAD)) == NULL) {
645             LOG(log_error, logtype_cnid, "Error reading config file");
646             goto loop_end;
647         }
648         maybe_start_dbd(dbdpn, dbdir, dbp->usock_file);
649
650     loop_end:
651         close(rqstfd);
652     }
653 }