]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
cnid_metad don't drop the slot if it's outside the respawn window, reuse it
[netatalk.git] / etc / cnid_dbd / cnid_metad.c
1 /*
2  * $Id: cnid_metad.c,v 1.17 2009-10-18 18:25:13 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 #define __USE_GNU
36 #include <unistd.h>
37 #undef __USE_GNU
38 #endif /* HAVE_UNISTD_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
90 #else
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
96 #endif
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 alarmed = 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_alarm(int sig _U_) {
384     alarmed = 1;
385 }
386
387 /* ------------------ */
388 int main(int argc, char *argv[])
389 {
390     char  dbdir[MAXPATHLEN + 1];
391     int   len, actual_len;
392     pid_t pid;
393     int   status;
394     char  *dbdpn = _PATH_CNID_DBD;
395     char  *host = DEFAULTHOST;
396     u_int16_t   port = DEFAULTPORT;
397     struct db_param *dbp;
398     int    i;
399     int    cc;
400     uid_t  uid = 0;
401     gid_t  gid = 0;
402     int    err = 0;
403     int    debug = 0;
404     int    ret;
405     char   *loglevel = NULL;
406     char   *logfile  = NULL;
407
408     set_processname("cnid_metad");
409
410     while (( cc = getopt( argc, argv, "ds:p:h:u:g:l:f:")) != -1 ) {
411         switch (cc) {
412         case 'd':
413             debug = 1;
414             break;
415         case 'h':
416             host = strdup(optarg);
417             break;
418         case 'u':
419             uid = user_to_uid (optarg);
420             if (!uid) {
421                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
422                 err++;
423             }
424             break;
425         case 'g':
426             gid =group_to_gid (optarg);
427             if (!gid) {
428                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
429                 err++;
430             }
431             break;
432         case 'p':
433             port = atoi(optarg);
434             break;
435         case 's':
436             dbdpn = strdup(optarg);
437             break;
438         case 'l':
439             loglevel = strdup(optarg);
440             break;
441         case 'f':
442             logfile = strdup(optarg);
443             break;
444         default:
445             err++;
446             break;
447         }
448     }
449
450     if (loglevel) {
451         strlcpy(logconfig + 8, loglevel, 13);
452         free(loglevel);
453         strcat(logconfig, " ");
454     }
455     if (logfile) {
456         strlcat(logconfig, logfile, MAXPATHLEN);
457         free(logfile);
458     }
459     setuplog(logconfig);
460
461     if (err) {
462         LOG(log_error, logtype_cnid, "main: bad arguments");
463         exit(1);
464     }
465
466     if (!debug) {
467
468         switch (fork()) {
469         case 0 :
470             fclose(stdin);
471             fclose(stdout);
472             fclose(stderr);
473
474 #ifdef TIOCNOTTY
475             {
476                 int i;
477                 if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
478                     (void)ioctl( i, TIOCNOTTY, 0 );
479                     setpgid( 0, getpid());
480                     (void) close(i);
481                 }
482             }
483 #else
484             setpgid( 0, getpid());
485 #endif
486             break;
487         case -1 :  /* error */
488             LOG(log_error, logtype_cnid, "detach from terminal: %s", strerror(errno));
489             exit(1);
490         default :  /* server */
491             exit(0);
492         }
493     }
494
495     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
496         exit(1);
497
498     /* switch uid/gid */
499     if (uid || gid) {
500         LOG(log_info, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
501         if (gid) {
502             if (SWITCH_TO_GID(gid) < 0) {
503                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
504                 exit(1);
505             }
506         }
507         if (uid) {
508             if (SWITCH_TO_UID(uid) < 0) {
509                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
510                 exit(1);
511             }
512         }
513     }
514
515     signal(SIGPIPE, SIG_IGN);
516     signal(SIGALRM, catch_alarm);
517
518     while (1) {
519         rqstfd = usockfd_check(srvfd, 10000000);
520         /* Collect zombie processes and log what happened to them */
521         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
522             for (i = 0; i < MAXVOLS; i++) {
523                 if (srv[i].pid == pid) {
524                     srv[i].pid = 0;
525                     close(srv[i].control_fd);
526                     break;
527                 }
528             }
529             if (WIFEXITED(status)) {
530                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i",
531                     pid, WEXITSTATUS(status));
532             }
533             else if (WIFSIGNALED(status)) {
534                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i",
535                     pid, WTERMSIG(status));
536             }
537             /* FIXME should */
538
539         }
540         if (rqstfd <= 0)
541             continue;
542
543         /* TODO: Check out read errors, broken pipe etc. in libatalk. Is
544            SIGIPE ignored there? Answer: Ignored for dsi, but not for asp ... */
545         alarm(5); /* to prevent read from getting stuck */
546         ret = read(rqstfd, &len, sizeof(int));
547         alarm(0);
548         if (alarmed) {
549             alarmed = 0;
550             LOG(log_severe, logtype_cnid, "Read(1) bailed with alarm (timeout)");
551             goto loop_end;
552         }
553
554         if (!ret) {
555             /* already close */
556             goto loop_end;
557         }
558         else if (ret < 0) {
559             LOG(log_error, logtype_cnid, "error read: %s", strerror(errno));
560             goto loop_end;
561         }
562         else if (ret != sizeof(int)) {
563             LOG(log_error, logtype_cnid, "short read: got %d", ret);
564             goto loop_end;
565         }
566         /*
567          *  checks for buffer overruns. The client libatalk side does it too
568          *  before handing the dir path over but who trusts clients?
569          */
570         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
571             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
572             goto loop_end;
573         }
574
575         alarm(5);
576         actual_len = read(rqstfd, dbdir, len);
577         alarm(0);
578         if (alarmed) {
579             alarmed = 0;
580             LOG(log_severe, logtype_cnid, "Read(2) bailed with alarm (timeout)");
581             goto loop_end;
582         }
583         if (actual_len != len) {
584             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
585             goto loop_end;
586         }
587         dbdir[len] = '\0';
588
589         if (set_dbdir(dbdir, len) < 0) {
590             goto loop_end;
591         }
592
593         if ((dbp = db_param_read(dbdir, METAD)) == NULL) {
594             LOG(log_error, logtype_cnid, "Error reading config file");
595             goto loop_end;
596         }
597         maybe_start_dbd(dbdpn, dbdir, dbp->usock_file);
598
599     loop_end:
600         close(rqstfd);
601     }
602 }