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