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