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