63e40b237af40e47beb6e6b35a657007d944e77b
[doldaconnect.git] / daemon / client.c
1 /*
2  *  Dolda Connect - Modular multiuser Direct Connect-style client
3  *  Copyright (C) 2004 Fredrik Tolf <fredrik@dolda2000.com>
4  *  
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *  
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *  
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <wchar.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <dirent.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33 #include "client.h"
34 #include "conf.h"
35 #include "log.h"
36 #include "utils.h"
37 #include "module.h"
38 #include "net.h"
39 #include "sysevents.h"
40 #include <tiger.h>
41
42 struct scanstate
43 {
44     struct scanstate *next;
45     struct sharecache *node;
46     DIR *dd;
47 };
48
49 struct scanqueue
50 {
51     struct scanqueue *next;
52     struct scanstate *state;
53 };
54
55 static int conf_share(int argc, wchar_t **argv);
56 static void freecache(struct sharecache *node);
57 static void checkhashes(void);
58 static void writehashcache(int now);
59
60 static struct configvar myvars[] =
61 {
62     /** The default nick name to use. The nickname can also be
63      * specified for individual hubs, overriding this setting. */
64     {CONF_VAR_STRING, "defnick", {.str = L"DoldaConnect user"}},
65     /** When scanning shares, this bitmask is consulted for every
66      * regular file. Unless the file's mode has the bits specified by
67      * this mask set, it will not be shared. */
68     {CONF_VAR_INT, "scanfilemask", {.num = 0004}},
69     /** When scanning shares, this bitmask is consulted for every
70      * directory encountered. Unless the directory's mode has the bits
71      * specified by this mask set, it will be ignored and any files
72      * under it will not be shared. */
73     {CONF_VAR_INT, "scandirmask", {.num = 0005}},
74     /** The filename to use for the hash cache (see the FILES section
75      * for more information). */
76     {CONF_VAR_STRING, "hashcache", {.str = L"dc-hashcache"}},
77     /** Writes of the hash cache and file lists are delayed for an
78      * amount of time, in order to minimize the time spent on I/O wait
79      * while hashing many small files. This variable sets the amount
80      * of time, in seconds. */
81     {CONF_VAR_INT, "hashwritedelay", {.num = 300}},
82     /** The amount of time, in seconds, to wait before automatically
83      * rescanning the shared directories for changes. Set to zero (the
84      * default) to disable automatic rescanning. (Broken shares are
85      * always rescanned upon detection, regardless of this
86      * setting.) */
87     {CONF_VAR_INT, "rescandelay", {.num = 0}},
88     {CONF_VAR_END}
89 };
90
91 static struct configcmd mycmds[] = 
92 {
93     {"share", conf_share},
94     {NULL}
95 };
96
97 static struct scanstate *scanjob = NULL;
98 static struct scanqueue *scanqueue = NULL;
99 static struct sharepoint *shares = NULL;
100 static struct hashcache *hashcache = NULL;
101 static struct timer *hashwritetimer = NULL;
102 /* Set initially to -1, but changed to 0 the first time run() is
103  * called. This is to avoid forking a hash job before daemonizing,
104  * since that would make the daemon unable to wait() for the hash
105  * job. */
106 static pid_t hashjob = -1;
107 struct sharecache *shareroot = NULL;
108 static struct timer *scantimer = NULL;
109 unsigned long long sharesize = 0;
110 GCBCHAIN(sharechangecb, unsigned long long);
111
112 static int conf_share(int argc, wchar_t **argv)
113 {
114     struct sharepoint *share;
115     char *b;
116     
117     if(argc < 3)
118     {
119         flog(LOG_WARNING, "not enough arguments given for share command");
120         return(1);
121     }
122     if((b = icwcstombs(argv[2], NULL)) == NULL)
123     {
124         flog(LOG_WARNING, "could not convert wcs path (%ls) to current locale's charset: %s", argv[2], strerror(errno));
125         return(1);
126     }
127     for(share = shares; share != NULL; share = share->next)
128     {
129         if(!strcmp(share->path, b) && !wcscmp(share->name, argv[1]))
130         {
131             share->delete = 0;
132             free(b);
133             return(0);
134         }
135     }
136     share = smalloc(sizeof(*share));
137     share->path = b;
138     share->delete = 0;
139     share->name = swcsdup(argv[1]);
140     share->next = shares;
141     share->prev = NULL;
142     if(shares != NULL)
143         shares->prev = share;
144     shares = share;
145     return(0);
146 }
147
148 static void dumpsharecache(struct sharecache *node, int l)
149 {
150     int i;
151     
152     for(; node != NULL; node = node->next)
153     {
154         for(i = 0; i < l; i++)
155             putc('\t', stdout);
156         printf("%ls\n", node->name);
157         if(node->f.b.type == FILE_DIR)
158             dumpsharecache(node->child, l + 1);
159     }
160 }
161
162 struct hash *newhash(wchar_t *algo, size_t len, char *buf)
163 {
164     struct hash *ret;
165     
166     ret = smalloc(sizeof(*ret));
167     memset(ret, 0, sizeof(*ret));
168     ret->algo = swcsdup(algo);
169     ret->len = len;
170     ret->buf = memcpy(smalloc(len), buf, len);
171     return(ret);
172 }
173
174 void freehash(struct hash *hash)
175 {
176     free(hash->algo);
177     free(hash->buf);
178     free(hash);
179 }
180
181 struct hash *duphash(struct hash *hash)
182 {
183     return(newhash(hash->algo, hash->len, hash->buf));
184 }
185
186 struct hash *parsehash(wchar_t *text)
187 {
188     wchar_t *p;
189     char *mbsbuf, *decbuf;
190     size_t buflen;
191     struct hash *ret;
192     
193     if((p = wcschr(text, L':')) == NULL)
194         return(NULL);
195     *(p++) = L'\0';
196     if((mbsbuf = icwcstombs(p, "US-ASCII")) == NULL)
197         return(NULL);
198     decbuf = base64decode(mbsbuf, &buflen);
199     free(mbsbuf);
200     if(decbuf == NULL)
201         return(NULL);
202     ret = newhash(text, buflen, decbuf);
203     free(decbuf);
204     return(ret);
205 }
206
207 wchar_t *unparsehash(struct hash *hash)
208 {
209     static wchar_t *buf = NULL;
210     wchar_t *whbuf;
211     char *hbuf;
212     size_t bufsize, bufdata;
213     
214     if(buf != NULL)
215         free(buf);
216     buf = NULL;
217     bufsize = bufdata = 0;
218     hbuf = base64encode(hash->buf, hash->len);
219     if((whbuf = icmbstowcs(hbuf, "US-ASCII")) == NULL)
220     {
221         flog(LOG_CRIT, "bug! could not convert base64 from us-ascii: %s", strerror(errno));
222         abort();
223     }
224     free(hbuf);
225     bufcat(buf, hash->algo, wcslen(hash->algo));
226     addtobuf(buf, ':');
227     bufcat(buf, whbuf, wcslen(whbuf));
228     free(whbuf);
229     addtobuf(buf, 0);
230     return(buf);
231 }
232
233 int hashcmp(struct hash *h1, struct hash *h2)
234 {
235     if(wcscmp(h1->algo, h2->algo))
236         return(0);
237     if(h1->len != h2->len)
238         return(0);
239     if(memcmp(h1->buf, h2->buf, h1->len))
240         return(0);
241     return(1);
242 }
243
244 static struct hashcache *newhashcache(void)
245 {
246     struct hashcache *new;
247     
248     new = smalloc(sizeof(*new));
249     memset(new, 0, sizeof(*new));
250     new->next = hashcache;
251     new->prev = NULL;
252     if(hashcache != NULL)
253         hashcache->prev = new;
254     hashcache = new;
255     return(new);
256 }
257
258 static void freehashcache(struct hashcache *hc)
259 {
260     if(hc->next != NULL)
261         hc->next->prev = hc->prev;
262     if(hc->prev != NULL)
263         hc->prev->next = hc->next;
264     if(hc == hashcache)
265         hashcache = hc->next;
266     free(hc);
267 }
268
269 static struct hashcache *findhashcache(dev_t dev, ino_t inode)
270 {
271     struct hashcache *hc;
272     
273     for(hc = hashcache; hc != NULL; hc = hc->next)
274     {
275         if((hc->dev == dev) && (hc->inode == inode))
276             return(hc);
277     }
278     return(NULL);
279 }
280
281 static void readhashcache(void)
282 {
283     int i, wc, line;
284     char *hcname;
285     FILE *stream;
286     char linebuf[256];
287     char *p, *p2, *wv[32], *hash;
288     struct hashcache *hc;
289     size_t len;
290     
291     if((hcname = findfile(icswcstombs(confgetstr("cli", "hashcache"), NULL, NULL), NULL, 0)) == NULL)
292         return;
293     if((stream = fopen(hcname, "r")) == NULL)
294     {
295         flog(LOG_WARNING, "could not open hash cache %s: %s", hcname, strerror(errno));
296         return;
297     }
298     while(hashcache != NULL)
299         freehashcache(hashcache);
300     line = 0;
301     while(!feof(stream))
302     {
303         fgets(linebuf, sizeof(linebuf), stream);
304         line++;
305         for(p = linebuf; *p; p++)
306         {
307             if(*p == '\n')
308                 *p = ' ';
309         }
310         if(linebuf[0] == '#')
311             continue;
312         for(wc = 0, p = linebuf; (wc < 32) && ((p2 = strchr(p, ' ')) != NULL); p = p2 + 1)
313         {
314             if(p2 == p)
315                 continue;
316             *p2 = 0;
317             wv[wc++] = p;
318         }
319         if(wc < 3)
320             continue;
321         hc = newhashcache();
322         hc->dev = strtoll(wv[0], NULL, 10);
323         hc->inode = strtoll(wv[1], NULL, 10);
324         hc->mtime = strtoll(wv[2], NULL, 10);
325         for(i = 3; i < wc; i++)
326         {
327             if(!strcmp(wv[i], "tth"))
328             {
329                 if(++i >= wc)
330                     continue;
331                 hash = base64decode(wv[i], &len);
332                 if(len != 24)
333                 {
334                     free(hash);
335                     continue;
336                 }
337                 memcpy(hc->tth, hash, 24);
338                 free(hash);
339             }
340         }
341     }
342     fclose(stream);
343 }
344
345 static void hashtimercb(int cancelled, void *uudata)
346 {
347     hashwritetimer = NULL;
348     if(!cancelled)
349         writehashcache(1);
350 }
351
352 static void writehashcache(int now)
353 {
354     char *buf;
355     char *hcname;
356     FILE *stream;
357     struct hashcache *hc;
358     
359     if(!now)
360     {
361         if(hashwritetimer == NULL)
362             hashwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), (void (*)(int, void *))hashtimercb, NULL);
363         return;
364     }
365     if(hashwritetimer != NULL)
366         canceltimer(hashwritetimer);
367     hcname = findfile(icswcstombs(confgetstr("cli", "hashcache"), NULL, NULL), NULL, 1);
368     if((stream = fopen(hcname, "w")) == NULL)
369     {
370         flog(LOG_WARNING, "could not write hash cache %s: %s", hcname, strerror(errno));
371         return;
372     }
373     fprintf(stream, "# Dolda Connect hash cache file\n");
374     fprintf(stream, "# Generated automatically, do not edit\n");
375     fprintf(stream, "# Format: DEVICE INODE MTIME [HASH...]\n");
376     fprintf(stream, "# HASH := HASHTYPE HASHVAL\n");
377     fprintf(stream, "# HASHTYPE can currently only be `tth'\n");
378     for(hc = hashcache; hc != NULL; hc = hc->next)
379     {
380         buf = base64encode(hc->tth, 24);
381         fprintf(stream, "%lli %lli %li tth %s\n", (long long)hc->dev, (long long)hc->inode, hc->mtime, buf);
382         free(buf);
383     }
384     fclose(stream);
385 }
386
387 static void hashread(struct socket *sk, void *uudata)
388 {
389     static char *hashbuf;
390     static size_t hashbufsize = 0, hashbufdata = 0;
391     char *buf, *p, *p2, *lp;
392     size_t bufsize;
393     char *wv[32];
394     int wc;
395     dev_t dev;
396     ino_t inode;
397     time_t mtime;
398     struct hashcache *hc;
399     
400     if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
401         return;
402     bufcat(hashbuf, buf, bufsize);
403     free(buf);
404     while((lp = memchr(hashbuf, '\n', hashbufdata)) != NULL)
405     {
406         *(lp++) = 0;
407         wc = 0;
408         p = hashbuf;
409         while(1)
410         {
411             while((p2 = strchr(p, ' ')) == p)
412                 p++;
413             wv[wc++] = p;
414             if(p2 == NULL)
415             {
416                 break;
417             } else {
418                 *p2 = 0;
419                 p = p2 + 1;
420             }
421         }
422         if(wc != 4)
423         {
424             flog(LOG_ERR, "BUG: unexpected number of words (%i) arrived from hashing process", wc);
425         } else {
426             dev = strtoll(wv[0], NULL, 10);
427             inode = strtoll(wv[1], NULL, 10);
428             mtime = strtol(wv[2], NULL, 10);
429             if((hc = findhashcache(dev, inode)) == NULL)
430             {
431                 hc = newhashcache();
432                 hc->dev = dev;
433                 hc->inode = inode;
434             }
435             hc->mtime = mtime;
436             buf = base64decode(wv[3], NULL);
437             memcpy(hc->tth, buf, 24);
438             free(buf);
439             writehashcache(0);
440         }
441         memmove(hashbuf, lp, hashbufdata -= (lp - hashbuf));
442     }
443 }
444
445 static void hashexit(pid_t pid, int status, struct socket *outsock)
446 {
447     if(pid != hashjob)
448         flog(LOG_ERR, "BUG: hashing process changed PID?! old: %i new %i", hashjob, pid);
449     if(status)
450         flog(LOG_WARNING, "hashing process exited with non-zero status: %i", status);
451     hashjob = 0;
452     checkhashes();
453     putsock(outsock);
454 }
455
456 static int hashfile(char *path)
457 {
458     int i, ret;
459     int fd;
460     int pfd[2];
461     char buf[4096];
462     struct stat sb;
463     struct tigertreehash tth;
464     char digest[24];
465     struct socket *outsock;
466     
467     if((fd = open(path, O_RDONLY)) < 0)
468     {
469         flog(LOG_WARNING, "could not open %s for hashing: %s", path, strerror(errno));
470         return(1);
471     }
472     if(fstat(fd, &sb) < 0)
473     {
474         flog(LOG_WARNING, "could not stat %s while hashing: %s", path, strerror(errno));
475         close(fd);
476         return(1);
477     }
478     if(pipe(pfd) < 0)
479     {
480         flog(LOG_WARNING, "could not create pipe(!): %s", strerror(errno));
481         close(fd);
482         return(1);
483     }
484     hashjob = fork();
485     if(hashjob < 0)
486     {
487         flog(LOG_WARNING, "could not fork(!) hashing process: %s", strerror(errno));
488         close(fd);
489         close(pfd[0]);
490         close(pfd[1]);
491         return(1);
492     }
493     if(hashjob == 0)
494     {
495         nice(10);
496         signal(SIGHUP, SIG_DFL);
497         fd = dup2(fd, 4);
498         pfd[1] = dup2(pfd[1], 3);
499         dup2(fd, 0);
500         dup2(pfd[1], 1);
501         for(i = 3; i < FD_SETSIZE; i++)
502             close(i);
503         initlog();
504         inittigertree(&tth);
505         while((ret = read(0, buf, 4096)) > 0)
506             dotigertree(&tth, buf, ret);
507         if(ret < 0)
508         {
509             flog(LOG_WARNING, "could not read from %s while hashing: %s", path, strerror(errno));
510             exit(1);
511         }
512         synctigertree(&tth);
513         restigertree(&tth, digest);
514         ret = snprintf(buf, sizeof(buf), "%lli %lli %li %s\n", (long long)sb.st_dev, (long long)sb.st_ino, sb.st_mtime, base64encode(digest, 24));
515         write(1, buf, ret);
516         exit(0);
517     }
518     close(fd);
519     close(pfd[1]);
520     outsock = wrapsock(pfd[0]);
521     outsock->readcb = hashread;
522     childcallback(hashjob, (void (*)(pid_t, int, void *))hashexit, outsock);
523     return(0);
524 }
525
526 /*
527  * Call only when hashjob == 0
528  */
529 static void checkhashes(void)
530 {
531     struct sharecache *node;
532     struct hashcache *hc;
533     char *path;
534     
535     node = shareroot->child;
536     for(node = shareroot->child; node != NULL; node = nextscnode(node))
537     {
538         if(node->f.b.type != FILE_REG)
539             continue;
540         if(!node->f.b.hastth)
541         {
542             if(((hc = findhashcache(node->dev, node->inode)) != NULL) && (hc->mtime == node->mtime))
543             {
544                 memcpy(node->hashtth, hc->tth, 24);
545                 node->f.b.hastth = 1;
546                 GCBCHAINDOCB(sharechangecb, sharesize);
547             } else {
548                 path = getfspath(node);
549                 if(hashfile(path))
550                 {
551                     flog(LOG_WARNING, "could not hash %s, unsharing it", path);
552                     freecache(node);
553                     free(path);
554                     flog(LOG_INFO, "sharing %lli bytes", sharesize);
555                     continue;
556                 }
557                 free(path);
558                 return;
559             }
560         }
561     }
562 }
563
564 struct sharecache *nextscnode(struct sharecache *node)
565 {
566     if(node->child != NULL)
567         return(node->child);
568     while(node->next == NULL)
569     {
570         node = node->parent;
571         if(node == shareroot)
572             return(NULL);
573     }
574     return(node->next);
575 }
576
577 static void freescan(struct scanstate *job)
578 {
579     if(job->dd != NULL)
580         closedir(job->dd);
581     free(job);
582 }
583
584 /* No need for optimization; lookup isn't really that common */
585 struct sharecache *findcache(struct sharecache *parent, wchar_t *name)
586 {
587     struct sharecache *node;
588     
589     for(node = parent->child; node != NULL; node = node->next)
590     {
591         if(!wcscmp(node->name, name))
592             return(node);
593     }
594     return(NULL);
595 }
596
597 static void attachcache(struct sharecache *parent, struct sharecache *node)
598 {
599     node->parent = parent;
600     node->next = parent->child;
601     if(parent->child != NULL)
602         parent->child->prev = node;
603     parent->child = node;
604 }
605
606 static void detachcache(struct sharecache *node)
607 {
608     if(node->next != NULL)
609         node->next->prev = node->prev;
610     if(node->prev != NULL)
611         node->prev->next = node->next;
612     if((node->parent != NULL) && (node->parent->child == node))
613         node->parent->child = node->next;
614     node->parent = NULL;
615     node->next = NULL;
616     node->prev = NULL;
617 }
618
619 static void freecache(struct sharecache *node)
620 {
621     struct sharecache *cur, *next;
622     struct scanqueue *q, *nq, **fq;
623     
624     detachcache(node);
625     fq = &scanqueue;
626     for(q = scanqueue; q != NULL; q = nq)
627     {
628         nq = q->next;
629         if(q->state->node == node)
630         {
631             flog(LOG_DEBUG, "freed node %ls cancelled queued scan", node->name);
632             freescan(q->state);
633             *fq = q->next;
634             free(q);
635             continue;
636         }
637         fq = &q->next;
638     }
639     if(node->child != NULL)
640     {
641         for(cur = node->child; cur != NULL; cur = next)
642         {
643             next = cur->next;
644             freecache(cur);
645         }
646     }
647     CBCHAINDOCB(node, share_delete, node);
648     CBCHAINFREE(node, share_delete);
649     sharesize -= node->size;
650     if(node->path != NULL)
651         free(node->path);
652     if(node->name != NULL)
653         free(node->name);
654     free(node);
655 }
656
657 static void freesharepoint(struct sharepoint *share)
658 {
659     struct sharecache *node;
660     
661     if(share->next != NULL)
662         share->next->prev = share->prev;
663     if(share->prev != NULL)
664         share->prev->next = share->next;
665     if(share == shares)
666         shares = share->next;
667     if((node = findcache(shareroot, share->name)) != NULL)
668         freecache(node);
669     free(share->path);
670     free(share->name);
671     free(share);
672 }
673
674 static struct sharecache *newcache(void)
675 {
676     struct sharecache *new;
677     
678     new = smalloc(sizeof(*new));
679     memset(new, 0, sizeof(*new));
680     CBCHAININIT(new, share_delete);
681     return(new);
682 }
683
684 char *getfspath(struct sharecache *node)
685 {
686     char *buf, *mbsname;
687     size_t bufsize;
688     
689     buf = smalloc(bufsize = 64);
690     *buf = 0;
691     while(node != NULL)
692     {
693         if(node->path != NULL)
694         {
695             if(bufsize < strlen(node->path) + strlen(buf) + 1)
696                 buf = srealloc(buf, strlen(node->path) + strlen(buf) + 1);
697             memmove(buf + strlen(node->path), buf, strlen(buf) + 1);
698             memcpy(buf, node->path, strlen(node->path));
699             return(buf);
700         }
701         if((mbsname = icwcstombs(node->name, NULL)) == NULL)
702         {
703             flog(LOG_WARNING, "could not map unicode share name (%ls) into filesystem charset: %s", node->name, strerror(errno));
704             free(buf);
705             return(NULL);
706         }
707         while(bufsize < strlen(mbsname) + 1 + strlen(buf) + 1)
708             buf = srealloc(buf, bufsize *= 2);
709         memmove(buf + strlen(mbsname) + 1, buf, strlen(buf) + 1);
710         memcpy(buf + 1, mbsname, strlen(mbsname));
711         *buf = '/';
712         free(mbsname);
713         node = node->parent;
714     }
715     buf = srealloc(buf, strlen(buf) + 1);
716     return(buf);
717 }
718
719 static int checknode(struct sharecache *node)
720 {
721     char *path;
722     struct stat sb;
723     
724     if(node->parent == NULL)
725     {
726         return(1);
727     } else {
728         if(!checknode(node->parent))
729             return(0);
730         path = getfspath(node);
731         if(stat(path, &sb) < 0)
732         {
733             flog(LOG_INFO, "%s was found to be broken (%s); scheduling rescan of parent", path, strerror(errno));
734             queuescan(node->parent);
735             return(0);
736         } else {
737             return(1);
738         }
739     }
740 }
741
742 int opensharecache(struct sharecache *node)
743 {
744     char *path;
745     int fd, errbak;
746     
747     path = getfspath(node);
748     fd = open(path, O_RDONLY);
749     errbak = errno;
750     if(fd < 0)
751     {
752         flog(LOG_WARNING, "could not open %s: %s", path, strerror(errbak));
753         checknode(node);
754     }
755     free(path);
756     errno = errbak;
757     return(fd);
758 }
759
760 static struct scanstate *newscan(struct sharecache *node)
761 {
762     struct scanstate *new;
763     
764     new = smalloc(sizeof(*new));
765     new->next = NULL;
766     new->node = node;
767     new->dd = NULL;
768     return(new);
769 }
770
771 void queuescan(struct sharecache *node)
772 {
773     struct scanqueue *new;
774     
775     new = smalloc(sizeof(*new));
776     new->state = newscan(node);
777     new->next = scanqueue;
778     scanqueue = new;
779 }
780
781 /* For internal use in doscan() */
782 static void removestale(struct sharecache *node)
783 {
784     struct sharecache *cur, *next;
785     
786     for(cur = node->child; cur != NULL; cur = next)
787     {
788         next = cur->next;
789         if(!cur->f.b.found)
790             freecache(cur);
791     }
792 }
793
794 /* For internal use in doscan() */
795 static void jobdone(void)
796 {
797     struct scanstate *jbuf;
798     
799     jbuf = scanjob;
800     scanjob = jbuf->next;
801     freescan(jbuf);
802     if(scanjob != NULL)
803         fchdir(dirfd(scanjob->dd));
804 }
805
806 int doscan(int quantum)
807 {
808     char *path;
809     wchar_t *wcs;
810     int type;
811     struct sharecache *n;
812     struct scanstate *jbuf;
813     struct scanqueue *qbuf;
814     struct dirent *de;
815     struct stat sb;
816     struct hashcache *hc;
817     int dmask, fmask;
818     static int busybefore = 0;
819     
820     dmask = confgetint("cli", "scandirmask");
821     fmask = confgetint("cli", "scanfilemask");
822     if((scanjob != NULL) && (scanjob->dd != NULL))
823     {
824         while(fchdir(dirfd(scanjob->dd)) < 0)
825         {
826             flog(LOG_WARNING, "could not fchdir to fd %i: %s", dirfd(scanjob->dd), strerror(errno));
827             removestale(scanjob->node);
828             jobdone();
829         }
830     }
831     while(quantum-- > 0)
832     {
833         if(scanjob != NULL)
834         {
835             busybefore = 1;
836         } else {
837             while(scanjob == NULL)
838             {
839                 if(scanqueue == NULL)
840                 {
841                     if(busybefore)
842                     {
843                         flog(LOG_INFO, "sharing %lli bytes", sharesize);
844                         busybefore = 0;
845                         GCBCHAINDOCB(sharechangecb, sharesize);
846                         if(hashjob == 0)
847                             checkhashes();
848                     }
849                     return(0);
850                 }
851                 busybefore = 1;
852                 scanjob = scanqueue->state;
853                 qbuf = scanqueue;
854                 scanqueue = qbuf->next;
855                 free(qbuf);
856                 for(n = scanjob->node->child; n != NULL; n = n->next)
857                     n->f.b.found = 0;
858             }
859         }
860         if(scanjob->dd == NULL)
861         {
862             path = getfspath(scanjob->node);
863             if((scanjob->dd = opendir(path)) == NULL)
864             {
865                 flog(LOG_WARNING, "cannot open directory %s for scanning: %s, deleting from share", path, strerror(errno));
866                 freecache(scanjob->node);
867                 free(path);
868                 jobdone();
869                 continue;
870             }
871             free(path);
872             if(fchdir(dirfd(scanjob->dd)) < 0)
873             {
874                 flog(LOG_WARNING, "could not fchdir to fd %i: %s", dirfd(scanjob->dd), strerror(errno));
875                 jobdone();
876                 continue;
877             }
878         }
879         if((de = readdir(scanjob->dd)) == NULL)
880         {
881             removestale(scanjob->node);
882             jobdone();
883             continue;
884         }
885         if(*de->d_name == '.')
886             continue;
887         if((wcs = icmbstowcs(de->d_name, NULL)) == NULL)
888         {
889             flog(LOG_WARNING, "file name %s has cannot be converted to wchar: %s", de->d_name, strerror(errno));
890             continue;
891         }
892         n = findcache(scanjob->node, wcs);
893         if(stat(de->d_name, &sb) < 0)
894         {
895             free(wcs);
896             if(n != NULL)
897             {
898                 flog(LOG_WARNING, "could not stat %s: %s, deleting from share", de->d_name, strerror(errno));
899                 freecache(n);
900             } else {
901                 flog(LOG_WARNING, "could not stat %s: %s", de->d_name, strerror(errno));
902             }
903             continue;
904         }
905         if(S_ISDIR(sb.st_mode))
906         {
907             if(~sb.st_mode & dmask)
908             {
909                 free(wcs);
910                 continue;
911             }
912             type = FILE_DIR;
913         } else if(S_ISREG(sb.st_mode)) {
914             if(~sb.st_mode & fmask)
915             {
916                 free(wcs);
917                 continue;
918             }
919             type = FILE_REG;
920         } else {
921             flog(LOG_WARNING, "unhandled file type: 0%o", sb.st_mode);
922             free(wcs);
923             continue;
924         }
925         if(n != NULL)
926         {
927             if((n->f.b.type != type) || (n->mtime != sb.st_mtime) || ((type == FILE_REG) && (n->size != sb.st_size)))
928             {
929                 freecache(n);
930                 n = NULL;
931             }
932         }
933         if(n == NULL)
934         {
935             n = newcache();
936             n->name = wcs;
937             if(S_ISREG(sb.st_mode))
938             {
939                 sharesize += (n->size = sb.st_size);
940             } else {
941                 n->size = 0;
942             }
943             n->mtime = sb.st_mtime;
944             n->dev = sb.st_dev;
945             n->inode = sb.st_ino;
946             n->f.b.type = type;
947             attachcache(scanjob->node, n);
948         } else {
949             free(wcs);
950         }
951         n->f.b.found = 1;
952         if(n->f.b.type == FILE_DIR)
953         {
954             jbuf = newscan(n);
955             jbuf->next = scanjob;
956             scanjob = jbuf;
957         } else if(n->f.b.type == FILE_REG) {
958             if(n->f.b.hastth && (n->mtime != sb.st_mtime))
959                 n->f.b.hastth = 0;
960             if(!n->f.b.hastth)
961             {
962                 if((hc = findhashcache(sb.st_dev, sb.st_ino)) != NULL)
963                 {
964                     if(hc->mtime == n->mtime)
965                     {
966                         n->f.b.hastth = 1;
967                         memcpy(n->hashtth, hc->tth, 24);
968                     } else {
969                         freehashcache(hc);
970                     }
971                 }
972             }
973         }
974     }
975     return(1);
976 }
977
978 static void rescancb(int cancelled, void *uudata)
979 {
980     scantimer = NULL;
981     if(!cancelled)
982     {
983         if(scanqueue == NULL)
984             scanshares();
985         else if(confgetint("cli", "rescandelay") > 0)
986             scantimer = timercallback(ntime() + confgetint("cli", "rescandelay"), (void (*)(int, void *))rescancb, NULL);
987     }
988 }
989
990 void scanshares(void)
991 {
992     struct sharepoint *cur;
993     struct sharecache *node;
994     struct stat sb;
995     
996     for(cur = shares; cur != NULL; cur = cur->next)
997     {
998         if((node = findcache(shareroot, cur->name)) == NULL)
999         {
1000             if(stat(cur->path, &sb))
1001             {
1002                 flog(LOG_WARNING, "could not stat share \"%ls\": %s", cur->name, strerror(errno));
1003                 continue;
1004             }
1005             if(!S_ISDIR(sb.st_mode))
1006             {
1007                 flog(LOG_WARNING, "%s is not a directory; won't share it", cur->path);
1008                 continue;
1009             }
1010             node = newcache();
1011             node->name = swcsdup(cur->name);
1012             node->path = sstrdup(cur->path);
1013             if(node->path[strlen(node->path) - 1] == '/')
1014                 node->path[strlen(node->path) - 1] = 0;
1015             node->f.b.type = FILE_DIR;
1016             attachcache(shareroot, node);
1017         }
1018         queuescan(node);
1019     }
1020     if(scantimer != NULL)
1021         canceltimer(scantimer);
1022     if(confgetint("cli", "rescandelay") > 0)
1023         scantimer = timercallback(ntime() + confgetint("cli", "rescandelay"), (void (*)(int, void *))rescancb, NULL);
1024 }
1025
1026 static void preinit(int hup)
1027 {
1028     struct sharepoint *cur;
1029     
1030     if(hup)
1031     {
1032         for(cur = shares; cur != NULL; cur = cur->next)
1033             cur->delete = 1;
1034     } else {
1035         shareroot = newcache();
1036         shareroot->name = swcsdup(L"");
1037         shareroot->f.b.type = FILE_DIR;
1038     }
1039 }
1040
1041 static int rsdelayupdate(struct configvar *var, void *uudata)
1042 {
1043     if(scantimer != NULL)
1044         canceltimer(scantimer);
1045     if(confgetint("cli", "rescandelay") > 0)
1046         scantimer = timercallback(ntime() + var->val.num, (void (*)(int, void *))rescancb, NULL);
1047     return(0);
1048 }
1049
1050 static int init(int hup)
1051 {
1052     struct sharepoint *cur, *next;
1053     
1054     readhashcache();
1055     for(cur = shares; cur != NULL; cur = next)
1056     {
1057         next = cur->next;
1058         if(cur->delete)
1059             freesharepoint(cur);
1060     }
1061     scanshares();
1062     if(!hup)
1063     {
1064         while(doscan(100));
1065         CBREG(confgetvar("cli", "rescandelay"), conf_update, rsdelayupdate, NULL, NULL);
1066     }
1067     return(0);
1068 }
1069
1070 static int run(void)
1071 {
1072     if(hashjob == -1)
1073     {
1074         hashjob = 0;
1075         checkhashes();
1076     }
1077     return(doscan(10));
1078 }
1079
1080 static void terminate(void)
1081 {
1082     if(hashjob != 0)
1083         kill(hashjob, SIGHUP);
1084     while(shares != NULL)
1085         freesharepoint(shares);
1086     freecache(shareroot);
1087 }
1088
1089 static struct module me =
1090 {
1091     .name = "cli",
1092     .conf =
1093     {
1094         .vars = myvars,
1095         .cmds = mycmds
1096     },
1097     .preinit = preinit,
1098     .init = init,
1099     .run = run,
1100     .terminate = terminate
1101 };
1102
1103 MODULE(me)