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