]> 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/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
51 #ifndef WEXITSTATUS
52 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
53 #endif /* ! WEXITSTATUS */
54 #ifndef WIFEXITED
55 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
56 #endif /* ! WIFEXITED */
57 #ifndef WIFSTOPPED
58 #define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
59 #endif
60
61 #ifndef WIFSIGNALED
62 #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
63 #endif
64 #ifndef WTERMSIG
65 #define WTERMSIG(status)      ((status) & 0x7f)
66 #endif
67
68 /* functions for username and group */
69 #include <pwd.h>
70 #include <grp.h>
71
72 /* FIXME */
73 #ifdef linux
74 #ifndef USE_SETRESUID
75 #define USE_SETRESUID 1
76 #define SWITCH_TO_GID(gid)  ((setresgid(gid,gid,gid) < 0 || setgid(gid) < 0) ? -1 : 0)
77 #define SWITCH_TO_UID(uid)  ((setresuid(uid,uid,uid) < 0 || setuid(uid) < 0) ? -1 : 0)
78 #endif  /* USE_SETRESUID */
79 #else   /* ! linux */
80 #ifndef USE_SETEUID
81 #define USE_SETEUID 1
82 #define SWITCH_TO_GID(gid)  ((setegid(gid) < 0 || setgid(gid) < 0) ? -1 : 0)
83 #define SWITCH_TO_UID(uid)  ((setuid(uid) < 0 || seteuid(uid) < 0 || setuid(uid) < 0) ? -1 : 0)
84 #endif  /* USE_SETEUID */
85 #endif  /* linux */
86
87 #include <atalk/util.h>
88 #include <atalk/logger.h>
89 #include <atalk/cnid_dbd_private.h>
90 #include <atalk/paths.h>
91 #include <atalk/volinfo.h>
92 #include <atalk/compat.h>
93
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 static uint maxvol;
103
104 #define MAXSPAWN   3                   /* Max times respawned in.. */
105 #define TESTTIME   42                  /* this much seconds apfd client tries to  *
106                                         * to reconnect every 5 secondes, catch it */
107 #define MAXVOLS    4096
108 #define DEFAULTHOST  "localhost"
109 #define DEFAULTPORT  "4700"
110
111 struct server {
112     struct volinfo *volinfo;
113     pid_t pid;
114     time_t tm;                    /* When respawned last */
115     int count;                    /* Times respawned in the last TESTTIME secondes */
116     int control_fd;               /* file descriptor to child cnid_dbd process */
117 };
118
119 static struct server srv[MAXVOLS];
120
121 /* Default logging config: log to syslog with level log_note */
122 static char logconfig[MAXPATHLEN + 21 + 1] = "default log_note";
123
124 static void daemon_exit(int i)
125 {
126     server_unlock(_PATH_CNID_METAD_LOCK);
127     exit(i);
128 }
129
130 /* ------------------ */
131 static void sigterm_handler(int sig)
132 {
133     switch( sig ) {
134     case SIGTERM :
135         LOG(log_info, logtype_afpd, "shutting down on signal %d", sig );
136         break;
137     default :
138         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
139     }
140     daemon_exit(0);
141 }
142
143 static struct server *test_usockfn(struct volinfo *volinfo)
144 {
145     int i;
146     for (i = 0; i < maxvol; i++) {
147         if ((srv[i].volinfo) && (strcmp(srv[i].volinfo->v_path, volinfo->v_path) == 0)) {
148             return &srv[i];
149         }
150     }
151     return NULL;
152 }
153
154 /* -------------------- */
155 static int maybe_start_dbd(char *dbdpn, struct volinfo *volinfo)
156 {
157     pid_t pid;
158     struct server *up;
159     int sv[2];
160     int i;
161     time_t t;
162     char buf1[8];
163     char buf2[8];
164     char *volpath = volinfo->v_path;
165
166     LOG(log_debug, logtype_cnid, "maybe_start_dbd: Volume: \"%s\"", volpath);
167
168     up = test_usockfn(volinfo);
169     if (up && up->pid) {
170         /* we already have a process, send our fd */
171         if (send_fd(up->control_fd, rqstfd) < 0) {
172             /* FIXME */
173             return -1;
174         }
175         return 0;
176     }
177
178     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: no cnid_dbd for that volume yet");
179
180     time(&t);
181     if (!up) {
182         /* find an empty slot (i < maxvol) or the first free slot (i == maxvol)*/
183         for (i = 0; i <= maxvol; i++) {
184             if (srv[i].volinfo == NULL && i < MAXVOLS) {
185                 up = &srv[i];
186                 up->volinfo = volinfo;
187                 retainvolinfo(volinfo);
188                 up->tm = t;
189                 up->count = 0;
190                 if (i == maxvol)
191                     maxvol++;
192                 break;
193             }
194         }
195         if (!up) {
196             LOG(log_error, logtype_cnid, "no free slot for cnid_dbd child. Configured maximum: %d. Do you have so many volumes?", MAXVOLS);
197             return -1;
198         }
199     } else {
200         /* we have a slot but no process, check for respawn too fast */
201         if ( (t < (up->tm + TESTTIME)) /* We're in the respawn time window */
202              &&
203              (up->count > MAXSPAWN) ) { /* ...and already tried to fork too often */
204             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn too fast just exiting");
205             return -1; /* just exit, dont sleep, because we might have work to do for another client  */
206         }
207         if ( t >= (up->tm + TESTTIME) ) { /* out of respawn too fast windows reset the count */
208             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn window ended");
209             up->tm = t;
210             up->count = 0;
211         }
212         up->count++;
213         LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn count now is: %u", up->count);
214         if (up->count > MAXSPAWN) {
215             /* We spawned too fast. From now until the first time we tried + TESTTIME seconds
216                we will just return -1 above */
217             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: reached MAXSPAWN threshhold");
218         }
219     }
220
221     /* 
222        Create socketpair for comm between parent and child.
223        We use it to pass fds from connecting afpd processes to our
224        cnid_dbd child via fd passing.
225     */
226     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
227         LOG(log_error, logtype_cnid, "error in socketpair: %s", strerror(errno));
228         return -1;
229     }
230
231     if ((pid = fork()) < 0) {
232         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
233         return -1;
234     }
235     if (pid == 0) {
236         int ret;
237         /*
238          *  Child. Close descriptors and start the daemon. If it fails
239          *  just log it. The client process will fail connecting
240          *  afterwards anyway.
241          */
242
243         close(srvfd);
244         close(sv[0]);
245
246         for (i = 0; i < MAXVOLS; i++) {
247             if (srv[i].pid && up != &srv[i]) {
248                 close(srv[i].control_fd);
249             }
250         }
251
252         sprintf(buf1, "%i", sv[1]);
253         sprintf(buf2, "%i", rqstfd);
254
255         if (up->count == MAXSPAWN) {
256             /* there's a pb with the db inform child
257              * it will run recover, delete the db whatever
258              */
259             LOG(log_error, logtype_cnid, "try with -d %s", up->volinfo->v_path);
260             ret = execlp(dbdpn, dbdpn, "-d", volpath, buf1, buf2, logconfig, NULL);
261         }
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, "ds:p:h:u:g:l:f:")) != -1 ) {
455         switch (cc) {
456         case 'd':
457             debug = 1;
458             break;
459         case 'h':
460             host = strdup(optarg);
461             break;
462         case 'u':
463             uid = user_to_uid (optarg);
464             if (!uid) {
465                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
466                 err++;
467             }
468             break;
469         case 'g':
470             gid =group_to_gid (optarg);
471             if (!gid) {
472                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
473                 err++;
474             }
475             break;
476         case 'p':
477             port = strdup(optarg);
478             break;
479         case 's':
480             dbdpn = strdup(optarg);
481             break;
482         case 'l':
483             loglevel = strdup(optarg);
484             break;
485         case 'f':
486             logfile = strdup(optarg);
487             break;
488         default:
489             err++;
490             break;
491         }
492     }
493
494     if (loglevel) {
495         strlcpy(logconfig + 8, loglevel, 13);
496         free(loglevel);
497         strcat(logconfig, " ");
498     }
499     if (logfile) {
500         strlcat(logconfig, logfile, MAXPATHLEN);
501         free(logfile);
502     }
503     setuplog(logconfig);
504
505     if (err) {
506         LOG(log_error, logtype_cnid, "main: bad arguments");
507         daemon_exit(1);
508     }
509
510     (void)setlimits();
511
512     /* Check PID lockfile and become a daemon */
513     switch(server_lock("cnid_metad", _PATH_CNID_METAD_LOCK, debug)) {
514     case -1: /* error */
515         daemon_exit(EXITERR_SYS);
516     case 0: /* child */
517         break;
518     default: /* server */
519         exit(0);
520     }
521
522     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
523         daemon_exit(1);
524
525     /* switch uid/gid */
526     if (uid || gid) {
527         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
528         if (gid) {
529             if (SWITCH_TO_GID(gid) < 0) {
530                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
531                 daemon_exit(1);
532             }
533         }
534         if (uid) {
535             if (SWITCH_TO_UID(uid) < 0) {
536                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
537                 daemon_exit(1);
538             }
539         }
540     }
541
542     set_signal();
543
544     sigemptyset(&set);
545     sigprocmask(SIG_SETMASK, NULL, &set);
546     sigdelset(&set, SIGCHLD);
547
548     while (1) {
549         rqstfd = usockfd_check(srvfd, &set);
550         /* Collect zombie processes and log what happened to them */
551         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
552             for (i = 0; i < maxvol; i++) {
553                 if (srv[i].pid == pid) {
554                     srv[i].pid = 0;
555                     close(srv[i].control_fd);
556                     break;
557                 }
558             }
559             if (WIFEXITED(status)) {
560                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
561                     pid, WEXITSTATUS(status));
562             }
563             else if (WIFSIGNALED(status)) {
564                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with 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         /* Load .volinfo file */
607         if ((volinfo = allocvolinfo(volpath)) == NULL) {
608             LOG(log_severe, logtype_cnid, "allocvolinfo(\"%s\"): %s",
609                 volpath, strerror(errno));
610             goto loop_end;
611         }
612
613         if (set_dbdir(volinfo->v_dbpath) < 0) {
614             goto loop_end;
615         }
616
617         maybe_start_dbd(dbdpn, volinfo);
618
619         (void)closevolinfo(volinfo);
620
621     loop_end:
622         close(rqstfd);
623     }
624 }