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