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