Major rework to use cbchains on sockets.
[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 int 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(0);
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     return(0);
468 }
469
470 static void hashexit(pid_t pid, int status, struct socket *outsock)
471 {
472     if(pid != hashjob)
473         flog(LOG_ERR, "BUG: hashing process changed PID?! old: %i new %i", hashjob, pid);
474     if(status)
475         flog(LOG_WARNING, "hashing process exited with non-zero status: %i", status);
476     hashjob = 0;
477     checkhashes();
478     putsock(outsock);
479 }
480
481 static int hashfile(char *path)
482 {
483     int i, ret;
484     int fd;
485     int pfd[2];
486     char buf[4096];
487     struct stat sb;
488     struct tigertreehash tth;
489     char digest[24];
490     struct socket *outsock;
491     
492     if((fd = open(path, O_RDONLY)) < 0)
493     {
494         flog(LOG_WARNING, "could not open %s for hashing: %s", path, strerror(errno));
495         return(1);
496     }
497     if(fstat(fd, &sb) < 0)
498     {
499         flog(LOG_WARNING, "could not stat %s while hashing: %s", path, strerror(errno));
500         close(fd);
501         return(1);
502     }
503     if(pipe(pfd) < 0)
504     {
505         flog(LOG_WARNING, "could not create pipe(!): %s", strerror(errno));
506         close(fd);
507         return(1);
508     }
509     hashjob = fork();
510     if(hashjob < 0)
511     {
512         flog(LOG_WARNING, "could not fork(!) hashing process: %s", strerror(errno));
513         close(fd);
514         close(pfd[0]);
515         close(pfd[1]);
516         return(1);
517     }
518     if(hashjob == 0)
519     {
520         nice(10);
521         signal(SIGHUP, SIG_DFL);
522         fd = dup2(fd, 4);
523         pfd[1] = dup2(pfd[1], 3);
524         dup2(fd, 0);
525         dup2(pfd[1], 1);
526         for(i = 3; i < FD_SETSIZE; i++)
527             close(i);
528         initlog();
529         inittigertree(&tth);
530         while((ret = read(0, buf, 4096)) > 0)
531             dotigertree(&tth, buf, ret);
532         if(ret < 0)
533         {
534             flog(LOG_WARNING, "could not read from %s while hashing: %s", path, strerror(errno));
535             exit(1);
536         }
537         synctigertree(&tth);
538         restigertree(&tth, digest);
539         ret = snprintf(buf, sizeof(buf), "%lli %lli %li %s\n", sb.st_dev, (long long)sb.st_ino, sb.st_mtime, base64encode(digest, 24));
540         write(1, buf, ret);
541         exit(0);
542     }
543     close(fd);
544     close(pfd[1]);
545     outsock = wrapsock(pfd[0]);
546     CBREG(outsock, socket_read, hashread, NULL, NULL);
547     childcallback(hashjob, (void (*)(pid_t, int, void *))hashexit, outsock);
548     return(0);
549 }
550
551 /*
552  * Call only when hashjob == 0
553  */
554 static void checkhashes(void)
555 {
556     struct sharecache *node;
557     struct hashcache *hc;
558     char *path;
559     
560     node = shareroot->child;
561     for(node = shareroot->child; node != NULL; node = nextscnode(node))
562     {
563         if(node->f.b.type != FILE_REG)
564             continue;
565         if(!node->f.b.hastth)
566         {
567             if(((hc = findhashcache(node->dev, node->inode)) != NULL) && (hc->mtime == node->mtime))
568             {
569                 memcpy(node->hashtth, hc->tth, 24);
570                 node->f.b.hastth = 1;
571                 GCBCHAINDOCB(sharechangecb, sharesize);
572             } else {
573                 path = getfspath(node);
574                 if(hashfile(path))
575                 {
576                     flog(LOG_WARNING, "could not hash %s, unsharing it", path);
577                     freecache(node);
578                     free(path);
579                     flog(LOG_INFO, "sharing %lli bytes", sharesize);
580                     continue;
581                 }
582                 free(path);
583                 return;
584             }
585         }
586     }
587 }
588
589 struct sharecache *nextscnode(struct sharecache *node)
590 {
591     if(node->child != NULL)
592         return(node->child);
593     while(node->next == NULL)
594     {
595         node = node->parent;
596         if(node == shareroot)
597             return(NULL);
598     }
599     return(node->next);
600 }
601
602 static void freescan(struct scanstate *job)
603 {
604     if(job->dd != NULL)
605         closedir(job->dd);
606     free(job);
607 }
608
609 /* No need for optimization; lookup isn't really that common */
610 struct sharecache *findcache(struct sharecache *parent, wchar_t *name)
611 {
612     struct sharecache *node;
613     
614     for(node = parent->child; node != NULL; node = node->next)
615     {
616         if(!wcscmp(node->name, name))
617             return(node);
618     }
619     return(NULL);
620 }
621
622 static void attachcache(struct sharecache *parent, struct sharecache *node)
623 {
624     node->parent = parent;
625     node->next = parent->child;
626     if(parent->child != NULL)
627         parent->child->prev = node;
628     parent->child = node;
629 }
630
631 static void detachcache(struct sharecache *node)
632 {
633     if(node->next != NULL)
634         node->next->prev = node->prev;
635     if(node->prev != NULL)
636         node->prev->next = node->next;
637     if((node->parent != NULL) && (node->parent->child == node))
638         node->parent->child = node->next;
639     node->parent = NULL;
640     node->next = NULL;
641     node->prev = NULL;
642 }
643
644 static void freecache(struct sharecache *node)
645 {
646     struct sharecache *cur, *next;
647     struct scanqueue *q, *nq, **fq;
648     
649     detachcache(node);
650     fq = &scanqueue;
651     for(q = scanqueue; q != NULL; q = nq)
652     {
653         nq = q->next;
654         if(q->state->node == node)
655         {
656             flog(LOG_DEBUG, "freed node %ls cancelled queued scan", node->name);
657             freescan(q->state);
658             *fq = q->next;
659             free(q);
660             continue;
661         }
662         fq = &q->next;
663     }
664     if(node->child != NULL)
665     {
666         for(cur = node->child; cur != NULL; cur = next)
667         {
668             next = cur->next;
669             freecache(cur);
670         }
671     }
672     CBCHAINDOCB(node, share_delete, node);
673     CBCHAINFREE(node, share_delete);
674     sharesize -= node->size;
675     if(node->path != NULL)
676         free(node->path);
677     if(node->name != NULL)
678         free(node->name);
679     free(node);
680 }
681
682 static void freesharepoint(struct sharepoint *share)
683 {
684     struct sharecache *node;
685     
686     if(share->next != NULL)
687         share->next->prev = share->prev;
688     if(share->prev != NULL)
689         share->prev->next = share->next;
690     if(share == shares)
691         shares = share->next;
692     if((node = findcache(shareroot, share->name)) != NULL)
693         freecache(node);
694     free(share->path);
695     free(share->name);
696     free(share);
697 }
698
699 static struct sharecache *newcache(void)
700 {
701     struct sharecache *new;
702     
703     new = smalloc(sizeof(*new));
704     memset(new, 0, sizeof(*new));
705     CBCHAININIT(new, share_delete);
706     return(new);
707 }
708
709 char *getfspath(struct sharecache *node)
710 {
711     char *buf, *mbsname;
712     size_t bufsize;
713     
714     buf = smalloc(bufsize = 64);
715     *buf = 0;
716     while(node != NULL)
717     {
718         if(node->path != NULL)
719         {
720             if(bufsize < strlen(node->path) + strlen(buf) + 1)
721                 buf = srealloc(buf, strlen(node->path) + strlen(buf) + 1);
722             memmove(buf + strlen(node->path), buf, strlen(buf) + 1);
723             memcpy(buf, node->path, strlen(node->path));
724             return(buf);
725         }
726         if((mbsname = icwcstombs(node->name, NULL)) == NULL)
727         {
728             flog(LOG_WARNING, "could not map unicode share name (%ls) into filesystem charset: %s", node->name, strerror(errno));
729             free(buf);
730             return(NULL);
731         }
732         while(bufsize < strlen(mbsname) + 1 + strlen(buf) + 1)
733             buf = srealloc(buf, bufsize *= 2);
734         memmove(buf + strlen(mbsname) + 1, buf, strlen(buf) + 1);
735         memcpy(buf + 1, mbsname, strlen(mbsname));
736         *buf = '/';
737         free(mbsname);
738         node = node->parent;
739     }
740     buf = srealloc(buf, strlen(buf) + 1);
741     return(buf);
742 }
743
744 static int checknode(struct sharecache *node)
745 {
746     char *path;
747     struct stat sb;
748     
749     if(node->parent == NULL)
750     {
751         return(1);
752     } else {
753         if(!checknode(node->parent))
754             return(0);
755         path = getfspath(node);
756         if(stat(path, &sb) < 0)
757         {
758             flog(LOG_INFO, "%s was found to be broken (%s); scheduling rescan of parent", path, strerror(errno));
759             queuescan(node->parent);
760             return(0);
761         } else {
762             return(1);
763         }
764     }
765 }
766
767 int opensharecache(struct sharecache *node)
768 {
769     char *path;
770     int fd, errbak;
771     
772     path = getfspath(node);
773     fd = open(path, O_RDONLY);
774     errbak = errno;
775     if(fd < 0)
776     {
777         flog(LOG_WARNING, "could not open %s: %s", path, strerror(errbak));
778         checknode(node);
779     }
780     free(path);
781     errno = errbak;
782     return(fd);
783 }
784
785 static struct scanstate *newscan(struct sharecache *node)
786 {
787     struct scanstate *new;
788     
789     new = smalloc(sizeof(*new));
790     new->next = NULL;
791     new->node = node;
792     new->dd = NULL;
793     return(new);
794 }
795
796 void queuescan(struct sharecache *node)
797 {
798     struct scanqueue *new;
799     
800     new = smalloc(sizeof(*new));
801     new->state = newscan(node);
802     new->next = scanqueue;
803     scanqueue = new;
804 }
805
806 /* For internal use in doscan() */
807 static void removestale(struct sharecache *node)
808 {
809     struct sharecache *cur, *next;
810     
811     for(cur = node->child; cur != NULL; cur = next)
812     {
813         next = cur->next;
814         if(!cur->f.b.found)
815             freecache(cur);
816     }
817 }
818
819 /* For internal use in doscan() */
820 static void jobdone(void)
821 {
822     struct scanstate *jbuf;
823     
824     jbuf = scanjob;
825     scanjob = jbuf->next;
826     freescan(jbuf);
827     if(scanjob != NULL)
828         fchdir(dirfd(scanjob->dd));
829 }
830
831 int doscan(int quantum)
832 {
833     char *path;
834     wchar_t *wcs;
835     int type;
836     struct sharecache *n;
837     struct scanstate *jbuf;
838     struct scanqueue *qbuf;
839     struct dirent *de;
840     struct stat sb;
841     struct hashcache *hc;
842     int dmask, fmask;
843     static int busybefore = 0;
844     
845     dmask = confgetint("cli", "scandirmask");
846     fmask = confgetint("cli", "scanfilemask");
847     if((scanjob != NULL) && (scanjob->dd != NULL))
848     {
849         while(fchdir(dirfd(scanjob->dd)) < 0)
850         {
851             flog(LOG_WARNING, "could not fchdir to fd %i: %s", dirfd(scanjob->dd), strerror(errno));
852             removestale(scanjob->node);
853             jobdone();
854         }
855     }
856     while(quantum-- > 0)
857     {
858         if(scanjob != NULL)
859         {
860             busybefore = 1;
861         } else {
862             while(scanjob == NULL)
863             {
864                 if(scanqueue == NULL)
865                 {
866                     if(busybefore)
867                     {
868                         flog(LOG_INFO, "sharing %lli bytes", sharesize);
869                         busybefore = 0;
870                         GCBCHAINDOCB(sharechangecb, sharesize);
871                         if(hashjob == 0)
872                             checkhashes();
873                     }
874                     return(0);
875                 }
876                 busybefore = 1;
877                 scanjob = scanqueue->state;
878                 qbuf = scanqueue;
879                 scanqueue = qbuf->next;
880                 free(qbuf);
881                 for(n = scanjob->node->child; n != NULL; n = n->next)
882                     n->f.b.found = 0;
883             }
884         }
885         if(scanjob->dd == NULL)
886         {
887             path = getfspath(scanjob->node);
888             if((scanjob->dd = opendir(path)) == NULL)
889             {
890                 flog(LOG_WARNING, "cannot open directory %s for scanning: %s, deleting from share", path, strerror(errno));
891                 freecache(scanjob->node);
892                 free(path);
893                 jobdone();
894                 continue;
895             }
896             free(path);
897             if(fchdir(dirfd(scanjob->dd)) < 0)
898             {
899                 flog(LOG_WARNING, "could not fchdir to fd %i: %s", dirfd(scanjob->dd), strerror(errno));
900                 jobdone();
901                 continue;
902             }
903         }
904         if((de = readdir(scanjob->dd)) == NULL)
905         {
906             removestale(scanjob->node);
907             jobdone();
908             continue;
909         }
910         if(*de->d_name == '.')
911             continue;
912         if((wcs = icmbstowcs(de->d_name, NULL)) == NULL)
913         {
914             flog(LOG_WARNING, "file name %s has cannot be converted to wchar: %s", de->d_name, strerror(errno));
915             continue;
916         }
917         n = findcache(scanjob->node, wcs);
918         if(stat(de->d_name, &sb) < 0)
919         {
920             free(wcs);
921             if(n != NULL)
922             {
923                 flog(LOG_WARNING, "could not stat %s: %s, deleting from share", de->d_name, strerror(errno));
924                 freecache(n);
925             } else {
926                 flog(LOG_WARNING, "could not stat %s: %s", de->d_name, strerror(errno));
927             }
928             continue;
929         }
930         if(S_ISDIR(sb.st_mode))
931         {
932             if(~sb.st_mode & dmask)
933             {
934                 free(wcs);
935                 continue;
936             }
937             type = FILE_DIR;
938         } else if(S_ISREG(sb.st_mode)) {
939             if(~sb.st_mode & fmask)
940             {
941                 free(wcs);
942                 continue;
943             }
944             type = FILE_REG;
945         } else {
946             flog(LOG_WARNING, "unhandled file type: 0%o", sb.st_mode);
947             free(wcs);
948             continue;
949         }
950         if(n != NULL)
951         {
952             if((n->f.b.type != type) || (n->mtime != sb.st_mtime) || ((type == FILE_REG) && (n->size != sb.st_size)))
953             {
954                 freecache(n);
955                 n = NULL;
956             }
957         }
958         if(n == NULL)
959         {
960             n = newcache();
961             n->name = wcs;
962             if(S_ISREG(sb.st_mode))
963             {
964                 sharesize += (n->size = sb.st_size);
965             } else {
966                 n->size = 0;
967             }
968             n->mtime = sb.st_mtime;
969             n->dev = sb.st_dev;
970             n->inode = sb.st_ino;
971             n->f.b.type = type;
972             attachcache(scanjob->node, n);
973         } else {
974             free(wcs);
975         }
976         n->f.b.found = 1;
977         if(n->f.b.type == FILE_DIR)
978         {
979             jbuf = newscan(n);
980             jbuf->next = scanjob;
981             scanjob = jbuf;
982         } else if(n->f.b.type == FILE_REG) {
983             if(n->f.b.hastth && (n->mtime != sb.st_mtime))
984                 n->f.b.hastth = 0;
985             if(!n->f.b.hastth)
986             {
987                 if((hc = findhashcache(sb.st_dev, sb.st_ino)) != NULL)
988                 {
989                     if(hc->mtime == n->mtime)
990                     {
991                         n->f.b.hastth = 1;
992                         memcpy(n->hashtth, hc->tth, 24);
993                     } else {
994                         freehashcache(hc);
995                     }
996                 }
997             }
998         }
999     }
1000     return(1);
1001 }
1002
1003 void scanshares(void)
1004 {
1005     struct sharepoint *cur;
1006     struct sharecache *node;
1007     struct stat sb;
1008     
1009     for(cur = shares; cur != NULL; cur = cur->next)
1010     {
1011         if((node = findcache(shareroot, cur->name)) == NULL)
1012         {
1013             if(stat(cur->path, &sb))
1014             {
1015                 flog(LOG_WARNING, "could not stat share \"%ls\": %s", cur->name, strerror(errno));
1016                 continue;
1017             }
1018             if(!S_ISDIR(sb.st_mode))
1019             {
1020                 flog(LOG_WARNING, "%s is not a directory; won't share it", cur->path);
1021                 continue;
1022             }
1023             node = newcache();
1024             node->name = swcsdup(cur->name);
1025             node->path = sstrdup(cur->path);
1026             if(node->path[strlen(node->path) - 1] == '/')
1027                 node->path[strlen(node->path) - 1] = 0;
1028             node->f.b.type = FILE_DIR;
1029             attachcache(shareroot, node);
1030         }
1031         queuescan(node);
1032     }
1033 }
1034
1035 static void preinit(int hup)
1036 {
1037     struct sharepoint *cur;
1038     
1039     if(hup)
1040     {
1041         for(cur = shares; cur != NULL; cur = cur->next)
1042             cur->delete = 1;
1043     } else {
1044         shareroot = newcache();
1045         shareroot->name = swcsdup(L"");
1046         shareroot->f.b.type = FILE_DIR;
1047     }
1048 }
1049
1050 static int init(int hup)
1051 {
1052     struct sharepoint *cur, *next;
1053     
1054     readhashcache();
1055     for(cur = shares; cur != NULL; cur = next)
1056     {
1057         next = cur->next;
1058         if(cur->delete)
1059             freesharepoint(cur);
1060     }
1061     scanshares();
1062     if(!hup)
1063         while(doscan(100));
1064     return(0);
1065 }
1066
1067 static int run(void)
1068 {
1069     if(hashjob == -1)
1070     {
1071         hashjob = 0;
1072         checkhashes();
1073     }
1074     return(doscan(10));
1075 }
1076
1077 static void terminate(void)
1078 {
1079     if(hashjob != 0)
1080         kill(hashjob, SIGHUP);
1081     while(shares != NULL)
1082         freesharepoint(shares);
1083     freecache(shareroot);
1084 }
1085
1086 static struct module me =
1087 {
1088     .name = "cli",
1089     .conf =
1090     {
1091         .vars = myvars,
1092         .cmds = mycmds
1093     },
1094     .preinit = preinit,
1095     .init = init,
1096     .run = run,
1097     .terminate = terminate
1098 };
1099
1100 MODULE(me)