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