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