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