]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
Remove PID file on exit
[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         if (ret < 0) {
323             LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
324             daemon_exit(0);
325         }
326     }
327     /*
328      *  Parent.
329      */
330     up->pid = pid;
331     close(sv[1]);
332     up->control_fd = sv[0];
333     return 0;
334 }
335
336 /* ------------------ */
337 static int set_dbdir(char *dbdir, int len)
338 {
339     struct stat st;
340
341     if (!len)
342         return -1;
343
344     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
345         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
346         return -1;
347     }
348
349     if (dbdir[len - 1] != '/') {
350         strcat(dbdir, "/");
351         len++;
352     }
353     strcpy(dbdir + len, DBHOME);
354     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
355         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
356         return -1;
357     }
358     return 0;
359 }
360
361 /* ------------------ */
362 static uid_t user_to_uid (char *username)
363 {
364     struct passwd *this_passwd;
365
366     /* check for anything */
367     if ( !username || strlen ( username ) < 1 ) return 0;
368
369     /* grab the /etc/passwd record relating to username */
370     this_passwd = getpwnam ( username );
371
372     /* return false if there is no structure returned */
373     if (this_passwd == NULL) return 0;
374
375     /* return proper uid */
376     return this_passwd->pw_uid;
377
378 }
379
380 /* ------------------ */
381 static gid_t group_to_gid ( char *group)
382 {
383     struct group *this_group;
384
385     /* check for anything */
386     if ( !group || strlen ( group ) < 1 ) return 0;
387
388     /* grab the /etc/groups record relating to group */
389     this_group = getgrnam ( group );
390
391     /* return false if there is no structure returned */
392     if (this_group == NULL) return 0;
393
394     /* return proper gid */
395     return this_group->gr_gid;
396
397 }
398
399 /* ------------------ */
400 static void catch_child(int sig _U_) 
401 {
402     sigchild = 1;
403 }
404
405 /* ----------------------- */
406 static void set_signal(void)
407 {
408     struct sigaction sv;
409     sigset_t set;
410
411     memset(&sv, 0, sizeof(sv));
412
413     /* Catch SIGCHLD */
414     sv.sa_handler = catch_child;
415     sv.sa_flags = SA_NOCLDSTOP;
416     sigemptyset(&sv.sa_mask);
417     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
418         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
419         daemon_exit(EXITERR_SYS);
420     }
421
422     /* Catch SIGTERM */
423     sv.sa_handler = sigterm_handler;
424     sigfillset(&sv.sa_mask );
425     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
426         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
427         daemon_exit(EXITERR_SYS);
428     }
429
430     /* Ignore the rest */
431     sv.sa_handler = SIG_IGN;
432     sigemptyset(&sv.sa_mask );
433     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
434         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
435         daemon_exit(EXITERR_SYS);
436     }
437     sv.sa_handler = SIG_IGN;
438     sigemptyset(&sv.sa_mask );
439     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
440         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
441         daemon_exit(EXITERR_SYS);
442     }
443     sv.sa_handler = SIG_IGN;
444     sigemptyset(&sv.sa_mask );
445     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
446         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
447         daemon_exit(EXITERR_SYS);
448     }
449     sv.sa_handler = SIG_IGN;
450     sigemptyset(&sv.sa_mask );
451     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
452         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
453         daemon_exit(EXITERR_SYS);
454     }
455     sv.sa_handler = SIG_IGN;
456     sigemptyset(&sv.sa_mask );
457     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
458         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
459         daemon_exit(EXITERR_SYS);
460     }
461
462     /* block everywhere but in pselect */
463     sigemptyset(&set);
464     sigaddset(&set, SIGCHLD);
465     sigprocmask(SIG_BLOCK, &set, NULL);
466 }
467
468 /* ------------------ */
469 int main(int argc, char *argv[])
470 {
471     char  dbdir[MAXPATHLEN + 1];
472     int   len, actual_len;
473     pid_t pid;
474     int   status;
475     char  *dbdpn = _PATH_CNID_DBD;
476     char  *host = DEFAULTHOST;
477     char  *port = DEFAULTPORT;
478     struct db_param *dbp;
479     int    i;
480     int    cc;
481     uid_t  uid = 0;
482     gid_t  gid = 0;
483     int    err = 0;
484     int    debug = 0;
485     int    ret;
486     char   *loglevel = NULL;
487     char   *logfile  = NULL;
488     sigset_t set;
489
490     set_processname("cnid_metad");
491
492     while (( cc = getopt( argc, argv, "ds:p:h:u:g:l:f:")) != -1 ) {
493         switch (cc) {
494         case 'd':
495             debug = 1;
496             break;
497         case 'h':
498             host = strdup(optarg);
499             break;
500         case 'u':
501             uid = user_to_uid (optarg);
502             if (!uid) {
503                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
504                 err++;
505             }
506             break;
507         case 'g':
508             gid =group_to_gid (optarg);
509             if (!gid) {
510                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
511                 err++;
512             }
513             break;
514         case 'p':
515             port = strdup(optarg);
516             break;
517         case 's':
518             dbdpn = strdup(optarg);
519             break;
520         case 'l':
521             loglevel = strdup(optarg);
522             break;
523         case 'f':
524             logfile = strdup(optarg);
525             break;
526         default:
527             err++;
528             break;
529         }
530     }
531
532     if (loglevel) {
533         strlcpy(logconfig + 8, loglevel, 13);
534         free(loglevel);
535         strcat(logconfig, " ");
536     }
537     if (logfile) {
538         strlcat(logconfig, logfile, MAXPATHLEN);
539         free(logfile);
540     }
541     setuplog(logconfig);
542
543     if (err) {
544         LOG(log_error, logtype_cnid, "main: bad arguments");
545         daemon_exit(1);
546     }
547
548     /* Check PID lockfile and become a daemon */
549     switch(server_lock("cnid_metad", _PATH_CNID_METAD_LOCK, 0)) {
550     case -1: /* error */
551         daemon_exit(EXITERR_SYS);
552     case 0: /* child */
553         break;
554     default: /* server */
555         exit(0);
556     }
557
558     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
559         daemon_exit(1);
560
561     /* switch uid/gid */
562     if (uid || gid) {
563         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
564         if (gid) {
565             if (SWITCH_TO_GID(gid) < 0) {
566                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
567                 daemon_exit(1);
568             }
569         }
570         if (uid) {
571             if (SWITCH_TO_UID(uid) < 0) {
572                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
573                 daemon_exit(1);
574             }
575         }
576     }
577
578     set_signal();
579
580     sigemptyset(&set);
581     sigprocmask(SIG_SETMASK, NULL, &set);
582     sigdelset(&set, SIGCHLD);
583
584     while (1) {
585         rqstfd = usockfd_check(srvfd, &set);
586         /* Collect zombie processes and log what happened to them */
587         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
588             for (i = 0; i < MAXVOLS; i++) {
589                 if (srv[i].pid == pid) {
590                     srv[i].pid = 0;
591                     close(srv[i].control_fd);
592                     break;
593                 }
594             }
595             if (WIFEXITED(status)) {
596                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
597                     pid, WEXITSTATUS(status));
598             }
599             else if (WIFSIGNALED(status)) {
600                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i",
601                     pid, WTERMSIG(status));
602             }
603             sigchild = 0;
604         }
605         if (rqstfd <= 0)
606             continue;
607
608         /* TODO: Check out read errors, broken pipe etc. in libatalk. Is
609            SIGIPE ignored there? Answer: Ignored for dsi, but not for asp ... */
610         ret = read(rqstfd, &len, sizeof(int));
611         if (!ret) {
612             /* already close */
613             goto loop_end;
614         }
615         else if (ret < 0) {
616             LOG(log_severe, logtype_cnid, "error read: %s", strerror(errno));
617             goto loop_end;
618         }
619         else if (ret != sizeof(int)) {
620             LOG(log_error, logtype_cnid, "short read: got %d", ret);
621             goto loop_end;
622         }
623         /*
624          *  checks for buffer overruns. The client libatalk side does it too
625          *  before handing the dir path over but who trusts clients?
626          */
627         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
628             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
629             goto loop_end;
630         }
631
632         actual_len = read(rqstfd, dbdir, len);
633         if (actual_len < 0) {
634             LOG(log_severe, logtype_cnid, "Read(2) error : %s", strerror(errno));
635             goto loop_end;
636         }
637         if (actual_len != len) {
638             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
639             goto loop_end;
640         }
641         dbdir[len] = '\0';
642
643         if (set_dbdir(dbdir, len) < 0) {
644             goto loop_end;
645         }
646
647         if ((dbp = db_param_read(dbdir, METAD)) == NULL) {
648             LOG(log_error, logtype_cnid, "Error reading config file");
649             goto loop_end;
650         }
651         maybe_start_dbd(dbdpn, dbdir, dbp->usock_file);
652
653     loop_end:
654         close(rqstfd);
655     }
656 }