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