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