]> arthur.barton.de Git - netatalk.git/blob - etc/cnid_dbd/cnid_metad.c
Spotlight: use async Tracker SPARQL API
[netatalk.git] / etc / cnid_dbd / cnid_metad.c
1 /*
2  * Copyright (C) Joerg Lenneis 2003
3  * Copyright (C) Frank Lahm 2009, 2010
4  *
5  * All Rights Reserved.  See COPYING.
6  */
7
8 /* 
9    cnid_dbd metadaemon to start up cnid_dbd upon request from afpd.
10    Here is how it works:
11    
12                        via TCP socket
13    1.       afpd          ------->        cnid_metad
14
15                    via UNIX domain socket
16    2.   cnid_metad        ------->         cnid_dbd
17
18                     passes afpd client fd
19    3.   cnid_metad        ------->         cnid_dbd
20
21    Result:
22                        via TCP socket
23    4.       afpd          ------->         cnid_dbd
24
25    cnid_metad and cnid_dbd have been converted to non-blocking IO in 2010.
26  */
27
28
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif /* HAVE_CONFIG_H */
32
33 #include <unistd.h>
34 #undef __USE_GNU
35
36 #include <stdlib.h>
37 #include <sys/param.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <signal.h>
41 #include <sys/types.h>
42 #include <sys/time.h>
43 #include <sys/resource.h>
44 #include <sys/wait.h>
45 #include <sys/uio.h>
46 #include <sys/un.h>
47 // #define _XPG4_2 1
48 #include <sys/socket.h>
49 #include <stdio.h>
50 #include <time.h>
51
52 #ifndef WEXITSTATUS
53 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
54 #endif /* ! WEXITSTATUS */
55 #ifndef WIFEXITED
56 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
57 #endif /* ! WIFEXITED */
58 #ifndef WIFSTOPPED
59 #define WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
60 #endif
61
62 #ifndef WIFSIGNALED
63 #define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
64 #endif
65 #ifndef WTERMSIG
66 #define WTERMSIG(status)      ((status) & 0x7f)
67 #endif
68
69 /* functions for username and group */
70 #include <pwd.h>
71 #include <grp.h>
72
73 /* FIXME */
74 #ifdef linux
75 #ifndef USE_SETRESUID
76 #define USE_SETRESUID 1
77 #define SWITCH_TO_GID(gid)  ((setresgid(gid,gid,gid) < 0 || setgid(gid) < 0) ? -1 : 0)
78 #define SWITCH_TO_UID(uid)  ((setresuid(uid,uid,uid) < 0 || setuid(uid) < 0) ? -1 : 0)
79 #endif  /* USE_SETRESUID */
80 #else   /* ! linux */
81 #ifndef USE_SETEUID
82 #define USE_SETEUID 1
83 #define SWITCH_TO_GID(gid)  ((setegid(gid) < 0 || setgid(gid) < 0) ? -1 : 0)
84 #define SWITCH_TO_UID(uid)  ((setuid(uid) < 0 || seteuid(uid) < 0 || setuid(uid) < 0) ? -1 : 0)
85 #endif  /* USE_SETEUID */
86 #endif  /* linux */
87
88 #include <atalk/util.h>
89 #include <atalk/logger.h>
90 #include <atalk/cnid_bdb_private.h>
91 #include <atalk/paths.h>
92 #include <atalk/compat.h>
93 #include <atalk/errchk.h>
94 #include <atalk/bstrlib.h>
95 #include <atalk/bstradd.h>
96 #include <atalk/netatalk_conf.h>
97 #include <atalk/volume.h>
98
99 #include "usockfd.h"
100
101 #define DBHOME        ".AppleDB"
102 #define DBHOMELEN    8
103
104 static int srvfd;
105 static int rqstfd;
106 static volatile sig_atomic_t sigchild = 0;
107 static uint maxvol;
108
109 #define MAXSPAWN   3                   /* Max times respawned in.. */
110 #define TESTTIME   10                  /* this much seconds apfd client tries to  *
111                                         * to reconnect every 5 secondes, catch it */
112 #define MAXVOLS    4096
113 #define DEFAULTHOST  "localhost"
114 #define DEFAULTPORT  "4700"
115
116 struct server {
117     char *v_path;
118     pid_t pid;
119     time_t tm;                    /* When respawned last */
120     unsigned int count;           /* Times respawned in the last TESTTIME secondes */
121     int control_fd;               /* file descriptor to child cnid_dbd process */
122 };
123
124 static struct server srv[MAXVOLS];
125
126 static void daemon_exit(int i)
127 {
128     exit(i);
129 }
130
131 /* ------------------ */
132 static void sig_handler(int sig)
133 {
134     switch( sig ) {
135     case SIGTERM:
136     case SIGQUIT:
137         LOG(log_note, logtype_afpd, "shutting down on %s",
138             sig == SIGTERM ? "SIGTERM" : "SIGQUIT");
139         break;
140     default :
141         LOG(log_error, logtype_afpd, "unexpected signal: %d", sig);
142     }
143     daemon_exit(0);
144 }
145
146 static struct server *test_usockfn(const char *path)
147 {
148     int i;
149
150     for (i = 0; i < maxvol; i++) {
151         if (srv[i].v_path && STRCMP(path, ==, srv[i].v_path))
152             return &srv[i];
153     }
154
155     return NULL;
156 }
157
158 /**
159  * Pass connection request to existing cnid_dbd process or start a new one
160  *
161  * @param[in] obj      handle
162  * @param[in] dbdpn    Path to cnid_dbd binary
163  * @param[in] volpath  Path of AFP volume
164  * @param[in] username  Optional username, may be NULL
165  *
166  * @return 0 on success, -1 on error
167  **/
168  int maybe_start_dbd(const AFPObj *obj, char *dbdpn, const char *volpath, const char *username)
169 {
170     pid_t pid;
171     struct server *up;
172     int sv[2];
173     int i;
174     time_t t;
175     char buf1[8];
176     char buf2[8];
177
178     LOG(log_debug, logtype_cnid, "maybe_start_dbd(\"%s\"): BEGIN", volpath);
179
180     up = test_usockfn(volpath);
181     if (up && up->pid) {
182         /* we already have a process, send our fd */
183         LOG(log_debug, logtype_cnid, "maybe_start_dbd: cnid_dbd[%d] already serving", up->pid);
184         if (send_fd(up->control_fd, rqstfd) < 0) {
185             /* FIXME */
186             return -1;
187         }
188         return 0;
189     }
190
191     LOG(log_debug, logtype_cnid, "maybe_start_dbd: no cnid_dbd serving yet");
192
193     time(&t);
194     if (!up) {
195         /* find an empty slot (i < maxvol) or the first free slot (i == maxvol)*/
196         for (i = 0; i <= maxvol && i < MAXVOLS; i++) {
197             if (srv[i].v_path == NULL) {
198                 up = &srv[i];
199                 if ((up->v_path = strdup(volpath)) == NULL)
200                     return -1;
201                 up->tm = t;
202                 up->count = 0;
203                 if (i == maxvol)
204                     maxvol++;
205                 break;
206             }
207         }
208         if (!up) {
209             LOG(log_error, logtype_cnid, "no free slot for cnid_dbd child. Configured maximum: %d. Do you have so many volumes?", MAXVOLS);
210             return -1;
211         }
212     } else {
213         /* we have a slot but no process */
214         if (up->count > 0) {
215             /* check for respawn too fast */
216             if (t < (up->tm + TESTTIME)) {
217                 /* We're in the respawn time window */
218                 if (up->count > MAXSPAWN) {
219                     /* ...and already tried to fork too often */
220                     LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawning too fast");
221                     return -1; /* just exit, dont sleep, because we might have work to do for another client  */
222                 }
223             } else {
224                 /* out of respawn too fast windows reset the count */
225                 LOG(log_info, logtype_cnid, "maybe_start_dbd: respawn window ended");
226                 up->count = 0;
227             }
228         }
229         up->count++;
230         up->tm = t;
231         LOG(log_maxdebug, logtype_cnid, "maybe_start_dbd: respawn count: %u", up->count);
232         if (up->count > MAXSPAWN) {
233             /* We spawned too fast. From now until the first time we tried + TESTTIME seconds
234                we will just return -1 above */
235             LOG(log_info, logtype_cnid, "maybe_start_dbd: reached MAXSPAWN threshhold");
236        }
237     }
238
239     /* 
240        Create socketpair for comm between parent and child.
241        We use it to pass fds from connecting afpd processes to our
242        cnid_dbd child via fd passing.
243     */
244     if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
245         LOG(log_error, logtype_cnid, "error in socketpair: %s", strerror(errno));
246         return -1;
247     }
248
249     if ((pid = fork()) < 0) {
250         LOG(log_error, logtype_cnid, "error in fork: %s", strerror(errno));
251         return -1;
252     }
253     if (pid == 0) {
254         int ret;
255         /*
256          *  Child. Close descriptors and start the daemon. If it fails
257          *  just log it. The client process will fail connecting
258          *  afterwards anyway.
259          */
260
261         close(srvfd);
262         close(sv[0]);
263
264         for (i = 0; i < MAXVOLS; i++) {
265             if (srv[i].pid && up != &srv[i]) {
266                 close(srv[i].control_fd);
267             }
268         }
269
270         sprintf(buf1, "%i", sv[1]);
271         sprintf(buf2, "%i", rqstfd);
272
273         if (up->count == MAXSPAWN) {
274             /* there's a pb with the db inform child, it will delete the db */
275             LOG(log_warning, logtype_cnid,
276                 "Multiple attempts to start CNID db daemon for \"%s\" failed, wiping the slate clean...",
277                 up->v_path);
278             ret = execlp(dbdpn, dbdpn,
279                          "-F", obj->options.configfile,
280                          "-p", volpath,
281                          "-t", buf1,
282                          "-l", buf2,
283                          "-u", username,
284                          NULL);
285         } else {
286             ret = execlp(dbdpn, dbdpn,
287                          "-F", obj->options.configfile,
288                          "-p", volpath,
289                          "-t", buf1,
290                          "-l", buf2,
291                          "-u", username,
292                          NULL);
293         }
294         /* Yikes! We're still here, so exec failed... */
295         LOG(log_error, logtype_cnid, "Fatal error in exec: %s", strerror(errno));
296         daemon_exit(0);
297     }
298     /*
299      *  Parent.
300      */
301     up->pid = pid;
302     close(sv[1]);
303     up->control_fd = sv[0];
304     return 0;
305 }
306
307 /* ------------------ */
308 static int set_dbdir(const char *dbdir, const char *vpath)
309 {
310     EC_INIT;
311     struct stat st;
312     bstring oldpath, newpath;
313     char *cmd_argv[4];
314
315     LOG(log_debug, logtype_cnid, "set_dbdir: volume: %s, db path: %s", vpath, dbdir);
316
317     EC_NULL_LOG( oldpath = bformat("%s/%s/", vpath, DBHOME) );
318     EC_NULL_LOG( newpath = bformat("%s/%s/", dbdir, DBHOME) );
319
320     if (lstat(dbdir, &st) < 0 && mkdir(dbdir, 0755) < 0) {
321         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", dbdir);
322         EC_FAIL;
323     }
324
325     if (lstat(cfrombstr(oldpath), &st) == 0 && lstat(cfrombstr(newpath), &st) != 0 && errno == ENOENT) {
326         /* There's an .AppleDB in the volume root, we move it */
327         cmd_argv[0] = "mv";
328         cmd_argv[1] = bdata(oldpath);
329         cmd_argv[2] = (char *)dbdir;
330         cmd_argv[3] = NULL;
331         if (run_cmd("mv", cmd_argv) != 0) {
332             LOG(log_error, logtype_cnid, "set_dbdir: moving CNID db from \"%s\" to \"%s\" failed",
333                 bdata(oldpath), dbdir);
334             EC_FAIL;
335         }
336
337     }
338
339     if (lstat(cfrombstr(newpath), &st) < 0 && mkdir(cfrombstr(newpath), 0755 ) < 0) {
340         LOG(log_error, logtype_cnid, "set_dbdir: mkdir failed for %s", bdata(newpath));
341         EC_FAIL;
342     }
343
344 EC_CLEANUP:
345     bdestroy(oldpath);
346     bdestroy(newpath);
347     EC_EXIT;
348 }
349
350 /* ------------------ */
351 static void catch_child(int sig _U_) 
352 {
353     sigchild = 1;
354 }
355
356 /* ----------------------- */
357 static void set_signal(void)
358 {
359     struct sigaction sv;
360     sigset_t set;
361
362     memset(&sv, 0, sizeof(sv));
363
364     /* Catch SIGCHLD */
365     sv.sa_handler = catch_child;
366     sv.sa_flags = SA_NOCLDSTOP;
367     sigemptyset(&sv.sa_mask);
368     if (sigaction(SIGCHLD, &sv, NULL) < 0) {
369         LOG(log_error, logtype_cnid, "cnid_metad: sigaction: %s", strerror(errno));
370         daemon_exit(EXITERR_SYS);
371     }
372
373     /* Catch SIGTERM and SIGQUIT */
374     sv.sa_handler = sig_handler;
375     sigfillset(&sv.sa_mask );
376     if (sigaction(SIGTERM, &sv, NULL ) < 0 ) {
377         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
378         daemon_exit(EXITERR_SYS);
379     }
380     if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
381         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
382         daemon_exit(EXITERR_SYS);
383     }
384
385     /* Ignore the rest */
386     sv.sa_handler = SIG_IGN;
387     sigemptyset(&sv.sa_mask );
388     if (sigaction(SIGALRM, &sv, NULL ) < 0 ) {
389         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
390         daemon_exit(EXITERR_SYS);
391     }
392     sv.sa_handler = SIG_IGN;
393     sigemptyset(&sv.sa_mask );
394     if (sigaction(SIGHUP, &sv, NULL ) < 0 ) {
395         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
396         daemon_exit(EXITERR_SYS);
397     }
398     sv.sa_handler = SIG_IGN;
399     sigemptyset(&sv.sa_mask );
400     if (sigaction(SIGUSR1, &sv, NULL ) < 0 ) {
401         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
402         daemon_exit(EXITERR_SYS);
403     }
404     sv.sa_handler = SIG_IGN;
405     sigemptyset(&sv.sa_mask );
406     if (sigaction(SIGUSR2, &sv, NULL ) < 0 ) {
407         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
408         daemon_exit(EXITERR_SYS);
409     }
410     sv.sa_handler = SIG_IGN;
411     sigemptyset(&sv.sa_mask );
412     if (sigaction(SIGPIPE, &sv, NULL ) < 0 ) {
413         LOG(log_error, logtype_afpd, "sigaction: %s", strerror(errno) );
414         daemon_exit(EXITERR_SYS);
415     }
416
417     /* block everywhere but in pselect */
418     sigemptyset(&set);
419     sigaddset(&set, SIGCHLD);
420     sigprocmask(SIG_SETMASK, &set, NULL);
421 }
422
423 static int setlimits(void)
424 {
425     struct rlimit rlim;
426
427     if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
428         LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
429         exit(1);
430     }
431     if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < 65535) {
432         rlim.rlim_cur = 65535;
433         if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < 65535)
434             rlim.rlim_max = 65535;
435         if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
436             LOG(log_error, logtype_afpd, "setlimits: %s", strerror(errno));
437             exit(1);
438         }
439     }
440     return 0;
441 }
442
443 static uid_t uid_from_name(const char *name)
444 {
445     struct passwd *pwd;
446
447     pwd = getpwnam(name);
448     if (pwd == NULL)
449         return 0;
450     return pwd->pw_uid;
451 }
452
453 /* ------------------ */
454 int main(int argc, char *argv[])
455 {
456     char  *volname = NULL;
457     char  *volpath = NULL;
458     char  *username = NULL;
459     int   len[DBD_NUM_OPEN_ARGS], actual_len;
460     pid_t pid;
461     int   status;
462     char  *dbdpn = _PATH_CNID_DBD;
463     char  *host;
464     char  *port;
465     int    i;
466     int    cc;
467     uid_t  uid = 0;
468     gid_t  gid = 0;
469     int    debug = 0;
470     int    ret;
471     sigset_t set;
472     AFPObj obj = { 0 };
473     struct vol *vol;
474
475     while (( cc = getopt( argc, argv, "dF:vV")) != -1 ) {
476         switch (cc) {
477         case 'd':
478             debug = 1;
479             break;
480         case 'F':
481             obj.cmdlineconfigfile = strdup(optarg);
482             break;
483         case 'v':
484         case 'V':
485             printf("cnid_metad (Netatalk %s)\n", VERSION);
486             return -1;
487         default:
488             printf("cnid_metad [-dvV] [-F alternate configfile ]\n");
489             return -1;
490         }
491     }
492
493     if (!debug && daemonize(0, 0) != 0)
494         exit(EXITERR_SYS);
495
496     if (afp_config_parse(&obj, "cnid_metad") != 0)
497         daemon_exit(1);
498
499     (void)setlimits();
500
501     host = atalk_iniparser_getstrdup(obj.iniconfig, INISEC_GLOBAL, "cnid listen", "localhost:4700");
502     if ((port = strrchr(host, ':')))
503         *port++ = 0;
504     else
505         port = DEFAULTPORT;
506     if ((srvfd = tsockfd_create(host, port, 10)) < 0)
507         daemon_exit(1);
508
509     LOG(log_note, logtype_afpd, "CNID Server listening on %s:%s", host, port);
510
511     /* switch uid/gid */
512     if (uid || gid) {
513         LOG(log_debug, logtype_cnid, "Setting uid/gid to %i/%i", uid, gid);
514         if (gid) {
515             if (SWITCH_TO_GID(gid) < 0) {
516                 LOG(log_info, logtype_cnid, "unable to switch to group %d", gid);
517                 daemon_exit(1);
518             }
519         }
520         if (uid) {
521             if (SWITCH_TO_UID(uid) < 0) {
522                 LOG(log_info, logtype_cnid, "unable to switch to user %d", uid);
523                 daemon_exit(1);
524             }
525         }
526     }
527
528     set_signal();
529
530     sigemptyset(&set);
531     sigprocmask(SIG_SETMASK, NULL, &set);
532     sigdelset(&set, SIGCHLD);
533
534     while (1) {
535         rqstfd = usockfd_check(srvfd, &set);
536         /* Collect zombie processes and log what happened to them */
537         if (sigchild) while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
538             for (i = 0; i < maxvol; i++) {
539                 if (srv[i].pid == pid) {
540                     srv[i].pid = 0;
541                     close(srv[i].control_fd);
542                     break;
543                 }
544             }
545             if (WIFEXITED(status)) {
546                 LOG(log_info, logtype_cnid, "cnid_dbd[%i] exited with exit code %i",
547                     pid, WEXITSTATUS(status));
548             } else {
549                 /* cnid_dbd did a clean exit probably on idle timeout, reset bookkeeping */
550                 srv[i].tm = 0;
551                 srv[i].count = 0;
552             }
553             if (WIFSIGNALED(status)) {
554                 LOG(log_info, logtype_cnid, "cnid_dbd[%i] got signal %i",
555                     pid, WTERMSIG(status));
556             }
557             sigchild = 0;
558         }
559         if (rqstfd <= 0)
560             continue;
561
562         ret = readt(rqstfd, &len[0], sizeof(int) * DBD_NUM_OPEN_ARGS, 1, 4);
563
564         if (!ret) {
565             /* already close */
566             goto loop_end;
567         }
568         else if (ret < 0) {
569             LOG(log_severe, logtype_cnid, "error read: %s", strerror(errno));
570             goto loop_end;
571         }
572         else if (ret != DBD_NUM_OPEN_ARGS * sizeof(int)) {
573             LOG(log_error, logtype_cnid, "short read: got %d", ret);
574             goto loop_end;
575         }
576
577         /*
578          *  checks for buffer overruns. The client libatalk side does it too
579          *  before handing the dir path over but who trusts clients?
580          */
581         if (!len[0] || !len[1]) {
582             LOG(log_error, logtype_cnid, "wrong len parameter: len[0]: %d, len[1]: %d", len[0], len[1]);
583             goto loop_end;
584         }
585
586         volname = malloc(len[0]);
587         volpath = malloc(len[1]);
588         if (len[2]) {
589             username = malloc(len[2]);
590         }
591         if (!volname || !volpath || (len[2] && !username)) {
592             LOG(log_severe, logtype_cnid, "malloc: %s", strerror(errno));
593             goto loop_end;
594         }
595
596         actual_len = readt(rqstfd, volname, len[0], 1, 5);
597         if (actual_len != len[0]) {
598             LOG(log_severe, logtype_cnid, "readt: %s", strerror(errno));
599             goto loop_end;
600         }
601
602         actual_len = readt(rqstfd, volpath, len[1], 1, 5);
603         if (actual_len != len[1]) {
604             LOG(log_severe, logtype_cnid, "readt: %s", strerror(errno));
605             goto loop_end;
606         }
607
608         if (len[2]) {
609             actual_len = readt(rqstfd, username, len[2], 1, 5);
610             if (actual_len != len[2]) {
611                 LOG(log_severe, logtype_cnid, "readt: %s", strerror(errno));
612                 goto loop_end;
613             }
614             strlcpy(obj.username, username, MAXUSERLEN);
615             obj.uid = uid_from_name(username);
616             if (!obj.uid)
617                 goto loop_end;
618         } else {
619             obj.username[0] = 0;
620         }
621
622         LOG(log_debug, logtype_cnid, "user: %s, volume %s, path %s",
623             username ? username : "-", volname, volpath);
624
625         if (load_volumes(&obj, lv_all) != 0) {
626             LOG(log_severe, logtype_cnid, "main: error reloading config");
627             goto loop_end;
628         }
629
630         if ((vol = getvolbypath(&obj, volpath)) == NULL) {
631             LOG(log_severe, logtype_cnid, "main: no volume for path \"%s\"", volpath);
632             goto loop_end;
633         }
634
635         LOG(log_maxdebug, logtype_cnid, "main: dbpath: %s", vol->v_dbpath);
636
637         if (set_dbdir(vol->v_dbpath, vol->v_path) < 0) {
638             goto loop_end;
639         }
640
641         maybe_start_dbd(&obj, dbdpn, vol->v_path, username);
642
643     loop_end:
644         close(rqstfd);
645         unload_volumes(&obj);
646         SAFE_FREE(volname);
647         SAFE_FREE(volpath);
648         SAFE_FREE(username);
649     }
650 }