]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
Merge master
[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/resource.h>
44 #include <sys/wait.h>
45 #include <sys/uio.h>
46 #include <sys/un.h>
47 // #define _XPG4_2 1
48 #include <sys/socket.h>
49 #include <stdio.h>
50 #include <time.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 #include <atalk/volinfo.h>
93 #include <atalk/compat.h>
94
95 #include "usockfd.h"
96
97 #define DBHOME        ".AppleDB"
98 #define DBHOMELEN    8
99
100 static int srvfd;
101 static int rqstfd;
102 static volatile sig_atomic_t sigchild = 0;
103 static uint maxvol;
104
105 #define MAXSPAWN   3                   /* Max times respawned in.. */
106 #define TESTTIME   42                  /* this much seconds apfd client tries to  *
107                                         * to reconnect every 5 secondes, catch it */
108 #define MAXVOLS    4096
109 #define DEFAULTHOST  "localhost"
110 #define DEFAULTPORT  "4700"
111
112 struct server {
113     struct volinfo *volinfo;
114     pid_t pid;
115     time_t tm;                    /* When respawned last */
116     int count;                    /* Times respawned in the last TESTTIME secondes */
117     int control_fd;               /* file descriptor to child cnid_dbd process */
118 };
119
120 static struct server srv[MAXVOLS];
121
122 /* Default logging config: log to syslog with level log_note */
123 static char logconfig[MAXPATHLEN + 21 + 1] = "default log_note";
124
125 static void daemon_exit(int i)
126 {
127     server_unlock(_PATH_CNID_METAD_LOCK);
128     exit(i);
129 }
130
131 /* ------------------ */
132 static void sigterm_handler(int sig)
133 {
134     switch( sig ) {
135     case SIGTERM :
136         LOG(log_info, logtype_afpd, "shutting down on signal %d", sig );
137         break;
138     default :
139         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
140     }
141     daemon_exit(0);
142 }
143
144 static struct server *test_usockfn(struct volinfo *volinfo)
145 {
146     int i;
147     for (i = 0; i < maxvol; i++) {
148         if ((srv[i].volinfo) && (strcmp(srv[i].volinfo->v_path, volinfo->v_path) == 0)) {
149             return &srv[i];
150         }
151     }
152     return NULL;
153 }
154
155 /* -------------------- */
156 static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
157 {
158     pid_t pid;
159     struct server *up;
160     int sv[2];
161     int i;
162     time_t t;
163     char buf1[8];
164     char buf2[8];
165     char *volpath = volinfo->v_path;
166
167     LOG(log_debug, logtype_cnid, "maybe_start_dbd: Volume: \"%s\"", volpath);
168
169     up = test_usockfn(volinfo);
170     if (up && up->pid) {
171         /* we already have a process, send our fd */
172         if (send_fd(up->control_fd, rqstfd) < 0) {
173             /* FIXME */
174             return -1;
175         }
176         return 0;
177     }
178
179     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: no cnid_dbd for that volume yet");
180
181     time(&t);
182     if (!up) {
183         /* find an empty slot (i < maxvol) or the first free slot (i == maxvol)*/
184         for (i = 0; i <= maxvol; i++) {
185             if (srv[i].volinfo == NULL && i < MAXVOLS) {
186                 up = &srv[i];
187                 up->volinfo = volinfo;
188                 retainvolinfo(volinfo);
189                 up->tm = t;
190                 up->count = 0;
191                 if (i == maxvol)
192                     maxvol++;
193                 break;
194             }
195         }
196         if (!up) {
197             LOG(log_error, logtype_cnid, "no free slot for cnid_dbd child. Configured maximum: %d. Do you have so many volumes?", MAXVOLS);
198             return -1;
199         }
200     } else {
201         /* we have a slot but no process, check for respawn too fast */
202         if ( (t < (up->tm + TESTTIME)) /* We're in the respawn time window */
203              &&
204              (up->count > MAXSPAWN) ) { /* ...and already tried to fork too often */
205             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn too fast just exiting");
206             return -1; /* just exit, dont sleep, because we might have work to do for another client  */
207         }
208         if ( t >= (up->tm + TESTTIME) ) { /* out of respawn too fast windows reset the count */
209             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn window ended");
210             up->tm = t;
211             up->count = 0;
212         }
213         up->count++;
214         LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn count now is: %u", up->count);
215         if (up->count > MAXSPAWN) {
216             /* We spawned too fast. From now until the first time we tried + TESTTIME seconds
217                we will just return -1 above */
218             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: reached MAXSPAWN threshhold");
219         }
220     }
221
222     /* 
223        Create socketpair for comm between parent and child.
224        We use it to pass fds from connecting afpd processes to our
225        cnid_dbd child via fd passing.
226     */
227     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
228         LOG(log_error, logtype_cnid, "error in socketpair: %s", strerror(errno));
229         return -1;
230     }
231
232     if ((pid = fork()) < 0) {
233         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
234         return -1;
235     }
236     if (pid == 0) {
237         int ret;
238         /*
239          *  Child. Close descriptors and start the daemon. If it fails
240          *  just log it. The client process will fail connecting
241          *  afterwards anyway.
242          */
243
244         close(srvfd);
245         close(sv[0]);
246
247         for (i = 0; i < MAXVOLS; i++) {
248             if (srv[i].pid && up != &srv[i]) {
249                 close(srv[i].control_fd);
250             }
251         }
252
253         sprintf(buf1, "%i", sv[1]);
254         sprintf(buf2, "%i", rqstfd);
255
256         if (up->count == MAXSPAWN) {
257             /* there's a pb with the db inform child, it will delete the db */
258             LOG(log_warning, logtype_cnid,
259                 "Multiple attempts to start CNID db daemon for \"%s\" failed, wiping the slate clean...",
260                 up->volinfo->v_path);
261             ret = execlp(dbdpn, dbdpn, "-d", volpath, buf1, buf2, logconfig, NULL);
262         } else {
263             ret = execlp(dbdpn, dbdpn, volpath, buf1, buf2, logconfig, NULL);
264         }
265         /* Yikes! We're still here, so exec failed... */
266         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
267         daemon_exit(0);
268     }
269     /*
270      *  Parent.
271      */
272     up->pid = pid;
273     close(sv[1]);
274     up->control_fd = sv[0];
275     return 0;
276 }
277
278 /* ------------------ */
279 static int set_dbdir(char *dbdir)
280 {
281     int len;
282     struct stat st;
283
284     len = strlen(dbdir);
285
286     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
287         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
288         return -1;
289     }
290
291     if (dbdir[len - 1] != '/') {
292         strcat(dbdir, "/");
293         len++;
294     }
295     strcpy(dbdir + len, DBHOME);
296     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
297         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
298         return -1;
299     }
300     return 0;
301 }
302
303 /* ------------------ */
304 static uid_t user_to_uid (char *username)
305 {
306     struct passwd *this_passwd;
307
308     /* check for anything */
309     if ( !username || strlen ( username ) < 1 ) return 0;
310
311     /* grab the /etc/passwd record relating to username */
312     this_passwd = getpwnam ( username );
313
314     /* return false if there is no structure returned */
315     if (this_passwd == NULL) return 0;
316
317     /* return proper uid */
318     return this_passwd->pw_uid;
319
320 }
321
322 /* ------------------ */
323 static gid_t group_to_gid ( char *group)
324 {
325     struct group *this_group;
326
327     /* check for anything */
328     if ( !group || strlen ( group ) < 1 ) return 0;
329
330     /* grab the /etc/groups record relating to group */
331     this_group = getgrnam ( group );
332
333     /* return false if there is no structure returned */
334     if (this_group == NULL) return 0;
335
336     /* return proper gid */
337     return this_group->gr_gid;
338
339 }
340
341 /* ------------------ */
342 static void catch_child(int sig _U_) 
343 {
344     sigchild = 1;
345 }
346
347 /* ----------------------- */
348 static void set_signal(void)
349 {
350     struct sigaction sv;
351     sigset_t set;
352
353     memset(&sv, 0, sizeof(sv));
354
355     /* Catch SIGCHLD */
356     sv.sa_handler = catch_child;
357     sv.sa_flags = SA_NOCLDSTOP;
358     sigemptyset(&sv.sa_mask);
359     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
360         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
361         daemon_exit(EXITERR_SYS);
362     }
363
364     /* Catch SIGTERM */
365     sv.sa_handler = sigterm_handler;
366     sigfillset(&sv.sa_mask );
367     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
368         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
369         daemon_exit(EXITERR_SYS);
370     }
371
372     /* Ignore the rest */
373     sv.sa_handler = SIG_IGN;
374     sigemptyset(&sv.sa_mask );
375     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
376         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
377         daemon_exit(EXITERR_SYS);
378     }
379     sv.sa_handler = SIG_IGN;
380     sigemptyset(&sv.sa_mask );
381     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
382         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
383         daemon_exit(EXITERR_SYS);
384     }
385     sv.sa_handler = SIG_IGN;
386     sigemptyset(&sv.sa_mask );
387     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
388         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
389         daemon_exit(EXITERR_SYS);
390     }
391     sv.sa_handler = SIG_IGN;
392     sigemptyset(&sv.sa_mask );
393     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
394         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
395         daemon_exit(EXITERR_SYS);
396     }
397     sv.sa_handler = SIG_IGN;
398     sigemptyset(&sv.sa_mask );
399     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
400         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
401         daemon_exit(EXITERR_SYS);
402     }
403
404     /* block everywhere but in pselect */
405     sigemptyset(&set);
406     sigaddset(&set, SIGCHLD);
407     sigprocmask(SIG_BLOCK, &set, NULL);
408 }
409
410 static int setlimits(void)
411 {
412     struct rlimit rlim;
413
414     if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
415         LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
416         exit(1);
417     }
418     if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < 65535) {
419         rlim.rlim_cur = 65535;
420         if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < 65535)
421             rlim.rlim_max = 65535;
422         if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
423             LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
424             exit(1);
425         }
426     }
427     return 0;
428 }
429
430 /* ------------------ */
431 int main(int argc, char *argv[])
432 {
433     char  volpath[MAXPATHLEN + 1];
434     int   len, actual_len;
435     pid_t pid;
436     int   status;
437     char  *dbdpn = _PATH_CNID_DBD;
438     char  *host = DEFAULTHOST;
439     char  *port = DEFAULTPORT;
440     int    i;
441     int    cc;
442     uid_t  uid = 0;
443     gid_t  gid = 0;
444     int    err = 0;
445     int    debug = 0;
446     int    ret;
447     char   *loglevel = NULL;
448     char   *logfile  = NULL;
449     sigset_t set;
450     struct volinfo *volinfo;
451
452     set_processname("cnid_metad");
453
454     while (( cc = getopt( argc, argv, "vVds:p:h:u:g:l:f:")) != -1 ) {
455         switch (cc) {
456         case 'v':
457         case 'V':
458             printf("cnid_metad (Netatalk %s)\n", VERSION);
459             return -1;
460         case 'd':
461             debug = 1;
462             break;
463         case 'h':
464             host = strdup(optarg);
465             break;
466         case 'u':
467             uid = user_to_uid (optarg);
468             if (!uid) {
469                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
470                 err++;
471             }
472             break;
473         case 'g':
474             gid =group_to_gid (optarg);
475             if (!gid) {
476                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
477                 err++;
478             }
479             break;
480         case 'p':
481             port = strdup(optarg);
482             break;
483         case 's':
484             dbdpn = strdup(optarg);
485             break;
486         case 'l':
487             loglevel = strdup(optarg);
488             break;
489         case 'f':
490             logfile = strdup(optarg);
491             break;
492         default:
493             err++;
494             break;
495         }
496     }
497
498     /* Check for PID lockfile */
499     if (check_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
500         return -1;
501
502     if (!debug && daemonize(0, 0) != 0)
503         exit(EXITERR_SYS);
504
505     /* Create PID lockfile */
506     if (create_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
507         return -1;
508
509     if (loglevel) {
510         strlcpy(logconfig + 8, loglevel, 13);
511         free(loglevel);
512         strcat(logconfig, " ");
513     }
514     if (logfile) {
515         strlcat(logconfig, logfile, MAXPATHLEN);
516         free(logfile);
517     }
518     setuplog(logconfig);
519
520     if (err) {
521         LOG(log_error, logtype_cnid, "main: bad arguments");
522         daemon_exit(1);
523     }
524
525     (void)setlimits();
526
527     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
528         daemon_exit(1);
529
530     /* switch uid/gid */
531     if (uid || gid) {
532         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
533         if (gid) {
534             if (SWITCH_TO_GID(gid) < 0) {
535                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
536                 daemon_exit(1);
537             }
538         }
539         if (uid) {
540             if (SWITCH_TO_UID(uid) < 0) {
541                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
542                 daemon_exit(1);
543             }
544         }
545     }
546
547     set_signal();
548
549     sigemptyset(&set);
550     sigprocmask(SIG_SETMASK, NULL, &set);
551     sigdelset(&set, SIGCHLD);
552
553     while (1) {
554         rqstfd = usockfd_check(srvfd, &set);
555         /* Collect zombie processes and log what happened to them */
556         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
557             for (i = 0; i < maxvol; i++) {
558                 if (srv[i].pid == pid) {
559                     srv[i].pid = 0;
560                     close(srv[i].control_fd);
561                     break;
562                 }
563             }
564             if (WIFEXITED(status)) {
565                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
566                     pid, WEXITSTATUS(status));
567             }
568             else if (WIFSIGNALED(status)) {
569                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i",
570                     pid, WTERMSIG(status));
571             }
572             sigchild = 0;
573         }
574         if (rqstfd <= 0)
575             continue;
576
577         ret = readt(rqstfd, &len, sizeof(int), 1, 4);
578
579         if (!ret) {
580             /* already close */
581             goto loop_end;
582         }
583         else if (ret < 0) {
584             LOG(log_severe, logtype_cnid, "error read: %s", strerror(errno));
585             goto loop_end;
586         }
587         else if (ret != sizeof(int)) {
588             LOG(log_error, logtype_cnid, "short read: got %d", ret);
589             goto loop_end;
590         }
591         /*
592          *  checks for buffer overruns. The client libatalk side does it too
593          *  before handing the dir path over but who trusts clients?
594          */
595         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
596             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
597             goto loop_end;
598         }
599
600         actual_len = readt(rqstfd, volpath, len, 1, 5);
601         if (actual_len < 0) {
602             LOG(log_severe, logtype_cnid, "Read(2) error : %s", strerror(errno));
603             goto loop_end;
604         }
605         if (actual_len != len) {
606             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
607             goto loop_end;
608         }
609         volpath[len] = '\0';
610
611         /* Load .volinfo file */
612         if ((volinfo = allocvolinfo(volpath)) == NULL) {
613             LOG(log_severe, logtype_cnid, "allocvolinfo(\"%s\"): %s",
614                 volpath, strerror(errno));
615             goto loop_end;
616         }
617
618         if (set_dbdir(volinfo->v_dbpath) < 0) {
619             goto loop_end;
620         }
621
622         maybe_start_dbd(dbdpn, volinfo);
623
624         (void)closevolinfo(volinfo);
625
626     loop_end:
627         close(rqstfd);
628     }
629 }