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