203a47dcf1b4d7b36e7584b53cc8baed17a9761a
[akaros.git] / tests / cs.c
1 /* 
2  * This file is part of the UCB release of Plan 9. It is subject to the license
3  * terms in the LICENSE file found in the top-level directory of this
4  * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
5  * part of the UCB release of Plan 9, including this file, may be copied,
6  * modified, propagated, or distributed except according to the terms contained
7  * in the LICENSE file.
8  */
9 #include <stdlib.h>
10
11 #include <stdio.h>
12 #include <parlib.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <signal.h>
17 #include <pthread.h>
18 #include <fcntl.h>
19 #include <ctype.h>
20 #include <error.h>
21 #include <iplib.h>
22 #include <dir.h>
23 #include <ndb.h>
24 #include <fcall.h>
25
26 enum
27 {
28         Nreply=                 20,
29         Maxreply=               256,
30         Maxrequest=             128,
31         Maxpath=                128,
32         Maxfdata=               8192,
33         Maxhost=                64,             /* maximum host name size */
34         Maxservice=             64,             /* maximum service name size */
35
36         Qdir=                   0,
37         Qcs=                    1,
38 };
39
40 typedef struct Mfile    Mfile;
41 typedef struct Mlist    Mlist;
42 typedef struct Network  Network;
43 typedef struct Flushreq Flushreq;
44 typedef struct Job      Job;
45
46 int vers;               /* incremented each clone/attach */
47 /* need to resolve the #inluce for all this stuff. */
48 #define DMDIR              0x80000000      /* mode bit for directories */
49 #define QTDIR 0x80
50 #define QTFILE 0
51 #define ERRMAX 128
52
53 struct Mfile
54 {
55         int             busy;
56
57         char            *user;
58         struct qid     qid;
59         int             fid;
60
61         /*
62          *  current request
63          */
64         char            *net;
65         char            *host;
66         char            *serv;
67         char            *rem;
68
69         /*
70          *  result of the last lookup
71          */
72         Network         *nextnet;
73         int             nreply;
74         char            *reply[Nreply];
75         int             replylen[Nreply];
76 };
77
78 struct Mlist
79 {
80         Mlist   *next;
81         Mfile   mf;
82 };
83
84
85 /*
86  *  active requests
87  */
88 struct Job
89 {
90         Job     *next;
91         int     flushed;
92         struct fcall    request;
93         struct fcall    reply;
94         pthread_t thread;
95 };
96
97 //spinlock_t    joblock;
98 int joblock;
99 Job     *joblist;
100
101 Mlist   *mlist;
102 int     mfd[2];
103 int     debug;
104 int     paranoia;
105 int     ipv6lookups = 1;
106 char    *dbfile = "lib/ndb/local";
107 struct ndb      *db, *netdb;
108
109 void    rversion(Job*);
110 void    rflush(Job*);
111 void    rattach(Job*, Mfile*);
112 char*   rwalk(Job*, Mfile*);
113 void    ropen(Job*, Mfile*);
114 void    rcreate(Job*, Mfile*);
115 void    rread(Job*, Mfile*);
116 void    rwrite(Job*, Mfile*);
117 void    rclunk(Job*, Mfile*);
118 void    rremove(Job*, Mfile*);
119 void    rstat(Job*, Mfile*);
120 void    rwstat(Job*, Mfile*);
121 void    rauth(Job*);
122 void    sendmsg(Job*, char*);
123 void    mountinit(char*, char*);
124 void    io(void);
125 void    ndbinit(void);
126 void    netinit(int);
127 void    netadd(char*);
128 char    *genquery(Mfile*, char*);
129 char*   ipinfoquery(Mfile*, char**, int);
130 int     needproto(Network*, struct ndbtuple*);
131 int     lookup(Mfile*);
132 struct ndbtuple*        reorder(struct ndbtuple*, struct ndbtuple*);
133 void    ipid(void);
134 void    readipinterfaces(void);
135 void*   emalloc(int);
136 char*   estrdup(char*);
137 Job*    newjob(void);
138 void    freejob(Job*);
139 void    setext(char*, int, char*);
140 void    cleanmf(Mfile*);
141
142 extern void     paralloc(void);
143
144 spinlock_t      dblock;         /* mutex on database operations */
145 spinlock_t      netlock;        /* mutex for netinit() */
146
147 char    *logfile = "cs";
148 char    *paranoiafile = "cs.paranoia";
149
150 char    mntpt[Maxpath];
151 char    netndb[Maxpath];
152
153 /*
154  *  Network specific translators
155  */
156 struct ndbtuple*        iplookup(Network*, char*, char*, int);
157 char*           iptrans(struct ndbtuple*, Network*, char*, char*, int);
158 struct ndbtuple*        telcolookup(Network*, char*, char*, int);
159 char*           telcotrans(struct ndbtuple*, Network*, char*, char*, int);
160 struct ndbtuple*        dnsiplookup(char*, struct ndbs*);
161
162 struct Network
163 {
164         char            *net;
165         struct ndbtuple *(*lookup)(Network*, char*, char*, int);
166         char            *(*trans)(struct ndbtuple*, Network*, char*, char*, int);
167         int             considered;             /* flag: ignored for "net!"? */
168         int             fasttimeouthack;        /* flag. was for IL */
169         Network         *next;
170 };
171
172 enum
173 {
174         Ntcp = 0,
175 };
176
177 /*
178  *  net doesn't apply to (r)udp, icmp(v6), or telco (for speed).
179  */
180 Network network[] = {
181 [Ntcp]  { "tcp",        iplookup,       iptrans,        0 },
182         { "udp",        iplookup,       iptrans,        1 },
183         { "icmp",       iplookup,       iptrans,        1 },
184         { "icmpv6",     iplookup,       iptrans,        1 },
185         { "rudp",       iplookup,       iptrans,        1 },
186         { "ssh",        iplookup,       iptrans,        1 },
187         { "telco",      telcolookup,    telcotrans,     1 },
188         { 0 },
189 };
190
191 spinlock_t ipifclock;
192 struct ipifc *ipifcs;
193
194 char    eaddr[16];              /* ascii ethernet address */
195 char    ipaddr[64];             /* ascii internet address */
196 uint8_t ipa[IPaddrlen];         /* binary internet address */
197 char    *mysysname;
198
199 Network *netlist;               /* networks ordered by preference */
200 Network *last;
201
202 static void
203 nstrcpy(char *to, char *from, int len)
204 {
205         strncpy(to, from, len);
206         to[len-1] = 0;
207 }
208
209 char *argv0;
210 void
211 usage(void)
212 {
213         fprintf(stderr, "CS:usage: %s [-dn] [-f ndb-file] [-x netmtpt]\n", argv0);
214         fprintf(stderr, "CS:usage");
215         exit(1);
216 }
217
218 /*
219  * based on libthread's threadsetname, but drags in less library code.
220  * actually just sets the arguments displayed.
221  */
222 void
223 procsetname(char *fmt, ...)
224 {
225 /* someday ... */
226 #if 0
227         int fd;
228         char *cmdname;
229         char buf[128];
230         va_list arg;
231
232         va_start(arg, fmt);
233         cmdname = vsmprint(fmt, arg);
234         va_end(arg);
235         if (cmdname == NULL)
236                 return;
237         snprintf(buf, sizeof buf, "#p/%d/args", getpid());
238         if((fd = open(buf, OWRITE)) >= 0){
239                 write(fd, cmdname, strlen(cmdname)+1);
240                 close(fd);
241         }
242         free(cmdname);
243 #endif
244 }
245
246 void
247 main(int argc, char *argv[])
248 {
249         int justsetname;
250         char ext[Maxpath], servefile[Maxpath];
251         argv0 = argv[0];
252         justsetname = 0;
253         setnetmtpt(mntpt, sizeof(mntpt), NULL);
254         ext[0] = 0;
255         argc--, argv++;
256         while (argc && **argv == '-'){
257                 switch(argv[0][1]){
258         case '4':
259                 ipv6lookups = 0;
260                 break;
261         case 'd':
262                 debug = 1;
263                 break;
264         case 'f':
265                 if (argc < 2)
266                         usage();
267                 dbfile = argv[1];
268                 argc--,argv++;
269                 break;
270         case 'n':
271                 justsetname = 1;
272                 break;
273         case 'x':
274                 if (argc < 2)
275                         usage();
276                 setnetmtpt(mntpt, sizeof(mntpt), argv[1]);
277                 argc--,argv++;
278                 setext(ext, sizeof(ext), mntpt);
279                 break;
280                 }
281                 argc--,argv++;
282         }
283
284         //rfork(RFREND|RFNOTEG);
285
286         snprintf(servefile, sizeof(servefile), "#s/cs%s", ext);
287         snprintf(netndb, sizeof(netndb), "%s/ndb", mntpt);
288         syscall(SYS_nunmount, (unsigned long)servefile, (unsigned long)mntpt);
289         remove(servefile);
290
291         ndbinit();
292         netinit(0);
293
294         if(!justsetname){
295                 mountinit(servefile, mntpt);
296                 io();
297         }
298         exit(0);
299 }
300
301 /*
302  *  if a mount point is specified, set the cs extention to be the mount point
303  *  with '_'s replacing '/'s
304  */
305 void
306 setext(char *ext, int n, char *p)
307 {
308         int i, c;
309
310         n--;
311         for(i = 0; i < n; i++){
312                 c = p[i];
313                 if(c == 0)
314                         break;
315                 if(c == '/')
316                         c = '_';
317                 ext[i] = c;
318         }
319         ext[i] = 0;
320 }
321
322 void
323 mountinit(char *service, char *mntpt)
324 {
325         int f;
326         int p[2];
327         char buf[32];
328         int ret;
329
330         ret = syscall(SYS_pipe, (unsigned long)p);
331         if (ret < 0){
332                 error(1, 0, "pipe: %r");
333                 exit(1);
334         }
335
336         /*
337          *  make a /srv/cs
338          * ORCLOSE means remove on last close. Handy. Not here yet. 
339          */
340         f = open(service, O_WRONLY|O_CREAT/*|ORCLOSE*/, 0666);
341 printf("open %s gets %d\n", service, f);
342         if(f < 0)
343                 error(1, 0, "%s: %r",service);
344         snprintf(buf, sizeof(buf), "%d", p[1]);
345         if(write(f, buf, strlen(buf)) != strlen(buf))
346                 error(1, 0, "Write %s: %r", service);
347         /* using #s: we create a pipe and drop it into #s. 
348          * we no longer mount. That's up to you.
349          * #s will route requests to us.
350          */
351         close(p[1]);
352
353         mfd[0] = mfd[1] = p[0];
354 }
355
356 void
357 ndbinit(void)
358 {
359         db = ndbopen(dbfile);
360         if(db == NULL)
361                 error(1, 0, "%s: %r","can't open network database");
362
363         netdb = ndbopen(netndb);
364         if(netdb != NULL){
365                 netdb->nohash = 1;
366                 db = ndbcat(netdb, db);
367         }
368 }
369
370 Mfile*
371 newfid(int fid)
372 {
373         Mlist *f, *ff;
374         Mfile *mf;
375
376         ff = 0;
377         for(f = mlist; f; f = f->next)
378                 if(f->mf.busy && f->mf.fid == fid)
379                         return &f->mf;
380                 else if(!ff && !f->mf.busy)
381                         ff = f;
382         if(ff == 0){
383                 ff = emalloc(sizeof *f);
384                 ff->next = mlist;
385                 mlist = ff;
386         }
387         mf = &ff->mf;
388         memset(mf, 0, sizeof *mf);
389         mf->fid = fid;
390         return mf;
391 }
392
393 Job*
394 newjob(void)
395 {
396         Job *job;
397
398         job = calloc(1, sizeof(Job));
399         if (! job){
400                 error(1, 0, "%s: %r","job calloc");
401         }
402 #warning "fix lock"
403 //      //lock(&joblock);
404         job->next = joblist;
405         joblist = job;
406         job->request.tag = -1;
407 //      //unlock(&joblock);
408         return job;
409 }
410
411 void
412 freejob(Job *job)
413 {
414         Job **l;
415 return;
416         //lock(&joblock);
417         for(l = &joblist; *l; l = &(*l)->next){
418                 if((*l) == job){
419                         *l = job->next;
420                         free(job);
421                         break;
422                 }
423         }
424         //unlock(&joblock);
425 }
426
427 void
428 flushjob(int tag)
429 {
430         Job *job;
431
432         //lock(&joblock);
433         for(job = joblist; job; job = job->next){
434                 if(job->request.tag == tag && job->request.type != Tflush){
435                         job->flushed = 1;
436                         break;
437                 }
438         }
439         //unlock(&joblock);
440 }
441
442 void *job_thread(void* arg)
443 {
444         Mfile *mf;
445         Job *job = arg;
446         //lock(&dblock);
447 printf("JOB!\n");
448         mf = newfid(job->request.fid);
449
450 printf("NEWFID is %p\n", mf);
451         if(debug)
452                 fprintf(stderr, "CS:%F", &job->request);
453 printf("DO %d\n", job->request.type);
454         switch(job->request.type){
455         default:
456                 fprintf(stderr, "CS:unknown request type %d", job->request.type);
457                 break;
458         case Tversion:
459                 rversion(job);
460                 break;
461         case Tauth:
462                 rauth(job);
463                 break;
464         case Tflush:
465                 rflush(job);
466                 break;
467         case Tattach:
468                 rattach(job, mf);
469                 break;
470         case Twalk:
471                 rwalk(job, mf);
472                 break;
473         case Topen:
474                 ropen(job, mf);
475                 break;
476         case Tcreate:
477                 rcreate(job, mf);
478                 break;
479         case Tread:
480                 rread(job, mf);
481                 break;
482         case Twrite:
483                 rwrite(job, mf);
484                 break;
485         case Tclunk:
486                 rclunk(job, mf);
487                 break;
488         case Tremove:
489                 rremove(job, mf);
490                 break;
491         case Tstat:
492                 rstat(job, mf);
493                 break;
494         case Twstat:
495                 rwstat(job, mf);
496                 break;
497         }
498         //unlock(&dblock);
499
500         freejob(job);
501
502         fprintf(stderr, "CS:Job done\n");
503         return 0;
504 }
505
506
507 void
508 io(void)
509 {
510         long n;
511
512         uint8_t mdata[IOHDRSZ + Maxfdata];
513         Job *job;
514
515         /*
516          * each request is handled via a thread. Somewhat less efficient than the old
517          * cs but way cleaner. 
518          */
519
520         for(;;){
521                 n = read9pmsg(mfd[0], mdata, sizeof mdata);
522                 if(n<=0)
523                         error(1, 0, "%s: %r","mount read");
524                 job = newjob();
525                 if(convM2S(mdata, n, &job->request) != n){
526                         error(1, 0, "format error %ux %ux %ux %ux %ux",
527                                 mdata[0], mdata[1], mdata[2], mdata[3], mdata[4]);
528                         freejob(job);
529                         continue;
530                 }
531                 /* stash the thread in the job so we can join them all
532                  * later if we want to.
533                  */
534 #if 0
535 printf("RUN THAT JOB!\n");
536                 if (pthread_create(&job->thread, NULL, &job_thread, job)) {
537 printf("ERROR!\n");
538                         error(1, 0, "%s: %r","Failed to create job");
539                         continue;
540                 }
541 #endif
542         job_thread(job);
543
544
545         }
546 }
547
548 void
549 rversion(Job *job)
550 {
551         if(job->request.msize > IOHDRSZ + Maxfdata)
552                 job->reply.msize = IOHDRSZ + Maxfdata;
553         else
554                 job->reply.msize = job->request.msize;
555         if(strncmp(job->request.version, "9P2000", 6) != 0)
556                 sendmsg(job, "unknown 9P version");
557         else{
558                 job->reply.version = "9P2000";
559                 sendmsg(job, 0);
560         }
561 }
562
563 void
564 rauth(Job *job)
565 {
566         sendmsg(job, "cs: authentication not required");
567 }
568
569 /*
570  *  don't flush till all the threads  are done
571  */
572 void
573 rflush(Job *job)
574 {
575         flushjob(job->request.oldtag);
576         sendmsg(job, 0);
577 }
578
579 void
580 rattach(Job *job, Mfile *mf)
581 {
582         if(mf->busy == 0){
583                 mf->busy = 1;
584                 mf->user = estrdup(job->request.uname);
585         }
586         mf->qid.vers = vers++;
587         mf->qid.type = QTDIR;
588         mf->qid.path = 0LL;
589         job->reply.qid = mf->qid;
590         sendmsg(job, 0);
591 }
592
593
594 char*
595 rwalk(Job *job, Mfile *mf)
596 {
597         char *err;
598         char **elems;
599         int nelems;
600         int i;
601         Mfile *nmf;
602         struct qid qid;
603
604         err = 0;
605         nmf = NULL;
606         elems = job->request.wname;
607         nelems = job->request.nwname;
608         job->reply.nwqid = 0;
609
610         if(job->request.newfid != job->request.fid){
611                 /* clone fid */
612                 nmf = newfid(job->request.newfid);
613                 if(nmf->busy){
614                         nmf = NULL;
615                         err = "clone to used channel";
616                         goto send;
617                 }
618                 *nmf = *mf;
619                 nmf->user = estrdup(mf->user);
620                 nmf->fid = job->request.newfid;
621                 nmf->qid.vers = vers++;
622                 mf = nmf;
623         }
624         /* else nmf will be nil */
625
626         qid = mf->qid;
627         if(nelems > 0){
628                 /* walk fid */
629                 for(i=0; i<nelems && i<MAXWELEM; i++){
630 printf("cs: i %d nelems %d \n", i, nelems);
631                         if((qid.type & QTDIR) == 0){
632                                 err = "not a directory";
633                                 break;
634                         }
635                         if(strcmp(elems[i], "..") == 0 || strcmp(elems[i], ".") == 0){
636                                 qid.type = QTDIR;
637                                 qid.path = Qdir;
638     Found:
639                                 job->reply.wqid[i] = qid;
640                                 job->reply.nwqid++;
641                                 continue;
642                         }
643                         if(strcmp(elems[i], "cs") == 0){
644                                 qid.type = QTFILE;
645                                 qid.path = Qcs;
646 printf("found cs, goto Found\n");
647                                 goto Found;
648                         }
649                         err = malloc(4096);
650                         snprintf(err, 4096,"%s:file does not exist", elems[i]);
651                         break;
652                 }
653         }
654
655     send:
656         if(nmf != NULL && (err!=NULL || job->reply.nwqid<nelems)){
657                 cleanmf(nmf);
658                 free(nmf->user);
659                 nmf->user = 0;
660                 nmf->busy = 0;
661                 nmf->fid = 0;
662         }
663         if(err == NULL)
664                 mf->qid = qid;
665         sendmsg(job, err);
666         free(err);
667         /* shoot me. */
668         /* we can fix this or we can get a real language. Guess how Ron votes? */
669         err = "file does not exist";
670         return err;
671 }
672
673 void
674 ropen(Job *job, Mfile *mf)
675 {
676         int mode;
677         char *err;
678
679         err = 0;
680         mode = job->request.mode;
681         if(mf->qid.type & QTDIR){
682                 if(mode)
683                         err = "permission denied";
684         }
685         job->reply.qid = mf->qid;
686         job->reply.iounit = 0;
687         sendmsg(job, err);
688 }
689
690 void
691 rcreate(Job *job, Mfile *mf)
692 {
693         sendmsg(job, "creation permission denied");
694 }
695
696 void
697 rread(Job *job, Mfile *mf)
698 {
699         int i, n, cnt;
700         long off, toff, clock;
701         struct dir dir;
702         uint8_t buf[Maxfdata];
703         char *err;
704
705         n = 0;
706         err = 0;
707         off = job->request.offset;
708         cnt = job->request.count;
709         if(mf->qid.type & QTDIR){
710                 //      clock = time(0);
711                 if(off == 0){
712                         memset(&dir, 0, sizeof dir);
713                         dir.name = "cs";
714                         dir.qid.type = QTFILE;
715                         dir.qid.vers = vers;
716                         dir.qid.path = Qcs;
717                         dir.mode = 0666;
718                         dir.length = 0;
719                         dir.uid = mf->user;
720                         dir.gid = mf->user;
721                         dir.muid = mf->user;
722                         dir.atime = clock;      /* wrong */
723                         dir.mtime = clock;      /* wrong */
724                         n = convD2M(&dir, buf, sizeof buf);
725                 }
726                 job->reply.data = (char*)buf;
727         } else {
728                 for(;;){
729                         /* look for an answer at the right offset */
730                         toff = 0;
731                         for(i = 0; mf->reply[i] && i < mf->nreply; i++){
732                                 n = mf->replylen[i];
733                                 if(off < toff + n)
734                                         break;
735                                 toff += n;
736                         }
737                         if(i < mf->nreply)
738                                 break;          /* got something to return */
739
740                         /* try looking up more answers */
741                         if(lookup(mf) == 0){
742                                 /* no more */
743                                 n = 0;
744                                 goto send;
745                         }
746                 }
747
748                 /* give back a single reply (or part of one) */
749                 job->reply.data = mf->reply[i] + (off - toff);
750                 if(cnt > toff - off + n)
751                         n = toff - off + n;
752                 else
753                         n = cnt;
754         }
755 send:
756         job->reply.count = n;
757         sendmsg(job, err);
758 }
759 void
760 cleanmf(Mfile *mf)
761 {
762         int i;
763
764         if(mf->net != NULL){
765                 free(mf->net);
766                 mf->net = NULL;
767         }
768         if(mf->host != NULL){
769                 free(mf->host);
770                 mf->host = NULL;
771         }
772         if(mf->serv != NULL){
773                 free(mf->serv);
774                 mf->serv = NULL;
775         }
776         if(mf->rem != NULL){
777                 free(mf->rem);
778                 mf->rem = NULL;
779         }
780         for(i = 0; i < mf->nreply; i++){
781                 free(mf->reply[i]);
782                 mf->reply[i] = NULL;
783                 mf->replylen[i] = 0;
784         }
785         mf->nreply = 0;
786         mf->nextnet = netlist;
787 }
788
789 void
790 rwrite(Job *job, Mfile *mf)
791 {
792         int cnt, n;
793         char *err;
794         char *field[4];
795         char curerr[64];
796
797         err = 0;
798         cnt = job->request.count;
799         if(mf->qid.type & QTDIR){
800                 err = "can't write directory";
801                 goto send;
802         }
803         if(cnt >= Maxrequest){
804                 err = "request too long";
805                 goto send;
806         }
807         job->request.data[cnt] = 0;
808 printf("CS: request data is :%s:\n", job->request.data);
809         /*
810          *  toggle debugging
811          */
812         if(strncmp(job->request.data, "debug", 5)==0){
813                 debug ^= 1;
814                 fprintf(stderr, "CS:debug %d", debug);
815                 goto send;
816         }
817
818         /*
819          *  toggle ipv6 lookups
820          */
821         if(strncmp(job->request.data, "ipv6", 4)==0){
822                 ipv6lookups ^= 1;
823                 fprintf(stderr, "CS:ipv6lookups %d", ipv6lookups);
824                 goto send;
825         }
826
827         /*
828          *  toggle debugging
829          */
830         if(strncmp(job->request.data, "paranoia", 8)==0){
831                 paranoia ^= 1;
832                 fprintf(stderr,  "CS:paranoia %d", paranoia);
833                 goto send;
834         }
835
836         /*
837          *  add networks to the default list
838          */
839         if(strncmp(job->request.data, "add ", 4)==0){
840                 if(job->request.data[cnt-1] == '\n')
841                         job->request.data[cnt-1] = 0;
842                 netadd(job->request.data+4);
843                 readipinterfaces();
844                 goto send;
845         }
846
847         /*
848          *  refresh all state
849          */
850         if(strncmp(job->request.data, "refresh", 7)==0){
851                 netinit(0/*1*/);
852                 goto send;
853         }
854
855         /* start transaction with a clean slate */
856         cleanmf(mf);
857
858         /*
859          *  look for a general query
860          */
861         if(*job->request.data == '!'){
862                 err = genquery(mf, job->request.data+1);
863                 goto send;
864         }
865
866         if(debug)
867                 fprintf(stderr,  "CS:write %s", job->request.data);
868         if(paranoia)
869                 fprintf(stderr,  "CS:write %s by %s", job->request.data, mf->user);
870
871         /*
872          *  break up name
873          */
874         n = getfields(job->request.data, field, 4, 1, "!");
875         switch(n){
876         case 1:
877                 mf->net = strdup("net");
878                 mf->host = strdup(field[0]);
879                 break;
880         case 4:
881                 mf->rem = strdup(field[3]);
882                 /* fall through */
883         case 3:
884                 mf->serv = strdup(field[2]);
885                 /* fall through */
886         case 2:
887                 mf->host = strdup(field[1]);
888                 mf->net = strdup(field[0]);
889                 break;
890         }
891 printf("CS: net %s host %s serv %s rem %s\n", 
892 mf->net, mf->host, mf->serv, mf->rem);
893         /*
894          *  do the first net worth of lookup
895          */
896         if(lookup(mf) == 0){
897                 snprintf(curerr, sizeof curerr, "%r");
898                 err = curerr;
899         }
900 send:
901         job->reply.count = cnt;
902         sendmsg(job, err);
903 }
904
905 void
906 rclunk(Job *job, Mfile *mf)
907 {
908         cleanmf(mf);
909         free(mf->user);
910         mf->user = 0;
911         mf->busy = 0;
912         mf->fid = 0;
913         sendmsg(job, 0);
914 }
915
916 void
917 rremove(Job *job, Mfile *mf)
918 {
919         sendmsg(job, "remove permission denied");
920 }
921
922 void
923 rstat(Job *job, Mfile *mf)
924 {
925         struct dir dir;
926         uint8_t buf[IOHDRSZ+Maxfdata];
927
928         memset(&dir, 0, sizeof dir);
929         if(mf->qid.type & QTDIR){
930                 dir.name = ".";
931                 dir.mode = DMDIR|0555;
932         } else {
933                 dir.name = "cs";
934                 dir.mode = 0666;
935         }
936         dir.qid = mf->qid;
937         dir.length = 0;
938         dir.uid = mf->user;
939         dir.gid = mf->user;
940         dir.muid = mf->user;
941         //dir.atime = dir.mtime = time(0);
942         job->reply.nstat = convD2M(&dir, buf, sizeof buf);
943         job->reply.stat = buf;
944         sendmsg(job, 0);
945 }
946
947 void
948 rwstat(Job *job, Mfile *mf)
949 {
950         sendmsg(job, "wstat permission denied");
951 }
952
953 void
954 sendmsg(Job *job, char *err)
955 {
956         int n;
957         uint8_t mdata[IOHDRSZ + Maxfdata];
958         char ename[ERRMAX];
959
960         if(err){
961                 job->reply.type = Rerror;
962                 snprintf(ename, sizeof(ename), "cs: %s", err);
963                 job->reply.ename = ename;
964         }else{
965                 job->reply.type = job->request.type+1;
966         }
967         job->reply.tag = job->request.tag;
968         n = convS2M(&job->reply, mdata, sizeof mdata);
969         if(n == 1){
970                 fprintf(stderr,  "CS:sendmsg convS2M of %F returns 0", &job->reply);
971                 abort();
972         }
973         //lock(&joblock);
974         if(job->flushed == 0)
975                 if(write(mfd[1], mdata, n)!=n)
976                         error(1, 0, "%s: %r","mount write");
977         //unlock(&joblock);
978         if(debug)
979                 fprintf(stderr,  "CS:%F %d", &job->reply, n);
980 }
981
982 static int
983 isvalidip(uint8_t *ip)
984 {
985         return ipcmp(ip, IPnoaddr) != 0 && ipcmp(ip, v4prefix) != 0;
986 }
987
988 static uint8_t loopbacknet[IPaddrlen] = {
989         0, 0, 0, 0,
990         0, 0, 0, 0,
991         0, 0, 0xff, 0xff,
992         127, 0, 0, 0
993 };
994 static uint8_t loopbackmask[IPaddrlen] = {
995         0xff, 0xff, 0xff, 0xff,
996         0xff, 0xff, 0xff, 0xff,
997         0xff, 0xff, 0xff, 0xff,
998         0xff, 0, 0, 0
999 };
1000
1001 void
1002 readipinterfaces(void)
1003 {
1004         if(myipaddr(ipa, mntpt) != 0)
1005                 ipmove(ipa, IPnoaddr);
1006         snprintf(ipaddr, sizeof(ipaddr), "%I", ipa);
1007         if (debug)
1008                 fprintf(stderr, "CS:dns", "ipaddr is %s\n", ipaddr);
1009 }
1010
1011 /*
1012  *  get the system name
1013  */
1014 void
1015 ipid(void)
1016 {
1017         uint8_t addr[6];
1018         struct ndbtuple *t, *tt;
1019         char *p, *attr;
1020         struct ndbs s;
1021         int f;
1022         char buf[Maxpath];
1023
1024         /* use environment, ether addr, or ipaddr to get system name */
1025         if(mysysname == 0){
1026                 /*
1027                  *  environment has priority.
1028                  *
1029                  *  on the sgi power the default system name
1030                  *  is the ip address.  ignore that.
1031                  *
1032                  */
1033                 p = getenv("sysname");
1034                 if(p && *p){
1035                         attr = ipattr(p);
1036                         if(strcmp(attr, "ip") != 0)
1037                                 mysysname = strdup(p);
1038                 }
1039
1040                 /*
1041                  *  the /net/ndb contains what the network
1042                  *  figured out from DHCP.  use that name if
1043                  *  there is one.
1044                  */
1045                 if(mysysname == 0 && netdb != NULL){
1046                         ndbreopen(netdb);
1047                         for(tt = t = ndbparse(netdb); t != NULL; t = t->entry){
1048                                 if(strcmp(t->attr, "sys") == 0){
1049                                         mysysname = strdup(t->val);
1050                                         break;
1051                                 }
1052                         }
1053                         ndbfree(tt);
1054                 }
1055
1056                 /* next network database, ip address, and ether address to find a name */
1057                 if(mysysname == 0){
1058                         t = NULL;
1059                         if(isvalidip(ipa))
1060                                 free(ndbgetvalue(db, &s, "ip", ipaddr, "sys", &t));
1061                         if(t == NULL){
1062                                 for(f = 0; f < 3; f++){
1063                                         snprintf(buf, sizeof buf, "%s/ether%d", mntpt, f);
1064                                         if(myetheraddr(addr, buf) >= 0){
1065                                                 snprintf(eaddr, sizeof(eaddr), "%E", addr);
1066                                                 free(ndbgetvalue(db, &s, "ether", eaddr, "sys", &t));
1067                                                 if(t != NULL)
1068                                                         break;
1069                                         }
1070                                 }
1071                         }
1072                         for(tt = t; tt != NULL; tt = tt->entry){
1073                                 if(strcmp(tt->attr, "sys") == 0){
1074                                         mysysname = strdup(tt->val);
1075                                         break;
1076                                 }
1077                         }
1078                         ndbfree(t);
1079                 }
1080
1081                 /* nothing else worked, use the ip address */
1082                 if(mysysname == 0 && isvalidip(ipa))
1083                         mysysname = strdup(ipaddr);
1084
1085
1086                 /* set /dev/sysname if we now know it */
1087                 if(mysysname){
1088                         f = open("/dev/sysname", O_RDWR);
1089                         if(f >= 0){
1090                                 write(f, mysysname, strlen(mysysname));
1091                                 close(f);
1092                         }
1093                 }
1094         }
1095 }
1096
1097 /*
1098  *  Set up a list of default networks by looking for
1099  *  /net/^*^/clone.
1100  *  For now, never background.
1101  */
1102 void
1103 netinit(int background)
1104 {
1105         char clone[Maxpath];
1106         Network *np;
1107         static int working;
1108
1109         /* add the mounted networks to the default list */
1110         for(np = network; np->net; np++){
1111                 int fuckup;
1112                 if(np->considered)
1113                         continue;
1114                 snprintf(clone, sizeof(clone), "%s/%s/clone", mntpt, np->net);
1115                 fuckup = open(clone, O_RDONLY);
1116                 if (fuckup < 0)
1117                         continue;
1118                 close(fuckup);
1119                 //if(access(clone, R_OK))
1120                         //continue;
1121                 if(netlist)
1122                         last->next = np;
1123                 else
1124                         netlist = np;
1125                 last = np;
1126                 np->next = 0;
1127                 np->considered = 1;
1128         }
1129
1130         /* find out what our ip address is */
1131         readipinterfaces();
1132
1133         /* set the system name if we need to, these days ip is all we have */
1134         ipid();
1135
1136         if(debug)
1137                 fprintf(stderr, logfile, "CS:mysysname %s eaddr %s ipaddr %s ipa %I\n",
1138                         mysysname?mysysname:"???", eaddr, ipaddr, ipa);
1139
1140 }
1141
1142 /*
1143  *  add networks to the standard list
1144  */
1145 void
1146 netadd(char *p)
1147 {
1148         Network *np;
1149         char *field[12];
1150         int i, n;
1151
1152         n = getfields(p, field, 12, 1, " ");
1153         for(i = 0; i < n; i++){
1154                 for(np = network; np->net; np++){
1155                         if(strcmp(field[i], np->net) != 0)
1156                                 continue;
1157                         if(np->considered)
1158                                 break;
1159                         if(netlist)
1160                                 last->next = np;
1161                         else
1162                                 netlist = np;
1163                         last = np;
1164                         np->next = 0;
1165                         np->considered = 1;
1166                 }
1167         }
1168 }
1169
1170 int
1171 lookforproto(struct ndbtuple *t, char *proto)
1172 {
1173         for(; t != NULL; t = t->entry)
1174                 if(strcmp(t->attr, "proto") == 0 && strcmp(t->val, proto) == 0)
1175                         return 1;
1176         return 0;
1177 }
1178
1179 /*
1180  *  lookup a request.  the network "net" means we should pick the
1181  *  best network to get there.
1182  */
1183 int
1184 lookup(Mfile *mf)
1185 {
1186         Network *np;
1187         char *cp;
1188         struct ndbtuple *nt, *t;
1189         char reply[Maxreply];
1190         int i, rv;
1191         int hack;
1192
1193         /* open up the standard db files */
1194         if(db == 0)
1195                 ndbinit();
1196         if(db == 0)
1197                 error(1, 0, "%s: %r","can't open mf->network database\n");
1198
1199         rv = 0;
1200
1201         if(mf->net == NULL)
1202                 return 0;       /* must have been a genquery */
1203
1204 printf("CS: Look up net %s \n", mf->net);
1205         if(strcmp(mf->net, "net") == 0){
1206                 /*
1207                  *  go through set of default nets
1208                  */
1209                 for(np = mf->nextnet; np; np = np->next){
1210                         nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1211                         if(nt == NULL)
1212                                 continue;
1213                         hack = np->fasttimeouthack && !lookforproto(nt, np->net);
1214                         for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1215                                 cp = (*np->trans)(t, np, mf->serv, mf->rem, hack);
1216                                 if(cp){
1217                                         /* avoid duplicates */
1218                                         for(i = 0; i < mf->nreply; i++)
1219                                                 if(strcmp(mf->reply[i], cp) == 0)
1220                                                         break;
1221                                         if(i == mf->nreply){
1222                                                 /* save the reply */
1223                                                 mf->replylen[mf->nreply] = strlen(cp);
1224                                                 mf->reply[mf->nreply++] = cp;
1225                                                 rv++;
1226                                         }
1227                                 }
1228                         }
1229                         ndbfree(nt);
1230                         np = np->next;
1231                         break;
1232                 }
1233                 mf->nextnet = np;
1234                 return rv;
1235         }
1236
1237         /*
1238          *  if not /net, we only get one lookup
1239          */
1240         if(mf->nreply != 0)
1241                 return 0;
1242         /*
1243          *  look for a specific network
1244          */
1245 printf("CS: netlist is %p\n", netlist);
1246         for(np = netlist; np && np->net != NULL; np++){
1247                 if(np->fasttimeouthack)
1248                         continue;
1249 printf("CS: compare net np->net %s mf->net %s\n", np->net, mf->net);
1250                 if(strcmp(np->net, mf->net) == 0)
1251                         break;
1252         }
1253
1254 printf("CS: np is %p np->net %p\n", np, np ? np->net : NULL);
1255         if(np && np->net != NULL){
1256                 /*
1257                  *  known network
1258                  */
1259                 nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1260                 for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1261                         cp = (*np->trans)(t, np, mf->serv, mf->rem, 0);
1262 printf("CS: Lookup %s\n", cp);
1263                         if(cp){
1264                                 mf->replylen[mf->nreply] = strlen(cp);
1265                                 mf->reply[mf->nreply++] = cp;
1266                                 rv++;
1267                         }
1268                 }
1269                 ndbfree(nt);
1270                 return rv;
1271         } else {
1272 printf("UNKONW NET\n");
1273                 /*
1274                  *  not a known network, don't translate host or service
1275                  */
1276                 if(mf->serv)
1277                         snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s",
1278                                 mntpt, mf->net, mf->host, mf->serv);
1279                 else
1280                         snprintf(reply, sizeof(reply), "%s/%s/clone %s",
1281                                 mntpt, mf->net, mf->host);
1282 printf("CS: reply is %s\n", reply);
1283                 mf->reply[0] = strdup(reply);
1284                 mf->replylen[0] = strlen(reply);
1285                 mf->nreply = 1;
1286                 return 1;
1287         }
1288 }
1289
1290 /*
1291  *  translate an ip service name into a port number.  If it's a numeric port
1292  *  number, look for restricted access.
1293  *
1294  *  the service '*' needs no translation.
1295  */
1296 char*
1297 ipserv(Network *np, char *name, char *buf, int blen)
1298 {
1299         char *p;
1300         int alpha = 0;
1301         int restr = 0;
1302         char port[10];
1303         struct ndbtuple *t, *nt;
1304         struct ndbs s;
1305
1306 printf("CS: port %s\n", name);
1307         /* '*' means any service */
1308         if(strcmp(name, "*")==0){
1309                 strcpy(buf, name);
1310                 return buf;
1311         }
1312
1313         /*  see if it's numeric or symbolic */
1314         port[0] = 0;
1315         for(p = name; *p; p++){
1316                 if(isdigit(*p))
1317                         {}
1318                 else if(isalpha(*p) || *p == '-' || *p == '$')
1319                         alpha = 1;
1320                 else
1321                         return 0;
1322         }
1323         t = NULL;
1324         p = NULL;
1325         if(alpha){
1326                 p = ndbgetvalue(db, &s, np->net, name, "port", &t);
1327 printf("CS: get value of port %s, p is (we hope not null)%p\n", name, p);
1328                 if(p == NULL)
1329                         return 0;
1330         } else {
1331                 /* look up only for tcp ports < 1024 to get the restricted
1332                  * attribute
1333                  */
1334                 if(atoi(name) < 1024 && strcmp(np->net, "tcp") == 0)
1335                         p = ndbgetvalue(db, &s, "port", name, "port", &t);
1336                 if(p == NULL)
1337                         p = strdup(name);
1338         }
1339
1340         if(t){
1341                 for(nt = t; nt; nt = nt->entry)
1342                         if(strcmp(nt->attr, "restricted") == 0)
1343                                 restr = 1;
1344                 ndbfree(t);
1345         }
1346         snprintf(buf, blen, "%s%s", p, restr ? "!r" : "");
1347         free(p);
1348 printf("CS: buf is %s\n", buf);
1349         return buf;
1350 }
1351
1352 /*
1353  *  lookup an ip attribute
1354  */
1355 int
1356 ipattrlookup(struct ndb *db, char *ipa, char *attr, char *val, int vlen)
1357 {
1358
1359         struct ndbtuple *t, *nt;
1360         char *alist[2];
1361
1362         alist[0] = attr;
1363         t = ndbipinfo(db, "ip", ipa, alist, 1);
1364         if(t == NULL)
1365                 return 0;
1366         for(nt = t; nt != NULL; nt = nt->entry){
1367                 if(strcmp(nt->attr, attr) == 0){
1368                         nstrcpy(val, nt->val, vlen);
1369                         ndbfree(t);
1370                         return 1;
1371                 }
1372         }
1373
1374         /* we shouldn't get here */
1375         ndbfree(t);
1376         return 0;
1377 }
1378
1379 /*
1380  *  lookup (and translate) an ip destination
1381  */
1382 struct ndbtuple*
1383 iplookup(Network *np, char *host, char *serv, int nolookup)
1384 {
1385         char *attr, *dnsname;
1386         struct ndbtuple *t, *nt;
1387         struct ndbs s;
1388         char ts[Maxservice];
1389         char dollar[Maxhost];
1390         uint8_t ip[IPaddrlen];
1391         uint8_t net[IPaddrlen];
1392         uint8_t tnet[IPaddrlen];
1393         struct ipifc *ifc;
1394         struct iplifc *lifc;
1395
1396         /*
1397          *  start with the service since it's the most likely to fail
1398          *  and costs the least
1399          */
1400         werrstr("can't translate address");
1401         if(serv==0 || ipserv(np, serv, ts, sizeof ts) == 0){
1402                 werrstr("can't translate service");
1403                 return 0;
1404         }
1405
1406         /* for dial strings with no host */
1407         if(strcmp(host, "*") == 0)
1408                 return ndbnew("ip", "*");
1409
1410         /*
1411          *  hack till we go v6 :: = 0.0.0.0
1412          */
1413         if(strcmp("::", host) == 0)
1414                 return ndbnew("ip", "*");
1415
1416         /*
1417          *  '$' means the rest of the name is an attribute that we
1418          *  need to search for
1419          */
1420         if(*host == '$'){
1421                 if(ipattrlookup(db, ipaddr, host+1, dollar, sizeof dollar))
1422                         host = dollar;
1423         }
1424
1425         /*
1426          *  turn '[ip address]' into just 'ip address'
1427          */
1428         if(*host == '[' && host[strlen(host)-1] == ']'){
1429                 host++;
1430                 host[strlen(host)-1] = 0;
1431         }
1432
1433         /*
1434          *  just accept addresses
1435          */
1436         attr = ipattr(host);
1437         if(strcmp(attr, "ip") == 0)
1438                 return ndbnew("ip", host);
1439
1440         /*
1441          *  give the domain name server the first opportunity to
1442          *  resolve domain names.  if that fails try the database.
1443          */
1444         t = 0;
1445         werrstr("can't translate address");
1446         if(strcmp(attr, "dom") == 0)
1447                 t = dnsiplookup(host, &s);
1448         if(t == 0)
1449                 free(ndbgetvalue(db, &s, attr, host, "ip", &t));
1450         if(t == 0){
1451                 dnsname = ndbgetvalue(db, &s, attr, host, "dom", NULL);
1452                 if(dnsname){
1453                         t = dnsiplookup(dnsname, &s);
1454                         free(dnsname);
1455                 }
1456         }
1457         if(t == 0)
1458                 t = dnsiplookup(host, &s);
1459         if(t == 0)
1460                 return 0;
1461
1462         /*
1463          *  reorder the tuple to have the matched line first and
1464          *  save that in the request structure.
1465          */
1466         t = reorder(t, s.t);
1467
1468         /*
1469          * reorder according to our interfaces
1470          */
1471         //lock(&ipifclock);
1472         for(ifc = ipifcs; ifc != NULL; ifc = ifc->next){
1473                 for(lifc = ifc->lifc; lifc != NULL; lifc = lifc->next){
1474                         maskip(lifc->ip, lifc->mask, net);
1475                         for(nt = t; nt; nt = nt->entry){
1476                                 if(strcmp(nt->attr, "ip") != 0)
1477                                         continue;
1478                                 parseip(ip, nt->val);
1479                                 maskip(ip, lifc->mask, tnet);
1480                                 if(memcmp(net, tnet, IPaddrlen) == 0){
1481                                         t = reorder(t, nt);
1482                                         //unlock(&ipifclock);
1483                                         return t;
1484                                 }
1485                         }
1486                 }
1487         }
1488         //unlock(&ipifclock);
1489
1490         return t;
1491 }
1492
1493 /*
1494  *  translate an ip address
1495  */
1496 char*
1497 iptrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int hack)
1498 {
1499         char ts[Maxservice];
1500         char reply[Maxreply];
1501         char x[Maxservice];
1502
1503         if(strcmp(t->attr, "ip") != 0)
1504                 return 0;
1505
1506         if(serv == 0 || ipserv(np, serv, ts, sizeof ts) == 0){
1507                 werrstr("can't translate service");
1508                 return 0;
1509         }
1510         if(rem != NULL)
1511                 snprintf(x, sizeof(x), "!%s", rem);
1512         else
1513                 *x = 0;
1514
1515         if(*t->val == '*')
1516                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s",
1517                         mntpt, np->net, ts, x);
1518         else
1519                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s%s",
1520                         mntpt, np->net, t->val, ts, x, hack? "!fasttimeout": "");
1521
1522         return strdup(reply);
1523 }
1524
1525 /*
1526  *  lookup a telephone number
1527  */
1528 struct ndbtuple*
1529 telcolookup(Network *np, char *host, char *serv, int nolookup)
1530 {
1531         struct ndbtuple *t;
1532         struct ndbs s;
1533
1534         werrstr("can't translate address");
1535         free(ndbgetvalue(db, &s, "sys", host, "telco", &t));
1536         if(t == 0)
1537                 return ndbnew("telco", host);
1538
1539         return reorder(t, s.t);
1540 }
1541
1542 /*
1543  *  translate a telephone address
1544  */
1545 char*
1546 telcotrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int unused)
1547 {
1548         char reply[Maxreply];
1549         char x[Maxservice];
1550
1551         if(strcmp(t->attr, "telco") != 0)
1552                 return 0;
1553
1554         if(rem != NULL)
1555                 snprintf(x, sizeof(x), "!%s", rem);
1556         else
1557                 *x = 0;
1558         if(serv)
1559                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s", mntpt, np->net,
1560                         t->val, serv, x);
1561         else
1562                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s", mntpt, np->net,
1563                         t->val, x);
1564         return strdup(reply);
1565 }
1566
1567 /*
1568  *  reorder the tuple to put x's line first in the entry
1569  */
1570 struct ndbtuple*
1571 reorder(struct ndbtuple *t, struct ndbtuple *x)
1572 {
1573         struct ndbtuple *nt;
1574         struct ndbtuple *line;
1575
1576         /* find start of this entry's line */
1577         for(line = x; line->entry == line->line; line = line->line)
1578                 ;
1579         line = line->line;
1580         if(line == t)
1581                 return t;       /* already the first line */
1582
1583         /* remove this line and everything after it from the entry */
1584         for(nt = t; nt->entry != line; nt = nt->entry)
1585                 ;
1586         nt->entry = 0;
1587
1588         /* make that the start of the entry */
1589         for(nt = line; nt->entry; nt = nt->entry)
1590                 ;
1591         nt->entry = t;
1592         return line;
1593 }
1594
1595 static struct ndbtuple*
1596 dnsip6lookup(char *mntpt, char *buf, struct ndbtuple *t)
1597 {
1598         struct ndbtuple *t6, *tt;
1599
1600         t6 = dnsquery(mntpt, buf, "ipv6");      /* lookup AAAA dns RRs */
1601         if (t6 == NULL)
1602                 return t;
1603
1604         /* convert ipv6 attr to ip */
1605         for (tt = t6; tt != NULL; tt = tt->entry)
1606                 if (strcmp(tt->attr, "ipv6") == 0)
1607                         strncpy(tt->attr, "ip", sizeof tt->attr - 1);
1608
1609         if (t == NULL)
1610                 return t6;
1611
1612         /* append t6 list to t list */
1613         for (tt = t; tt->entry != NULL; tt = tt->entry)
1614                 ;
1615         tt->entry = t6;
1616         return t;
1617 }
1618
1619 /*
1620  *  call the dns process and have it try to translate a name
1621  */
1622 struct ndbtuple*
1623 dnsiplookup(char *host, struct ndbs *s)
1624 {
1625         char buf[Maxreply];
1626         struct ndbtuple *t;
1627
1628         //unlock(&dblock);
1629
1630         /* save the name */
1631         snprintf(buf, sizeof(buf), "%s", host);
1632
1633         if(strcmp(ipattr(buf), "ip") == 0)
1634                 t = dnsquery(mntpt, buf, "ptr");
1635         else {
1636                 t = dnsquery(mntpt, buf, "ip");
1637                 /* special case: query ipv6 (AAAA dns RR) too */
1638                 if (ipv6lookups)
1639                         t = dnsip6lookup(mntpt, buf, t);
1640         }
1641         s->t = t;
1642
1643         if(t == NULL){
1644                 snprintf(buf, sizeof buf, "%r");
1645                 if(strstr(buf, "exist"))
1646                         werrstr("can't translate address: %s", buf);
1647                 else if(strstr(buf, "dns failure"))
1648                         werrstr("temporary problem: %s", buf);
1649         }
1650
1651         //lock(&dblock);
1652         return t;
1653 }
1654
1655 int
1656 qmatch(struct ndbtuple *t, char **attr, char **val, int n)
1657 {
1658         int i, found;
1659         struct ndbtuple *nt;
1660
1661         for(i = 1; i < n; i++){
1662                 found = 0;
1663                 for(nt = t; nt; nt = nt->entry)
1664                         if(strcmp(attr[i], nt->attr) == 0)
1665                                 if(strcmp(val[i], "*") == 0
1666                                 || strcmp(val[i], nt->val) == 0){
1667                                         found = 1;
1668                                         break;
1669                                 }
1670                 if(found == 0)
1671                         break;
1672         }
1673         return i == n;
1674 }
1675
1676 /* this is awful but I don't want to bring in libstring just for this.
1677  * you want real strings don't use C
1678  */
1679 void
1680 qreply(Mfile *mf, struct ndbtuple *t)
1681 {
1682         struct ndbtuple *nt;
1683         char *s, *cur;
1684         int len, amt;
1685
1686         s = malloc(4096);
1687         cur = s;
1688         len = 4096;
1689
1690         for(nt = t; mf->nreply < Nreply && nt; nt = nt->entry){
1691                 amt = snprintf(cur, len, "%s=%s", nt->attr, nt->val);
1692
1693                 if (amt < 0)
1694                         len = 0;
1695                 else {
1696                         len -= amt;
1697                         cur += len;
1698                 }
1699
1700                 if(nt->line != nt->entry){
1701                         mf->replylen[mf->nreply] = strlen(s);
1702                         mf->reply[mf->nreply++] = strdup(s);
1703                         cur = s;
1704                         len = 4096;
1705                 } else {
1706                         amt = snprintf(cur, len, " ");
1707                         if (amt < 0)
1708                                 len = 0;
1709                         else {
1710                                 len -= amt;
1711                                 cur += len;
1712                         }
1713                 }
1714
1715         }
1716         free(s);
1717 }
1718
1719 enum
1720 {
1721         Maxattr=        32,
1722 };
1723
1724 /*
1725  *  generic query lookup.  The query is of one of the following
1726  *  forms:
1727  *
1728  *  attr1=val1 attr2=val2 attr3=val3 ...
1729  *
1730  *  returns the matching tuple
1731  *
1732  *  ipinfo attr=val attr1 attr2 attr3 ...
1733  *
1734  *  is like ipinfo and returns the attr{1-n}
1735  *  associated with the ip address.
1736  */
1737 char*
1738 genquery(Mfile *mf, char *query)
1739 {
1740         int i, n;
1741         char *p;
1742         char *attr[Maxattr];
1743         char *val[Maxattr];
1744         struct ndbtuple *t;
1745         struct ndbs s;
1746
1747         n = getfields(query, attr, ARRAY_SIZE(attr), 1, " ");
1748         if(n == 0)
1749                 return "bad query";
1750
1751         if(strcmp(attr[0], "ipinfo") == 0)
1752                 return ipinfoquery(mf, attr, n);
1753
1754         /* parse pairs */
1755         for(i = 0; i < n; i++){
1756                 p = strchr(attr[i], '=');
1757                 if(p == 0)
1758                         return "bad query";
1759                 *p++ = 0;
1760                 val[i] = p;
1761         }
1762
1763         /* give dns a chance */
1764         if((strcmp(attr[0], "dom") == 0 || strcmp(attr[0], "ip") == 0) && val[0]){
1765                 t = dnsiplookup(val[0], &s);
1766                 if(t){
1767                         if(qmatch(t, attr, val, n)){
1768                                 qreply(mf, t);
1769                                 ndbfree(t);
1770                                 return 0;
1771                         }
1772                         ndbfree(t);
1773                 }
1774         }
1775
1776         /* first pair is always the key.  It can't be a '*' */
1777         t = ndbsearch(db, &s, attr[0], val[0]);
1778
1779         /* search is the and of all the pairs */
1780         while(t){
1781                 if(qmatch(t, attr, val, n)){
1782                         qreply(mf, t);
1783                         ndbfree(t);
1784                         return 0;
1785                 }
1786
1787                 ndbfree(t);
1788                 t = ndbsnext(&s, attr[0], val[0]);
1789         }
1790
1791         return "no match";
1792 }
1793
1794 /*
1795  *  resolve an ip address
1796  */
1797 static struct ndbtuple*
1798 ipresolve(char *attr, char *host)
1799 {
1800         struct ndbtuple *t, *nt, **l;
1801
1802         t = iplookup(&network[Ntcp], host, "*", 0);
1803         for(l = &t; *l != NULL; ){
1804                 nt = *l;
1805                 if(strcmp(nt->attr, "ip") != 0){
1806                         *l = nt->entry;
1807                         nt->entry = NULL;
1808                         ndbfree(nt);
1809                         continue;
1810                 }
1811                 strcpy(nt->attr, attr);
1812                 l = &nt->entry;
1813         }
1814         return t;
1815 }
1816
1817 char*
1818 ipinfoquery(Mfile *mf, char **list, int n)
1819 {
1820         int i, nresolve;
1821         int resolve[Maxattr];
1822         struct ndbtuple *t, *nt, **l;
1823         char *attr, *val;
1824
1825         /* skip 'ipinfo' */
1826         list++; n--;
1827
1828         if(n < 1)
1829                 return "bad query";
1830
1831         /* get search attribute=value, or assume ip=myipaddr */
1832         attr = *list;
1833         if((val = strchr(attr, '=')) != NULL){
1834                 *val++ = 0;
1835                 list++;
1836                 n--;
1837         }else{
1838                 attr = "ip";
1839                 val = ipaddr;
1840         }
1841
1842         if(n < 1)
1843                 return "bad query";
1844
1845         /*
1846          *  don't let ndbipinfo resolve the addresses, we're
1847          *  better at it.
1848          */
1849         nresolve = 0;
1850         for(i = 0; i < n; i++)
1851                 if(*list[i] == '@'){            /* @attr=val ? */
1852                         list[i]++;
1853                         resolve[i] = 1;         /* we'll resolve it */
1854                         nresolve++;
1855                 } else
1856                         resolve[i] = 0;
1857
1858         t = ndbipinfo(db, attr, val, list, n);
1859         if(t == NULL)
1860                 return "no match";
1861
1862         if(nresolve != 0){
1863                 for(l = &t; *l != NULL;){
1864                         nt = *l;
1865
1866                         /* already an address? */
1867                         if(strcmp(ipattr(nt->val), "ip") == 0){
1868                                 l = &(*l)->entry;
1869                                 continue;
1870                         }
1871
1872                         /* user wants it resolved? */
1873                         for(i = 0; i < n; i++)
1874                                 if(strcmp(list[i], nt->attr) == 0)
1875                                         break;
1876                         if(i >= n || resolve[i] == 0){
1877                                 l = &(*l)->entry;
1878                                 continue;
1879                         }
1880
1881                         /* resolve address and replace entry */
1882                         *l = ipresolve(nt->attr, nt->val);
1883                         while(*l != NULL)
1884                                 l = &(*l)->entry;
1885                         *l = nt->entry;
1886
1887                         nt->entry = NULL;
1888                         ndbfree(nt);
1889                 }
1890         }
1891
1892         /* make it all one line */
1893         for(nt = t; nt != NULL; nt = nt->entry){
1894                 if(nt->entry == NULL)
1895                         nt->line = t;
1896                 else
1897                         nt->line = nt->entry;
1898         }
1899
1900         qreply(mf, t);
1901
1902         return NULL;
1903 }
1904
1905 void*
1906 emalloc(int size)
1907 {
1908         void *x;
1909
1910         x = calloc(size, 1);
1911         if(x == NULL)
1912                 abort();
1913         memset(x, 0, size);
1914         return x;
1915 }
1916
1917 char*
1918 estrdup(char *s)
1919 {
1920         int size;
1921         char *p;
1922
1923         size = strlen(s)+1;
1924         p = calloc(size, 1);
1925         if(p == NULL)
1926                 abort();
1927         memmove(p, s, size);
1928         return p;
1929 }