]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
temporary fix, enable more clients for cnid_metad.
[netatalk.git] / etc / cnid_dbd / cnid_metad.c
1 /*
2  * $Id: cnid_metad.c,v 1.1.4.5 2003-11-18 12:32:46 didg Exp $
3  *
4  * Copyright (C) Joerg Lenneis 2003
5  * All Rights Reserved.  See COPYRIGHT.
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
44 #ifndef WEXITSTATUS 
45 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
46 #endif /* ! WEXITSTATUS */
47 #ifndef WIFEXITED
48 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
49 #endif /* ! WIFEXITED */
50 #ifndef WIFSTOPPED
51 #define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
52 #endif
53
54 #ifndef WIFSIGNALED
55 #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
56 #endif
57 #ifndef WTERMSIG
58 #define WTERMSIG(status)      ((status) & 0x7f)
59 #endif
60
61 #ifdef ATACC
62 #define fork aTaC_fork
63 #endif
64
65 /* functions for username and group */
66 #include <pwd.h>
67 #include <grp.h>
68
69 #include <atalk/logger.h>
70 #include <atalk/cnid_dbd_private.h>
71
72 #include "db_param.h"
73 #include "usockfd.h"
74
75 #define DBHOME        ".AppleDB"
76 #define DBHOMELEN    8      
77
78 static int srvfd;
79 static int rqstfd;
80
81 #define MAXSRV 128
82
83 #define MAXSPAWN   3                   /* Max times respawned in.. */
84 #define TESTTIME   20                  /* this much seconds */
85
86 struct server {
87     char  *name;
88     pid_t pid;
89     time_t tm;                    /* When respawned last */
90     int count;                    /* Times respawned in the last TESTTIME secondes */
91     int   sv[2];
92 };
93
94 static struct server srv[MAXSRV +1];
95
96 static struct server *test_usockfn(char *dir, char *fn)
97 {
98 int i;
99     for (i = 1; i <= MAXSRV; i++) {
100         if (srv[i].name && !strcmp(srv[i].name, dir)) {
101             return &srv[i];
102         }
103     }
104     return NULL;
105 }
106
107 /* -------------------- */
108 static int send_cred(int socket, int fd)
109 {
110    int ret;
111    struct msghdr msgh; 
112    struct iovec iov[1];
113    struct cmsghdr *cmsgp = NULL;
114    char buf[CMSG_SPACE(sizeof fd)];
115    int er=0;
116
117    memset(&msgh,0,sizeof (msgh));
118    memset(buf,0,sizeof (buf));
119
120    msgh.msg_name = NULL;
121    msgh.msg_namelen = 0;
122
123    msgh.msg_iov = iov;
124    msgh.msg_iovlen = 1;
125
126    iov[0].iov_base = &er;
127    iov[0].iov_len = sizeof(er);
128
129    msgh.msg_control = buf;
130    msgh.msg_controllen = sizeof(buf);
131
132    cmsgp = CMSG_FIRSTHDR(&msgh);
133    cmsgp->cmsg_level = SOL_SOCKET;
134    cmsgp->cmsg_type = SCM_RIGHTS;
135    cmsgp->cmsg_len = CMSG_LEN(sizeof(fd));
136
137    *((int *)CMSG_DATA(cmsgp)) = fd;
138    msgh.msg_controllen = cmsgp->cmsg_len;
139
140    do  {
141        ret = sendmsg(socket,&msgh, 0);
142    } while ( ret == -1 && errno == EINTR );
143    if (ret == -1) {
144        LOG(log_error, logtype_cnid, "error in sendmsg: %s", strerror(errno));
145        return -1;
146    }
147    return 0;
148 }
149
150 /* -------------------- */
151 static int maybe_start_dbd(char *dbdpn, char *dbdir, char *usockfn)
152 {
153     pid_t pid;
154     struct server *up;
155     int i;
156     time_t t;
157
158     up = test_usockfn(dbdir, usockfn);
159     if (up && up->pid) {
160        /* we already have a process, send our fd */
161        if (send_cred(up->sv[0], rqstfd) < 0) {
162            /* FIXME */
163            return -1;
164        }
165        return 0;
166     }
167
168     time(&t);
169     if (!up) {
170         /* find an empty slot */
171         for (i = 1; i <= MAXSRV; i++) {
172             if (!srv[i].pid && srv[i].tm + TESTTIME < t) {
173                 up = &srv[i];
174                 free(up->name);
175                 up->tm = t;
176                 up->count = 0;
177                 /* copy name */
178                 up->name = strdup(dbdir);
179                 break;
180             }
181         }
182         if (!up) {
183             LOG(log_error, logtype_cnid, "no free slot");
184             return -1;
185         }
186     }
187     else {
188         /* we have a slot but no process, check for respawn too fast */
189         if (up->tm + TESTTIME > t) {
190             up->count++;
191         } else {
192             up->count = 0;
193             up->tm = t;
194         }
195         if (up->count >= MAXSPAWN) {
196             up->tm = t;
197             LOG(log_error, logtype_cnid, "respawn too fast %s", up->name);
198             /* FIXME should we sleep a little ? */
199             return -1;
200         }
201         
202     }
203     /* create socketpair for comm between parent and child 
204      * FIXME Do we really need a permanent pipe between them ?
205      */
206     if (socketpair(PF_UNIX, SOCK_STREAM, 0, up->sv) < 0) {
207         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
208         return -1;
209     }
210         
211     if ((pid = fork()) < 0) {
212         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
213         return -1;
214     }    
215     if (pid == 0) {
216         /*
217          *  Child. Close descriptors and start the daemon. If it fails
218          *  just log it. The client process will fail connecting
219          *  afterwards anyway.
220          */
221         close(0);
222         close(1);
223         close(srvfd);
224         dup2(up->sv[1], 0);
225         dup2(rqstfd, 1);
226
227         close(up->sv[0]);
228         close(up->sv[1]);
229         close(rqstfd);
230         if (execlp(dbdpn, dbdpn, dbdir, NULL) < 0) {
231             LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
232             exit(0);
233         }
234     }
235     /*
236      *  Parent.
237      */
238     up->pid = pid;
239     return 0;
240 }
241
242 /* ------------------ */
243 static int set_dbdir(char *dbdir, int len)
244 {
245    struct stat st;
246
247     if (!len)
248         return -1;
249
250     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
251         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
252         return -1;
253     }
254
255     if (dbdir[len - 1] != '/') {
256          strcat(dbdir, "/");
257          len++;
258     }
259     strcpy(dbdir + len, DBHOME);
260     if (stat(dbdir, &st) < 0 && mkdir(dbdir, 0755 ) < 0) {
261         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
262         return -1;
263     }
264     return 0;   
265 }
266
267 /* ------------------ */
268 uid_t user_to_uid ( username )
269 char    *username;
270 {
271     struct passwd *this_passwd;
272  
273     /* check for anything */
274     if ( !username || strlen ( username ) < 1 ) return 0;
275  
276     /* grab the /etc/passwd record relating to username */
277     this_passwd = getpwnam ( username );
278  
279     /* return false if there is no structure returned */
280     if (this_passwd == NULL) return 0;
281  
282     /* return proper uid */
283     return this_passwd->pw_uid;
284  
285
286
287 /* ------------------ */
288 gid_t group_to_gid ( group )
289 char    *group;
290 {
291     struct group *this_group;
292  
293     /* check for anything */
294     if ( !group || strlen ( group ) < 1 ) return 0;
295  
296     /* grab the /etc/groups record relating to group */
297     this_group = getgrnam ( group );
298  
299     /* return false if there is no structure returned */
300     if (this_group == NULL) return 0;
301  
302     /* return proper gid */
303     return this_group->gr_gid;
304  
305 }
306
307 /* ------------------ */
308 int main(int argc, char *argv[])
309 {
310     char  dbdir[MAXPATHLEN + 1];
311     int   len;
312     pid_t pid;
313     int   status;
314     char  *dbdpn = NULL;
315     char  *host = NULL;
316     int   port = 0;
317     struct db_param *dbp;
318     int    i;
319     int    cc;
320     uid_t  uid = 0;
321     gid_t  gid = 0;
322     int    err = 0;
323     int    debug = 0;
324     int    ret;
325     
326     while (( cc = getopt( argc, argv, "ds:p:h:u:g:")) != -1 ) {
327         switch (cc) {
328         case 'd':
329             debug = 1;
330             break;
331         case 'h':
332             host = strdup(optarg);  
333             break;
334         case 'u':
335             uid = user_to_uid (optarg);
336             if (!uid) {
337                 LOG(log_error, logtype_cnid, "main: bad user %s", optarg);
338                 err++;
339             }
340             break;
341         case 'g':
342             gid =group_to_gid (optarg);
343             if (!gid) {
344                 LOG(log_error, logtype_cnid, "main: bad group %s", optarg);
345                 err++;
346             }
347             break;
348         case 'p':
349             port = atoi(optarg);
350             break;
351         case 's':
352             dbdpn = strdup(optarg);
353             break;
354         default:
355             err++;
356             break;
357         }
358     }
359     
360     if (err || !host || !port || !dbdpn) {
361         LOG(log_error, logtype_cnid, "main: bad arguments");
362         exit(1);
363     }
364     
365     if (!debug) {
366  
367         switch (fork()) {
368         case 0 :
369             fclose(stdin);
370             fclose(stdout);
371             fclose(stderr);
372
373 #ifdef TIOCNOTTY
374             {
375                 int i;
376                 if (( i = open( "/dev/tty", O_RDWR )) >= 0 ) {
377                     (void)ioctl( i, TIOCNOTTY, 0 );
378                     setpgid( 0, getpid());
379                     (void) close(i);
380                 }
381             }
382 #else
383             setpgid( 0, getpid());
384 #endif
385            break;
386         case -1 :  /* error */
387             LOG(log_error, logtype_cnid, "detach from terminal: %s", strerror(errno));
388             exit(1);
389         default :  /* server */
390             exit(0);
391         }
392     }
393
394     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
395         exit(1);
396     /* switch uid/gid */
397     if (uid || gid) {
398
399         LOG(log_info, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
400         if (gid) {
401             if (setresgid(gid,gid,gid) < 0 || setgid(gid) < 0) {
402                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
403                 exit(1);
404             }
405         }
406         if (uid) {
407             if (setresuid(uid,uid,uid) < 0 || setuid(uid) < 0) {
408                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
409                 exit(1);
410             }
411         }
412     }
413
414     signal(SIGPIPE, SIG_IGN);
415
416     while (1) {
417         /* Collect zombie processes and log what happened to them */       
418         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
419            for (i = 1; i <= MAXSRV; i++) {
420                if (srv[i].pid == pid) {
421                    srv[i].pid = 0;
422 #if 0                   
423                    free(srv[i].name);
424 #endif                   
425                    close(srv[i].sv[0]);
426                    close(srv[i].sv[1]);
427                    break;
428                }
429             }
430             if (WIFEXITED(status)) {
431                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with exit code %i", 
432                     pid, WEXITSTATUS(status));
433             }
434             else if (WIFSIGNALED(status)) {
435                 LOG(log_info, logtype_cnid, "cnid_dbd pid %i exited with signal %i", 
436                     pid, WTERMSIG(status));
437             }
438             /* FIXME should */
439             
440         }
441         if ((rqstfd = usockfd_check(srvfd, 10000000)) <= 0)
442             continue;
443         /* TODO: Check out read errors, broken pipe etc. in libatalk. Is
444            SIGIPE ignored there? Answer: Ignored for dsi, but not for asp ... */
445         ret = read(rqstfd, &len, sizeof(int));
446         if (!ret) {
447             /* already close */
448             goto loop_end;
449         }
450         else if (ret < 0) {
451             LOG(log_error, logtype_cnid, "error read: %s", strerror(errno));
452             goto loop_end;
453         }
454         else if (ret != sizeof(int)) {
455             LOG(log_error, logtype_cnid, "short read: got %d", ret);
456             goto loop_end;
457         }
458         /*
459          *  checks for buffer overruns. The client libatalk side does it too 
460          *  before handing the dir path over but who trusts clients?
461          */
462         if (!len || len +DBHOMELEN +2 > MAXPATHLEN) {
463             LOG(log_error, logtype_cnid, "wrong len parameter: %d", len);
464             goto loop_end;
465         }
466         if (read(rqstfd, dbdir, len) != len) {
467             LOG(log_error, logtype_cnid, "error/short read (dir): %s", strerror(errno));
468             goto loop_end;
469         }
470         dbdir[len] = '\0';
471         
472         if (set_dbdir(dbdir, len) < 0) {
473             goto loop_end;
474         }
475         
476         if ((dbp = db_param_read(dbdir)) == NULL) {
477             LOG(log_error, logtype_cnid, "Error reading config file");
478             goto loop_end;
479         }
480         maybe_start_dbd(dbdpn, dbdir, dbp->usock_file);
481
482     loop_end:
483         close(rqstfd);
484     }
485 }