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