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