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