]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
ms, not us stupid
[netatalk.git] / etc / cnid_dbd / cnid_metad.c
1 /*
2  * $Id: cnid_metad.c,v 1.22 2009-11-16 02:04:47 didg Exp $
3  *
4  * Copyright (C) Joerg Lenneis 2003
5  * All Rights Reserved.  See COPYING.
6  *
7  */
8
9 /* 
10    cnid_dbd metadaemon to start up cnid_dbd upon request from afpd.
11    Here is how it works:
12    
13                        via TCP socket
14    1.       afpd          ------->        cnid_metad
15
16                    via UNIX domain socket
17    2.   cnid_metad        ------->         cnid_dbd
18
19                     passes afpd client fd
20    3.   cnid_metad        ------->         cnid_dbd
21
22    Result:
23                        via TCP socket
24    4.       afpd          ------->         cnid_dbd
25  */
26
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif /* HAVE_CONFIG_H */
31
32 #include <unistd.h>
33 #undef __USE_GNU
34
35 #include <stdlib.h>
36 #include <sys/param.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <signal.h>
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 #ifdef HAVE_SYS_TIME_H
44 #include <sys/time.h>
45 #endif
46 #ifdef HAVE_SYS_WAIT_H
47 #include <sys/wait.h>
48 #endif
49 #ifdef HAVE_SYS_UIO_H
50 #include <sys/uio.h>
51 #endif
52 #include <sys/un.h>
53 #define _XPG4_2 1
54 #include <sys/socket.h>
55 #include <stdio.h>
56 #include <time.h>
57 #include <sys/ioctl.h>
58
59 #ifndef WEXITSTATUS
60 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
61 #endif /* ! WEXITSTATUS */
62 #ifndef WIFEXITED
63 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
64 #endif /* ! WIFEXITED */
65 #ifndef WIFSTOPPED
66 #define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
67 #endif
68
69 #ifndef WIFSIGNALED
70 #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
71 #endif
72 #ifndef WTERMSIG
73 #define WTERMSIG(status)      ((status) & 0x7f)
74 #endif
75
76 /* functions for username and group */
77 #include <pwd.h>
78 #include <grp.h>
79
80 /* FIXME */
81 #ifdef linux
82 #ifndef USE_SETRESUID
83 #define USE_SETRESUID 1
84 #define SWITCH_TO_GID(gid)  ((setresgid(gid,gid,gid) < 0 || setgid(gid) < 0) ? -1 : 0)
85 #define SWITCH_TO_UID(uid)  ((setresuid(uid,uid,uid) < 0 || setuid(uid) < 0) ? -1 : 0)
86 #endif  /* USE_SETRESUID */
87 #else   /* ! linux */
88 #ifndef USE_SETEUID
89 #define USE_SETEUID 1
90 #define SWITCH_TO_GID(gid)  ((setegid(gid) < 0 || setgid(gid) < 0) ? -1 : 0)
91 #define SWITCH_TO_UID(uid)  ((setuid(uid) < 0 || seteuid(uid) < 0 || setuid(uid) < 0) ? -1 : 0)
92 #endif  /* USE_SETEUID */
93 #endif  /* linux */
94
95 #include <atalk/util.h>
96 #include <atalk/logger.h>
97 #include <atalk/cnid_dbd_private.h>
98 #include <atalk/paths.h>
99
100 #include "db_param.h"
101 #include "usockfd.h"
102
103 #define DBHOME        ".AppleDB"
104 #define DBHOMELEN    8
105
106 static int srvfd;
107 static int rqstfd;
108 static volatile sig_atomic_t sigchild = 0;
109
110 #define MAXSPAWN   3                   /* Max times respawned in.. */
111 #define TESTTIME   42                  /* this much seconds apfd client tries to  *
112                                         * to reconnect every 5 secondes, catch it */
113 #define MAXVOLS    512
114 #define DEFAULTHOST  "localhost"
115 #define DEFAULTPORT  "4700"
116
117 struct server {
118     char  *name;
119     pid_t pid;
120     time_t tm;                    /* When respawned last */
121     int count;                    /* Times respawned in the last TESTTIME secondes */
122     int control_fd;               /* file descriptor to child cnid_dbd process */
123 };
124
125 static struct server srv[MAXVOLS];
126
127 /* Default logging config: log to syslog with level log_note */
128 static char logconfig[MAXPATHLEN + 21 + 1] = "default log_note";
129
130 static void daemon_exit(int i)
131 {
132     server_unlock(_PATH_CNID_METAD_LOCK);
133     exit(i);
134 }
135
136 /* ------------------ */
137 static void sigterm_handler(int sig)
138 {
139     switch( sig ) {
140     case SIGTERM :
141         LOG(log_info, logtype_afpd, "shutting down on signal %d", sig );
142         break;
143     default :
144         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
145     }
146     daemon_exit(0);
147 }
148
149 static struct server *test_usockfn(char *dir)
150 {
151     int i;
152     for (i = 0; i < MAXVOLS; i++) {
153         if (srv[i].name && !strcmp(srv[i].name, dir)) {
154             return &srv[i];
155         }
156     }
157     return NULL;
158 }
159
160 /* -------------------- */
161 static int send_cred(int socket, int fd)
162 {
163     int ret;
164     struct msghdr msgh;
165     struct iovec iov[1];
166     struct cmsghdr *cmsgp = NULL;
167     char *buf;
168     size_t size;
169     int er=0;
170
171     size = CMSG_SPACE(sizeof fd);
172     buf = malloc(size);
173     if (!buf) {
174         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
175         return -1;
176     }
177
178     memset(&msgh,0,sizeof (msgh));
179     memset(buf,0, size);
180
181     msgh.msg_name = NULL;
182     msgh.msg_namelen = 0;
183
184     msgh.msg_iov = iov;
185     msgh.msg_iovlen = 1;
186
187     iov[0].iov_base = &er;
188     iov[0].iov_len = sizeof(er);
189
190     msgh.msg_control = buf;
191     msgh.msg_controllen = size;
192
193     cmsgp = CMSG_FIRSTHDR(&msgh);
194     cmsgp->cmsg_level = SOL_SOCKET;
195     cmsgp->cmsg_type = SCM_RIGHTS;
196     cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
197
198     *((int *)CMSG_DATA(cmsgp)) = fd;
199     msgh.msg_controllen = cmsgp->cmsg_len;
200
201     do  {
202         ret = sendmsg(socket,&msgh, 0);
203     } while ( ret == -1 && errno == EINTR );
204     if (ret == -1) {
205         LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
206         free(buf);
207         return -1;
208     }
209     free(buf);
210     return 0;
211 }
212
213 /* -------------------- */
214 static int maybe_start_dbd(char *dbdpn, char *dbdir, char *usockfn)
215 {
216     pid_t pid;
217     struct server *up;
218     int sv[2];
219     int i;
220     time_t t;
221     char buf1[8];
222     char buf2[8];
223
224     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: dbdir: '%s', UNIX socket file: '%s'", 
225         dbdir, usockfn);
226
227     up = test_usockfn(dbdir);
228     if (up && up->pid) {
229         /* we already have a process, send our fd */
230         if (send_cred(up->control_fd, rqstfd) < 0) {
231             /* FIXME */
232             return -1;
233         }
234         return 0;
235     }
236
237     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: no cnid_dbd for that volume yet. Starting one ...");
238
239     time(&t);
240     if (!up) {
241         /* find an empty slot */
242         for (i = 0; i < MAXVOLS; i++) {
243             if ( !srv[i].name ) {
244                 up = &srv[i];
245                 up->tm = t;
246                 up->count = 0;
247                 up->name = strdup(dbdir);
248                 break;
249             }
250         }
251         if (!up) {
252             LOG(log_error, logtype_cnid, "no free slot for cnid_dbd child. Configured maximum: %d. Do you have so many volumes?", MAXVOLS);
253             return -1;
254         }
255     }
256     else {
257         /* we have a slot but no process, check for respawn too fast */
258         if ( (t < (up->tm + TESTTIME)) /* We're in the respawn time window */
259              &&
260              (up->count > MAXSPAWN) ) { /* ...and already tried to fork too often */
261             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn too fast just exiting");
262             return -1; /* just exit, dont sleep, because we might have work to do for another client  */
263         }
264         if ( t >= (up->tm + TESTTIME) ) { /* out of respawn too fast windows reset the count */
265             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn window ended");
266             up->tm = t;
267             up->count = 0;
268         }
269         up->count++;
270         LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn count now is: %u", up->count);
271         if (up->count > MAXSPAWN) {
272             /* We spawned too fast. From now until the first time we tried + TESTTIME seconds
273                we will just return -1 above */
274             LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: reached MAXSPAWN threshhold");
275         }
276     }
277
278     /* 
279        Create socketpair for comm between parent and child.
280        We use it to pass fds from connecting afpd processes to our
281        cnid_dbd child via fd passing.
282     */
283     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
284         LOG(log_error, logtype_cnid, "error in socketpair: %s", strerror(errno));
285         return -1;
286     }
287
288     if ((pid = fork()) < 0) {
289         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
290         return -1;
291     }
292     if (pid == 0) {
293         int ret;
294         /*
295          *  Child. Close descriptors and start the daemon. If it fails
296          *  just log it. The client process will fail connecting
297          *  afterwards anyway.
298          */
299
300         close(srvfd);
301         close(sv[0]);
302
303         for (i = 0; i < MAXVOLS; i++) {
304             if (srv[i].pid && up != &srv[i]) {
305                 close(srv[i].control_fd);
306             }
307         }
308
309         sprintf(buf1, "%i", sv[1]);
310         sprintf(buf2, "%i", rqstfd);
311
312         if (up->count == MAXSPAWN) {
313             /* there's a pb with the db inform child
314              * it will run recover, delete the db whatever
315              */
316             LOG(log_error, logtype_cnid, "try with -d %s", up->name);
317             ret = execlp(dbdpn, dbdpn, "-d", dbdir, buf1, buf2, logconfig, NULL);
318         }
319         else {
320             ret = execlp(dbdpn, dbdpn, dbdir, buf1, buf2, logconfig, NULL);
321         }
322         /* Yikes! We're still here, so exec failed... */
323         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
324         daemon_exit(0);
325     }
326     /*
327      *  Parent.
328      */
329     up->pid = pid;
330     close(sv[1]);
331     up->control_fd = sv[0];
332     return 0;
333 }
334
335 /* ------------------ */
336 static int set_dbdir(char *dbdir, int len)
337 {
338     struct stat st;
339
340     if (!len)
341         return -1;
342
343     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
344         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
345         return -1;
346     }
347
348     if (dbdir[len - 1] != '/') {
349         strcat(dbdir, "/");
350         len++;
351     }
352     strcpy(dbdir + len, DBHOME);
353     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
354         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
355         return -1;
356     }
357     return 0;
358 }
359
360 /* ------------------ */
361 static uid_t user_to_uid (char *username)
362 {
363     struct passwd *this_passwd;
364
365     /* check for anything */
366     if ( !username || strlen ( username ) < 1 ) return 0;
367
368     /* grab the /etc/passwd record relating to username */
369     this_passwd = getpwnam ( username );
370
371     /* return false if there is no structure returned */
372     if (this_passwd == NULL) return 0;
373
374     /* return proper uid */
375     return this_passwd->pw_uid;
376
377 }
378
379 /* ------------------ */
380 static gid_t group_to_gid ( char *group)
381 {
382     struct group *this_group;
383
384     /* check for anything */
385     if ( !group || strlen ( group ) < 1 ) return 0;
386
387     /* grab the /etc/groups record relating to group */
388     this_group = getgrnam ( group );
389
390     /* return false if there is no structure returned */
391     if (this_group == NULL) return 0;
392
393     /* return proper gid */
394     return this_group->gr_gid;
395
396 }
397
398 /* ------------------ */
399 static void catch_child(int sig _U_) 
400 {
401     sigchild = 1;
402 }
403
404 /* ----------------------- */
405 static void set_signal(void)
406 {
407     struct sigaction sv;
408     sigset_t set;
409
410     memset(&sv, 0, sizeof(sv));
411
412     /* Catch SIGCHLD */
413     sv.sa_handler = catch_child;
414     sv.sa_flags = SA_NOCLDSTOP;
415     sigemptyset(&sv.sa_mask);
416     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
417         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
418         daemon_exit(EXITERR_SYS);
419     }
420
421     /* Catch SIGTERM */
422     sv.sa_handler = sigterm_handler;
423     sigfillset(&sv.sa_mask );
424     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
425         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
426         daemon_exit(EXITERR_SYS);
427     }
428
429     /* Ignore the rest */
430     sv.sa_handler = SIG_IGN;
431     sigemptyset(&sv.sa_mask );
432     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
433         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
434         daemon_exit(EXITERR_SYS);
435     }
436     sv.sa_handler = SIG_IGN;
437     sigemptyset(&sv.sa_mask );
438     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
439         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
440         daemon_exit(EXITERR_SYS);
441     }
442     sv.sa_handler = SIG_IGN;
443     sigemptyset(&sv.sa_mask );
444     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
445         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
446         daemon_exit(EXITERR_SYS);
447     }
448     sv.sa_handler = SIG_IGN;
449     sigemptyset(&sv.sa_mask );
450     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
451         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
452         daemon_exit(EXITERR_SYS);
453     }
454     sv.sa_handler = SIG_IGN;
455     sigemptyset(&sv.sa_mask );
456     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
457         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
458         daemon_exit(EXITERR_SYS);
459     }
460
461     /* block everywhere but in pselect */
462     sigemptyset(&set);
463     sigaddset(&set, SIGCHLD);
464     sigprocmask(SIG_BLOCK, &set, NULL);
465 }
466
467 /* ------------------ */
468 int main(int argc, char *argv[])
469 {
470     char  dbdir[MAXPATHLEN + 1];
471     int   len, actual_len;
472     pid_t pid;
473     int   status;
474     char  *dbdpn = _PATH_CNID_DBD;
475     char  *host = DEFAULTHOST;
476     char  *port = DEFAULTPORT;
477     struct db_param *dbp;
478     int    i;
479     int    cc;
480     uid_t  uid = 0;
481     gid_t  gid = 0;
482     int    err = 0;
483     int    debug = 0;
484     int    ret;
485     char   *loglevel = NULL;
486     char   *logfile  = NULL;
487     sigset_t set;
488
489     set_processname("cnid_metad");
490
491     while (( cc = getopt( argc, argv, "ds:p:h:u:g:l:f:")) != -1 ) {
492         switch (cc) {
493         case 'd':
494             debug = 1;
495             break;
496         case 'h':
497             host = strdup(optarg);
498             break;
499         case 'u':
500             uid = user_to_uid (optarg);
501             if (!uid) {
502                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
503                 err++;
504             }
505             break;
506         case 'g':
507             gid =group_to_gid (optarg);
508             if (!gid) {
509                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
510                 err++;
511             }
512             break;
513         case 'p':
514             port = strdup(optarg);
515             break;
516         case 's':
517             dbdpn = strdup(optarg);
518             break;
519         case 'l':
520             loglevel = strdup(optarg);
521             break;
522         case 'f':
523             logfile = strdup(optarg);
524             break;
525         default:
526             err++;
527             break;
528         }
529     }
530
531     if (loglevel) {
532         strlcpy(logconfig + 8, loglevel, 13);
533         free(loglevel);
534         strcat(logconfig, " ");
535     }
536     if (logfile) {
537         strlcat(logconfig, logfile, MAXPATHLEN);
538         free(logfile);
539     }
540     setuplog(logconfig);
541
542     if (err) {
543         LOG(log_error, logtype_cnid, "main: bad arguments");
544         daemon_exit(1);
545     }
546
547     /* Check PID lockfile and become a daemon */
548     switch(server_lock("cnid_metad", _PATH_CNID_METAD_LOCK, 0)) {
549     case -1: /* error */
550         daemon_exit(EXITERR_SYS);
551     case 0: /* child */
552         break;
553     default: /* server */
554         exit(0);
555     }
556
557     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
558         daemon_exit(1);
559
560     /* switch uid/gid */
561     if (uid || gid) {
562         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
563         if (gid) {
564             if (SWITCH_TO_GID(gid) < 0) {
565                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
566                 daemon_exit(1);
567             }
568         }
569         if (uid) {
570             if (SWITCH_TO_UID(uid) < 0) {
571                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
572                 daemon_exit(1);
573             }
574         }
575     }
576
577     set_signal();
578
579     sigemptyset(&set);
580     sigprocmask(SIG_SETMASK, NULL, &set);
581     sigdelset(&set, SIGCHLD);
582
583     while (1) {
584         rqstfd = usockfd_check(srvfd, &set);
585         /* Collect zombie processes and log what happened to them */
586         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
587             for (i = 0; i < MAXVOLS; i++) {
588                 if (srv[i].pid == pid) {
589                     srv[i].pid = 0;
590                     close(srv[i].control_fd);
591                     break;
592                 }
593             }
594             if (WIFEXITED(status)) {
595                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
596                     pid, WEXITSTATUS(status));
597             }
598             else if (WIFSIGNALED(status)) {
599                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i",
600                     pid, WTERMSIG(status));
601             }
602             sigchild = 0;
603         }
604         if (rqstfd <= 0)
605             continue;
606
607         /* TODO: Check out read errors, broken pipe etc. in libatalk. Is
608            SIGIPE ignored there? Answer: Ignored for dsi, but not for asp ... */
609         ret = readt(rqstfd, &len, sizeof(int), 1, 5);
610         if (!ret) {
611             /* already close */
612             goto loop_end;
613         }
614         else if (ret < 0) {
615             LOG(log_severe, logtype_cnid, "error read: %s", strerror(errno));
616             goto loop_end;
617         }
618         else if (ret != sizeof(int)) {
619             LOG(log_error, logtype_cnid, "short read: got %d", ret);
620             goto loop_end;
621         }
622         /*
623          *  checks for buffer overruns. The client libatalk side does it too
624          *  before handing the dir path over but who trusts clients?
625          */
626         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
627             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
628             goto loop_end;
629         }
630
631         actual_len = read(rqstfd, dbdir, len);
632         if (actual_len < 0) {
633             LOG(log_severe, logtype_cnid, "Read(2) error : %s", strerror(errno));
634             goto loop_end;
635         }
636         if (actual_len != len) {
637             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
638             goto loop_end;
639         }
640         dbdir[len] = '\0';
641
642         if (set_dbdir(dbdir, len) < 0) {
643             goto loop_end;
644         }
645
646         if ((dbp = db_param_read(dbdir, METAD)) == NULL) {
647             LOG(log_error, logtype_cnid, "Error reading config file");
648             goto loop_end;
649         }
650         maybe_start_dbd(dbdpn, dbdir, dbp->usock_file);
651
652     loop_end:
653         close(rqstfd);
654     }
655 }