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