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