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