]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
Previous fix 9e4e07c1811edbaf3376ad6e238a1353b405002b resulted in the inability to...
[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
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, it will delete the db */
257             LOG(log_warning, logtype_cnid,
258                 "Multiple attempts to start CNID db daemon for \"%s\" failed, wiping the slate clean...",
259                 up->volinfo->v_path);
260             ret = execlp(dbdpn, dbdpn, "-d", volpath, buf1, buf2, logconfig, NULL);
261         } else {
262             ret = execlp(dbdpn, dbdpn, volpath, buf1, buf2, logconfig, NULL);
263         }
264         /* Yikes! We're still here, so exec failed... */
265         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
266         daemon_exit(0);
267     }
268     /*
269      *  Parent.
270      */
271     up->pid = pid;
272     close(sv[1]);
273     up->control_fd = sv[0];
274     return 0;
275 }
276
277 /* ------------------ */
278 static int set_dbdir(char *dbdir)
279 {
280     int len;
281     struct stat st;
282
283     len = strlen(dbdir);
284
285     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
286         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
287         return -1;
288     }
289
290     if (dbdir[len - 1] != '/') {
291         strcat(dbdir, "/");
292         len++;
293     }
294     strcpy(dbdir + len, DBHOME);
295     if (stat(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     return 0;
300 }
301
302 /* ------------------ */
303 static uid_t user_to_uid (char *username)
304 {
305     struct passwd *this_passwd;
306
307     /* check for anything */
308     if ( !username || strlen ( username ) < 1 ) return 0;
309
310     /* grab the /etc/passwd record relating to username */
311     this_passwd = getpwnam ( username );
312
313     /* return false if there is no structure returned */
314     if (this_passwd == NULL) return 0;
315
316     /* return proper uid */
317     return this_passwd->pw_uid;
318
319 }
320
321 /* ------------------ */
322 static gid_t group_to_gid ( char *group)
323 {
324     struct group *this_group;
325
326     /* check for anything */
327     if ( !group || strlen ( group ) < 1 ) return 0;
328
329     /* grab the /etc/groups record relating to group */
330     this_group = getgrnam ( group );
331
332     /* return false if there is no structure returned */
333     if (this_group == NULL) return 0;
334
335     /* return proper gid */
336     return this_group->gr_gid;
337
338 }
339
340 /* ------------------ */
341 static void catch_child(int sig _U_) 
342 {
343     sigchild = 1;
344 }
345
346 /* ----------------------- */
347 static void set_signal(void)
348 {
349     struct sigaction sv;
350     sigset_t set;
351
352     memset(&sv, 0, sizeof(sv));
353
354     /* Catch SIGCHLD */
355     sv.sa_handler = catch_child;
356     sv.sa_flags = SA_NOCLDSTOP;
357     sigemptyset(&sv.sa_mask);
358     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
359         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
360         daemon_exit(EXITERR_SYS);
361     }
362
363     /* Catch SIGTERM */
364     sv.sa_handler = sigterm_handler;
365     sigfillset(&sv.sa_mask );
366     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
367         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
368         daemon_exit(EXITERR_SYS);
369     }
370
371     /* Ignore the rest */
372     sv.sa_handler = SIG_IGN;
373     sigemptyset(&sv.sa_mask );
374     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
375         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
376         daemon_exit(EXITERR_SYS);
377     }
378     sv.sa_handler = SIG_IGN;
379     sigemptyset(&sv.sa_mask );
380     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
381         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
382         daemon_exit(EXITERR_SYS);
383     }
384     sv.sa_handler = SIG_IGN;
385     sigemptyset(&sv.sa_mask );
386     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
387         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
388         daemon_exit(EXITERR_SYS);
389     }
390     sv.sa_handler = SIG_IGN;
391     sigemptyset(&sv.sa_mask );
392     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
393         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
394         daemon_exit(EXITERR_SYS);
395     }
396     sv.sa_handler = SIG_IGN;
397     sigemptyset(&sv.sa_mask );
398     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
399         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
400         daemon_exit(EXITERR_SYS);
401     }
402
403     /* block everywhere but in pselect */
404     sigemptyset(&set);
405     sigaddset(&set, SIGCHLD);
406     sigprocmask(SIG_BLOCK, &set, NULL);
407 }
408
409 static int setlimits(void)
410 {
411     struct rlimit rlim;
412
413     if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
414         LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
415         exit(1);
416     }
417     if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < 65535) {
418         rlim.rlim_cur = 65535;
419         if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < 65535)
420             rlim.rlim_max = 65535;
421         if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
422             LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
423             exit(1);
424         }
425     }
426     return 0;
427 }
428
429 /* ------------------ */
430 int main(int argc, char *argv[])
431 {
432     char  volpath[MAXPATHLEN + 1];
433     int   len, actual_len;
434     pid_t pid;
435     int   status;
436     char  *dbdpn = _PATH_CNID_DBD;
437     char  *host = DEFAULTHOST;
438     char  *port = DEFAULTPORT;
439     int    i;
440     int    cc;
441     uid_t  uid = 0;
442     gid_t  gid = 0;
443     int    err = 0;
444     int    debug = 0;
445     int    ret;
446     char   *loglevel = NULL;
447     char   *logfile  = NULL;
448     sigset_t set;
449     struct volinfo *volinfo;
450
451     set_processname("cnid_metad");
452
453     while (( cc = getopt( argc, argv, "ds:p:h:u:g:l:f:")) != -1 ) {
454         switch (cc) {
455         case 'd':
456             debug = 1;
457             break;
458         case 'h':
459             host = strdup(optarg);
460             break;
461         case 'u':
462             uid = user_to_uid (optarg);
463             if (!uid) {
464                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
465                 err++;
466             }
467             break;
468         case 'g':
469             gid =group_to_gid (optarg);
470             if (!gid) {
471                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
472                 err++;
473             }
474             break;
475         case 'p':
476             port = strdup(optarg);
477             break;
478         case 's':
479             dbdpn = strdup(optarg);
480             break;
481         case 'l':
482             loglevel = strdup(optarg);
483             break;
484         case 'f':
485             logfile = strdup(optarg);
486             break;
487         default:
488             err++;
489             break;
490         }
491     }
492
493     /* Check for PID lockfile */
494     if (check_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
495         return -1;
496
497     if (!debug && daemonize(0, 0) != 0)
498         exit(EXITERR_SYS);
499
500     /* Create PID lockfile */
501     if (create_lockfile("cnid_metad", _PATH_CNID_METAD_LOCK))
502         return -1;
503
504     if (loglevel) {
505         strlcpy(logconfig + 8, loglevel, 13);
506         free(loglevel);
507         strcat(logconfig, " ");
508     }
509     if (logfile) {
510         strlcat(logconfig, logfile, MAXPATHLEN);
511         free(logfile);
512     }
513     setuplog(logconfig);
514
515     if (err) {
516         LOG(log_error, logtype_cnid, "main: bad arguments");
517         daemon_exit(1);
518     }
519
520     (void)setlimits();
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 }