Plan 9 programs for controlling and checking the network: cs.c, csquery.c, netstat.c
[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(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
892         /*
893          *  do the first net worth of lookup
894          */
895         if(lookup(mf) == 0){
896                 snprintf(curerr, sizeof curerr, "%r");
897                 err = curerr;
898         }
899 send:
900         job->reply.count = cnt;
901         sendmsg(job, err);
902 }
903
904 void
905 rclunk(Job *job, Mfile *mf)
906 {
907         cleanmf(mf);
908         free(mf->user);
909         mf->user = 0;
910         mf->busy = 0;
911         mf->fid = 0;
912         sendmsg(job, 0);
913 }
914
915 void
916 rremove(Job *job, Mfile *mf)
917 {
918         sendmsg(job, "remove permission denied");
919 }
920
921 void
922 rstat(Job *job, Mfile *mf)
923 {
924         struct dir dir;
925         uint8_t buf[IOHDRSZ+Maxfdata];
926
927         memset(&dir, 0, sizeof dir);
928         if(mf->qid.type & QTDIR){
929                 dir.name = ".";
930                 dir.mode = DMDIR|0555;
931         } else {
932                 dir.name = "cs";
933                 dir.mode = 0666;
934         }
935         dir.qid = mf->qid;
936         dir.length = 0;
937         dir.uid = mf->user;
938         dir.gid = mf->user;
939         dir.muid = mf->user;
940         //dir.atime = dir.mtime = time(0);
941         job->reply.nstat = convD2M(&dir, buf, sizeof buf);
942         job->reply.stat = buf;
943         sendmsg(job, 0);
944 }
945
946 void
947 rwstat(Job *job, Mfile *mf)
948 {
949         sendmsg(job, "wstat permission denied");
950 }
951
952 void
953 sendmsg(Job *job, char *err)
954 {
955         int n;
956         uint8_t mdata[IOHDRSZ + Maxfdata];
957         char ename[ERRMAX];
958
959         if(err){
960                 job->reply.type = Rerror;
961                 snprintf(ename, sizeof(ename), "cs: %s", err);
962                 job->reply.ename = ename;
963         }else{
964                 job->reply.type = job->request.type+1;
965         }
966         job->reply.tag = job->request.tag;
967         n = convS2M(&job->reply, mdata, sizeof mdata);
968         if(n == 0){
969                 fprintf(stderr,  "CS:sendmsg convS2M of %F returns 0", &job->reply);
970                 abort();
971         }
972         //lock(&joblock);
973         if(job->flushed == 0)
974                 if(write(mfd[1], mdata, n)!=n)
975                         error(1, 0, "%s: %r","mount write");
976         //unlock(&joblock);
977         if(debug)
978                 fprintf(stderr,  "CS:%F %d", &job->reply, n);
979 }
980
981 static int
982 isvalidip(uint8_t *ip)
983 {
984         return ipcmp(ip, IPnoaddr) != 0 && ipcmp(ip, v4prefix) != 0;
985 }
986
987 static uint8_t loopbacknet[IPaddrlen] = {
988         0, 0, 0, 0,
989         0, 0, 0, 0,
990         0, 0, 0xff, 0xff,
991         127, 0, 0, 0
992 };
993 static uint8_t loopbackmask[IPaddrlen] = {
994         0xff, 0xff, 0xff, 0xff,
995         0xff, 0xff, 0xff, 0xff,
996         0xff, 0xff, 0xff, 0xff,
997         0xff, 0, 0, 0
998 };
999
1000 void
1001 readipinterfaces(void)
1002 {
1003         if(myipaddr(ipa, mntpt) != 0)
1004                 ipmove(ipa, IPnoaddr);
1005         snprintf(ipaddr, sizeof(ipaddr), "%I", ipa);
1006         if (debug)
1007                 fprintf(stderr, "CS:dns", "ipaddr is %s\n", ipaddr);
1008 }
1009
1010 /*
1011  *  get the system name
1012  */
1013 void
1014 ipid(void)
1015 {
1016         uint8_t addr[6];
1017         struct ndbtuple *t, *tt;
1018         char *p, *attr;
1019         struct ndbs s;
1020         int f;
1021         char buf[Maxpath];
1022
1023         /* use environment, ether addr, or ipaddr to get system name */
1024         if(mysysname == 0){
1025                 /*
1026                  *  environment has priority.
1027                  *
1028                  *  on the sgi power the default system name
1029                  *  is the ip address.  ignore that.
1030                  *
1031                  */
1032                 p = getenv("sysname");
1033                 if(p && *p){
1034                         attr = ipattr(p);
1035                         if(strcmp(attr, "ip") != 0)
1036                                 mysysname = strdup(p);
1037                 }
1038
1039                 /*
1040                  *  the /net/ndb contains what the network
1041                  *  figured out from DHCP.  use that name if
1042                  *  there is one.
1043                  */
1044                 if(mysysname == 0 && netdb != NULL){
1045                         ndbreopen(netdb);
1046                         for(tt = t = ndbparse(netdb); t != NULL; t = t->entry){
1047                                 if(strcmp(t->attr, "sys") == 0){
1048                                         mysysname = strdup(t->val);
1049                                         break;
1050                                 }
1051                         }
1052                         ndbfree(tt);
1053                 }
1054
1055                 /* next network database, ip address, and ether address to find a name */
1056                 if(mysysname == 0){
1057                         t = NULL;
1058                         if(isvalidip(ipa))
1059                                 free(ndbgetvalue(db, &s, "ip", ipaddr, "sys", &t));
1060                         if(t == NULL){
1061                                 for(f = 0; f < 3; f++){
1062                                         snprintf(buf, sizeof buf, "%s/ether%d", mntpt, f);
1063                                         if(myetheraddr(addr, buf) >= 0){
1064                                                 snprintf(eaddr, sizeof(eaddr), "%E", addr);
1065                                                 free(ndbgetvalue(db, &s, "ether", eaddr, "sys", &t));
1066                                                 if(t != NULL)
1067                                                         break;
1068                                         }
1069                                 }
1070                         }
1071                         for(tt = t; tt != NULL; tt = tt->entry){
1072                                 if(strcmp(tt->attr, "sys") == 0){
1073                                         mysysname = strdup(tt->val);
1074                                         break;
1075                                 }
1076                         }
1077                         ndbfree(t);
1078                 }
1079
1080                 /* nothing else worked, use the ip address */
1081                 if(mysysname == 0 && isvalidip(ipa))
1082                         mysysname = strdup(ipaddr);
1083
1084
1085                 /* set /dev/sysname if we now know it */
1086                 if(mysysname){
1087                         f = open("/dev/sysname", O_RDWR);
1088                         if(f >= 0){
1089                                 write(f, mysysname, strlen(mysysname));
1090                                 close(f);
1091                         }
1092                 }
1093         }
1094 }
1095
1096 /*
1097  *  Set up a list of default networks by looking for
1098  *  /net/^*^/clone.
1099  *  For now, never background.
1100  */
1101 void
1102 netinit(int background)
1103 {
1104         char clone[Maxpath];
1105         Network *np;
1106         static int working;
1107
1108         /* add the mounted networks to the default list */
1109         for(np = network; np->net; np++){
1110                 if(np->considered)
1111                         continue;
1112                 snprintf(clone, sizeof(clone), "%s/%s/clone", mntpt, np->net);
1113                 if(access(clone, R_OK))
1114                         continue;
1115                 if(netlist)
1116                         last->next = np;
1117                 else
1118                         netlist = np;
1119                 last = np;
1120                 np->next = 0;
1121                 np->considered = 1;
1122         }
1123
1124         /* find out what our ip address is */
1125         readipinterfaces();
1126
1127         /* set the system name if we need to, these days ip is all we have */
1128         ipid();
1129
1130         if(debug)
1131                 fprintf(stderr, logfile, "CS:mysysname %s eaddr %s ipaddr %s ipa %I\n",
1132                         mysysname?mysysname:"???", eaddr, ipaddr, ipa);
1133
1134 }
1135
1136 /*
1137  *  add networks to the standard list
1138  */
1139 void
1140 netadd(char *p)
1141 {
1142         Network *np;
1143         char *field[12];
1144         int i, n;
1145
1146         n = getfields(p, field, 12, 1, " ");
1147         for(i = 0; i < n; i++){
1148                 for(np = network; np->net; np++){
1149                         if(strcmp(field[i], np->net) != 0)
1150                                 continue;
1151                         if(np->considered)
1152                                 break;
1153                         if(netlist)
1154                                 last->next = np;
1155                         else
1156                                 netlist = np;
1157                         last = np;
1158                         np->next = 0;
1159                         np->considered = 1;
1160                 }
1161         }
1162 }
1163
1164 int
1165 lookforproto(struct ndbtuple *t, char *proto)
1166 {
1167         for(; t != NULL; t = t->entry)
1168                 if(strcmp(t->attr, "proto") == 0 && strcmp(t->val, proto) == 0)
1169                         return 1;
1170         return 0;
1171 }
1172
1173 /*
1174  *  lookup a request.  the network "net" means we should pick the
1175  *  best network to get there.
1176  */
1177 int
1178 lookup(Mfile *mf)
1179 {
1180         Network *np;
1181         char *cp;
1182         struct ndbtuple *nt, *t;
1183         char reply[Maxreply];
1184         int i, rv;
1185         int hack;
1186
1187         /* open up the standard db files */
1188         if(db == 0)
1189                 ndbinit();
1190         if(db == 0)
1191                 error(1, 0, "%s: %r","can't open mf->network database\n");
1192
1193         rv = 0;
1194
1195         if(mf->net == NULL)
1196                 return 0;       /* must have been a genquery */
1197
1198         if(strcmp(mf->net, "net") == 0){
1199                 /*
1200                  *  go through set of default nets
1201                  */
1202                 for(np = mf->nextnet; np; np = np->next){
1203                         nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1204                         if(nt == NULL)
1205                                 continue;
1206                         hack = np->fasttimeouthack && !lookforproto(nt, np->net);
1207                         for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1208                                 cp = (*np->trans)(t, np, mf->serv, mf->rem, hack);
1209                                 if(cp){
1210                                         /* avoid duplicates */
1211                                         for(i = 0; i < mf->nreply; i++)
1212                                                 if(strcmp(mf->reply[i], cp) == 0)
1213                                                         break;
1214                                         if(i == mf->nreply){
1215                                                 /* save the reply */
1216                                                 mf->replylen[mf->nreply] = strlen(cp);
1217                                                 mf->reply[mf->nreply++] = cp;
1218                                                 rv++;
1219                                         }
1220                                 }
1221                         }
1222                         ndbfree(nt);
1223                         np = np->next;
1224                         break;
1225                 }
1226                 mf->nextnet = np;
1227                 return rv;
1228         }
1229
1230         /*
1231          *  if not /net, we only get one lookup
1232          */
1233         if(mf->nreply != 0)
1234                 return 0;
1235         /*
1236          *  look for a specific network
1237          */
1238         for(np = netlist; np && np->net != NULL; np++){
1239                 if(np->fasttimeouthack)
1240                         continue;
1241                 if(strcmp(np->net, mf->net) == 0)
1242                         break;
1243         }
1244
1245         if(np && np->net != NULL){
1246                 /*
1247                  *  known network
1248                  */
1249                 nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1250                 for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1251                         cp = (*np->trans)(t, np, mf->serv, mf->rem, 0);
1252                         if(cp){
1253                                 mf->replylen[mf->nreply] = strlen(cp);
1254                                 mf->reply[mf->nreply++] = cp;
1255                                 rv++;
1256                         }
1257                 }
1258                 ndbfree(nt);
1259                 return rv;
1260         } else {
1261                 /*
1262                  *  not a known network, don't translate host or service
1263                  */
1264                 if(mf->serv)
1265                         snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s",
1266                                 mntpt, mf->net, mf->host, mf->serv);
1267                 else
1268                         snprintf(reply, sizeof(reply), "%s/%s/clone %s",
1269                                 mntpt, mf->net, mf->host);
1270                 mf->reply[0] = strdup(reply);
1271                 mf->replylen[0] = strlen(reply);
1272                 mf->nreply = 1;
1273                 return 1;
1274         }
1275 }
1276
1277 /*
1278  *  translate an ip service name into a port number.  If it's a numeric port
1279  *  number, look for restricted access.
1280  *
1281  *  the service '*' needs no translation.
1282  */
1283 char*
1284 ipserv(Network *np, char *name, char *buf, int blen)
1285 {
1286         char *p;
1287         int alpha = 0;
1288         int restr = 0;
1289         char port[10];
1290         struct ndbtuple *t, *nt;
1291         struct ndbs s;
1292
1293         /* '*' means any service */
1294         if(strcmp(name, "*")==0){
1295                 strcpy(buf, name);
1296                 return buf;
1297         }
1298
1299         /*  see if it's numeric or symbolic */
1300         port[0] = 0;
1301         for(p = name; *p; p++){
1302                 if(isdigit(*p))
1303                         {}
1304                 else if(isalpha(*p) || *p == '-' || *p == '$')
1305                         alpha = 1;
1306                 else
1307                         return 0;
1308         }
1309         t = NULL;
1310         p = NULL;
1311         if(alpha){
1312                 p = ndbgetvalue(db, &s, np->net, name, "port", &t);
1313                 if(p == NULL)
1314                         return 0;
1315         } else {
1316                 /* look up only for tcp ports < 1024 to get the restricted
1317                  * attribute
1318                  */
1319                 if(atoi(name) < 1024 && strcmp(np->net, "tcp") == 0)
1320                         p = ndbgetvalue(db, &s, "port", name, "port", &t);
1321                 if(p == NULL)
1322                         p = strdup(name);
1323         }
1324
1325         if(t){
1326                 for(nt = t; nt; nt = nt->entry)
1327                         if(strcmp(nt->attr, "restricted") == 0)
1328                                 restr = 1;
1329                 ndbfree(t);
1330         }
1331         snprintf(buf, blen, "%s%s", p, restr ? "!r" : "");
1332         free(p);
1333
1334         return buf;
1335 }
1336
1337 /*
1338  *  lookup an ip attribute
1339  */
1340 int
1341 ipattrlookup(struct ndb *db, char *ipa, char *attr, char *val, int vlen)
1342 {
1343
1344         struct ndbtuple *t, *nt;
1345         char *alist[2];
1346
1347         alist[0] = attr;
1348         t = ndbipinfo(db, "ip", ipa, alist, 1);
1349         if(t == NULL)
1350                 return 0;
1351         for(nt = t; nt != NULL; nt = nt->entry){
1352                 if(strcmp(nt->attr, attr) == 0){
1353                         nstrcpy(val, nt->val, vlen);
1354                         ndbfree(t);
1355                         return 1;
1356                 }
1357         }
1358
1359         /* we shouldn't get here */
1360         ndbfree(t);
1361         return 0;
1362 }
1363
1364 /*
1365  *  lookup (and translate) an ip destination
1366  */
1367 struct ndbtuple*
1368 iplookup(Network *np, char *host, char *serv, int nolookup)
1369 {
1370         char *attr, *dnsname;
1371         struct ndbtuple *t, *nt;
1372         struct ndbs s;
1373         char ts[Maxservice];
1374         char dollar[Maxhost];
1375         uint8_t ip[IPaddrlen];
1376         uint8_t net[IPaddrlen];
1377         uint8_t tnet[IPaddrlen];
1378         struct ipifc *ifc;
1379         struct iplifc *lifc;
1380
1381         /*
1382          *  start with the service since it's the most likely to fail
1383          *  and costs the least
1384          */
1385         werrstr("can't translate address");
1386         if(serv==0 || ipserv(np, serv, ts, sizeof ts) == 0){
1387                 werrstr("can't translate service");
1388                 return 0;
1389         }
1390
1391         /* for dial strings with no host */
1392         if(strcmp(host, "*") == 0)
1393                 return ndbnew("ip", "*");
1394
1395         /*
1396          *  hack till we go v6 :: = 0.0.0.0
1397          */
1398         if(strcmp("::", host) == 0)
1399                 return ndbnew("ip", "*");
1400
1401         /*
1402          *  '$' means the rest of the name is an attribute that we
1403          *  need to search for
1404          */
1405         if(*host == '$'){
1406                 if(ipattrlookup(db, ipaddr, host+1, dollar, sizeof dollar))
1407                         host = dollar;
1408         }
1409
1410         /*
1411          *  turn '[ip address]' into just 'ip address'
1412          */
1413         if(*host == '[' && host[strlen(host)-1] == ']'){
1414                 host++;
1415                 host[strlen(host)-1] = 0;
1416         }
1417
1418         /*
1419          *  just accept addresses
1420          */
1421         attr = ipattr(host);
1422         if(strcmp(attr, "ip") == 0)
1423                 return ndbnew("ip", host);
1424
1425         /*
1426          *  give the domain name server the first opportunity to
1427          *  resolve domain names.  if that fails try the database.
1428          */
1429         t = 0;
1430         werrstr("can't translate address");
1431         if(strcmp(attr, "dom") == 0)
1432                 t = dnsiplookup(host, &s);
1433         if(t == 0)
1434                 free(ndbgetvalue(db, &s, attr, host, "ip", &t));
1435         if(t == 0){
1436                 dnsname = ndbgetvalue(db, &s, attr, host, "dom", NULL);
1437                 if(dnsname){
1438                         t = dnsiplookup(dnsname, &s);
1439                         free(dnsname);
1440                 }
1441         }
1442         if(t == 0)
1443                 t = dnsiplookup(host, &s);
1444         if(t == 0)
1445                 return 0;
1446
1447         /*
1448          *  reorder the tuple to have the matched line first and
1449          *  save that in the request structure.
1450          */
1451         t = reorder(t, s.t);
1452
1453         /*
1454          * reorder according to our interfaces
1455          */
1456         //lock(&ipifclock);
1457         for(ifc = ipifcs; ifc != NULL; ifc = ifc->next){
1458                 for(lifc = ifc->lifc; lifc != NULL; lifc = lifc->next){
1459                         maskip(lifc->ip, lifc->mask, net);
1460                         for(nt = t; nt; nt = nt->entry){
1461                                 if(strcmp(nt->attr, "ip") != 0)
1462                                         continue;
1463                                 parseip(ip, nt->val);
1464                                 maskip(ip, lifc->mask, tnet);
1465                                 if(memcmp(net, tnet, IPaddrlen) == 0){
1466                                         t = reorder(t, nt);
1467                                         //unlock(&ipifclock);
1468                                         return t;
1469                                 }
1470                         }
1471                 }
1472         }
1473         //unlock(&ipifclock);
1474
1475         return t;
1476 }
1477
1478 /*
1479  *  translate an ip address
1480  */
1481 char*
1482 iptrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int hack)
1483 {
1484         char ts[Maxservice];
1485         char reply[Maxreply];
1486         char x[Maxservice];
1487
1488         if(strcmp(t->attr, "ip") != 0)
1489                 return 0;
1490
1491         if(serv == 0 || ipserv(np, serv, ts, sizeof ts) == 0){
1492                 werrstr("can't translate service");
1493                 return 0;
1494         }
1495         if(rem != NULL)
1496                 snprintf(x, sizeof(x), "!%s", rem);
1497         else
1498                 *x = 0;
1499
1500         if(*t->val == '*')
1501                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s",
1502                         mntpt, np->net, ts, x);
1503         else
1504                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s%s",
1505                         mntpt, np->net, t->val, ts, x, hack? "!fasttimeout": "");
1506
1507         return strdup(reply);
1508 }
1509
1510 /*
1511  *  lookup a telephone number
1512  */
1513 struct ndbtuple*
1514 telcolookup(Network *np, char *host, char *serv, int nolookup)
1515 {
1516         struct ndbtuple *t;
1517         struct ndbs s;
1518
1519         werrstr("can't translate address");
1520         free(ndbgetvalue(db, &s, "sys", host, "telco", &t));
1521         if(t == 0)
1522                 return ndbnew("telco", host);
1523
1524         return reorder(t, s.t);
1525 }
1526
1527 /*
1528  *  translate a telephone address
1529  */
1530 char*
1531 telcotrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int unused)
1532 {
1533         char reply[Maxreply];
1534         char x[Maxservice];
1535
1536         if(strcmp(t->attr, "telco") != 0)
1537                 return 0;
1538
1539         if(rem != NULL)
1540                 snprintf(x, sizeof(x), "!%s", rem);
1541         else
1542                 *x = 0;
1543         if(serv)
1544                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s", mntpt, np->net,
1545                         t->val, serv, x);
1546         else
1547                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s", mntpt, np->net,
1548                         t->val, x);
1549         return strdup(reply);
1550 }
1551
1552 /*
1553  *  reorder the tuple to put x's line first in the entry
1554  */
1555 struct ndbtuple*
1556 reorder(struct ndbtuple *t, struct ndbtuple *x)
1557 {
1558         struct ndbtuple *nt;
1559         struct ndbtuple *line;
1560
1561         /* find start of this entry's line */
1562         for(line = x; line->entry == line->line; line = line->line)
1563                 ;
1564         line = line->line;
1565         if(line == t)
1566                 return t;       /* already the first line */
1567
1568         /* remove this line and everything after it from the entry */
1569         for(nt = t; nt->entry != line; nt = nt->entry)
1570                 ;
1571         nt->entry = 0;
1572
1573         /* make that the start of the entry */
1574         for(nt = line; nt->entry; nt = nt->entry)
1575                 ;
1576         nt->entry = t;
1577         return line;
1578 }
1579
1580 static struct ndbtuple*
1581 dnsip6lookup(char *mntpt, char *buf, struct ndbtuple *t)
1582 {
1583         struct ndbtuple *t6, *tt;
1584
1585         t6 = dnsquery(mntpt, buf, "ipv6");      /* lookup AAAA dns RRs */
1586         if (t6 == NULL)
1587                 return t;
1588
1589         /* convert ipv6 attr to ip */
1590         for (tt = t6; tt != NULL; tt = tt->entry)
1591                 if (strcmp(tt->attr, "ipv6") == 0)
1592                         strncpy(tt->attr, "ip", sizeof tt->attr - 1);
1593
1594         if (t == NULL)
1595                 return t6;
1596
1597         /* append t6 list to t list */
1598         for (tt = t; tt->entry != NULL; tt = tt->entry)
1599                 ;
1600         tt->entry = t6;
1601         return t;
1602 }
1603
1604 /*
1605  *  call the dns process and have it try to translate a name
1606  */
1607 struct ndbtuple*
1608 dnsiplookup(char *host, struct ndbs *s)
1609 {
1610         char buf[Maxreply];
1611         struct ndbtuple *t;
1612
1613         //unlock(&dblock);
1614
1615         /* save the name */
1616         snprintf(buf, sizeof(buf), "%s", host);
1617
1618         if(strcmp(ipattr(buf), "ip") == 0)
1619                 t = dnsquery(mntpt, buf, "ptr");
1620         else {
1621                 t = dnsquery(mntpt, buf, "ip");
1622                 /* special case: query ipv6 (AAAA dns RR) too */
1623                 if (ipv6lookups)
1624                         t = dnsip6lookup(mntpt, buf, t);
1625         }
1626         s->t = t;
1627
1628         if(t == NULL){
1629                 snprintf(buf, sizeof buf, "%r");
1630                 if(strstr(buf, "exist"))
1631                         werrstr("can't translate address: %s", buf);
1632                 else if(strstr(buf, "dns failure"))
1633                         werrstr("temporary problem: %s", buf);
1634         }
1635
1636         //lock(&dblock);
1637         return t;
1638 }
1639
1640 int
1641 qmatch(struct ndbtuple *t, char **attr, char **val, int n)
1642 {
1643         int i, found;
1644         struct ndbtuple *nt;
1645
1646         for(i = 1; i < n; i++){
1647                 found = 0;
1648                 for(nt = t; nt; nt = nt->entry)
1649                         if(strcmp(attr[i], nt->attr) == 0)
1650                                 if(strcmp(val[i], "*") == 0
1651                                 || strcmp(val[i], nt->val) == 0){
1652                                         found = 1;
1653                                         break;
1654                                 }
1655                 if(found == 0)
1656                         break;
1657         }
1658         return i == n;
1659 }
1660
1661 /* this is awful but I don't want to bring in libstring just for this.
1662  * you want real strings don't use C
1663  */
1664 void
1665 qreply(Mfile *mf, struct ndbtuple *t)
1666 {
1667         struct ndbtuple *nt;
1668         char *s, *cur;
1669         int len, amt;
1670
1671         s = malloc(4096);
1672         cur = s;
1673         len = 4096;
1674
1675         for(nt = t; mf->nreply < Nreply && nt; nt = nt->entry){
1676                 amt = snprintf(cur, len, "%s=%s", nt->attr, nt->val);
1677
1678                 if (amt < 0)
1679                         len = 0;
1680                 else {
1681                         len -= amt;
1682                         cur += len;
1683                 }
1684
1685                 if(nt->line != nt->entry){
1686                         mf->replylen[mf->nreply] = strlen(s);
1687                         mf->reply[mf->nreply++] = strdup(s);
1688                         cur = s;
1689                         len = 4096;
1690                 } else {
1691                         amt = snprintf(cur, len, " ");
1692                         if (amt < 0)
1693                                 len = 0;
1694                         else {
1695                                 len -= amt;
1696                                 cur += len;
1697                         }
1698                 }
1699
1700         }
1701         free(s);
1702 }
1703
1704 enum
1705 {
1706         Maxattr=        32,
1707 };
1708
1709 /*
1710  *  generic query lookup.  The query is of one of the following
1711  *  forms:
1712  *
1713  *  attr1=val1 attr2=val2 attr3=val3 ...
1714  *
1715  *  returns the matching tuple
1716  *
1717  *  ipinfo attr=val attr1 attr2 attr3 ...
1718  *
1719  *  is like ipinfo and returns the attr{1-n}
1720  *  associated with the ip address.
1721  */
1722 char*
1723 genquery(Mfile *mf, char *query)
1724 {
1725         int i, n;
1726         char *p;
1727         char *attr[Maxattr];
1728         char *val[Maxattr];
1729         struct ndbtuple *t;
1730         struct ndbs s;
1731
1732         n = getfields(query, attr, ARRAY_SIZE(attr), 1, " ");
1733         if(n == 0)
1734                 return "bad query";
1735
1736         if(strcmp(attr[0], "ipinfo") == 0)
1737                 return ipinfoquery(mf, attr, n);
1738
1739         /* parse pairs */
1740         for(i = 0; i < n; i++){
1741                 p = strchr(attr[i], '=');
1742                 if(p == 0)
1743                         return "bad query";
1744                 *p++ = 0;
1745                 val[i] = p;
1746         }
1747
1748         /* give dns a chance */
1749         if((strcmp(attr[0], "dom") == 0 || strcmp(attr[0], "ip") == 0) && val[0]){
1750                 t = dnsiplookup(val[0], &s);
1751                 if(t){
1752                         if(qmatch(t, attr, val, n)){
1753                                 qreply(mf, t);
1754                                 ndbfree(t);
1755                                 return 0;
1756                         }
1757                         ndbfree(t);
1758                 }
1759         }
1760
1761         /* first pair is always the key.  It can't be a '*' */
1762         t = ndbsearch(db, &s, attr[0], val[0]);
1763
1764         /* search is the and of all the pairs */
1765         while(t){
1766                 if(qmatch(t, attr, val, n)){
1767                         qreply(mf, t);
1768                         ndbfree(t);
1769                         return 0;
1770                 }
1771
1772                 ndbfree(t);
1773                 t = ndbsnext(&s, attr[0], val[0]);
1774         }
1775
1776         return "no match";
1777 }
1778
1779 /*
1780  *  resolve an ip address
1781  */
1782 static struct ndbtuple*
1783 ipresolve(char *attr, char *host)
1784 {
1785         struct ndbtuple *t, *nt, **l;
1786
1787         t = iplookup(&network[Ntcp], host, "*", 0);
1788         for(l = &t; *l != NULL; ){
1789                 nt = *l;
1790                 if(strcmp(nt->attr, "ip") != 0){
1791                         *l = nt->entry;
1792                         nt->entry = NULL;
1793                         ndbfree(nt);
1794                         continue;
1795                 }
1796                 strcpy(nt->attr, attr);
1797                 l = &nt->entry;
1798         }
1799         return t;
1800 }
1801
1802 char*
1803 ipinfoquery(Mfile *mf, char **list, int n)
1804 {
1805         int i, nresolve;
1806         int resolve[Maxattr];
1807         struct ndbtuple *t, *nt, **l;
1808         char *attr, *val;
1809
1810         /* skip 'ipinfo' */
1811         list++; n--;
1812
1813         if(n < 1)
1814                 return "bad query";
1815
1816         /* get search attribute=value, or assume ip=myipaddr */
1817         attr = *list;
1818         if((val = strchr(attr, '=')) != NULL){
1819                 *val++ = 0;
1820                 list++;
1821                 n--;
1822         }else{
1823                 attr = "ip";
1824                 val = ipaddr;
1825         }
1826
1827         if(n < 1)
1828                 return "bad query";
1829
1830         /*
1831          *  don't let ndbipinfo resolve the addresses, we're
1832          *  better at it.
1833          */
1834         nresolve = 0;
1835         for(i = 0; i < n; i++)
1836                 if(*list[i] == '@'){            /* @attr=val ? */
1837                         list[i]++;
1838                         resolve[i] = 1;         /* we'll resolve it */
1839                         nresolve++;
1840                 } else
1841                         resolve[i] = 0;
1842
1843         t = ndbipinfo(db, attr, val, list, n);
1844         if(t == NULL)
1845                 return "no match";
1846
1847         if(nresolve != 0){
1848                 for(l = &t; *l != NULL;){
1849                         nt = *l;
1850
1851                         /* already an address? */
1852                         if(strcmp(ipattr(nt->val), "ip") == 0){
1853                                 l = &(*l)->entry;
1854                                 continue;
1855                         }
1856
1857                         /* user wants it resolved? */
1858                         for(i = 0; i < n; i++)
1859                                 if(strcmp(list[i], nt->attr) == 0)
1860                                         break;
1861                         if(i >= n || resolve[i] == 0){
1862                                 l = &(*l)->entry;
1863                                 continue;
1864                         }
1865
1866                         /* resolve address and replace entry */
1867                         *l = ipresolve(nt->attr, nt->val);
1868                         while(*l != NULL)
1869                                 l = &(*l)->entry;
1870                         *l = nt->entry;
1871
1872                         nt->entry = NULL;
1873                         ndbfree(nt);
1874                 }
1875         }
1876
1877         /* make it all one line */
1878         for(nt = t; nt != NULL; nt = nt->entry){
1879                 if(nt->entry == NULL)
1880                         nt->line = t;
1881                 else
1882                         nt->line = nt->entry;
1883         }
1884
1885         qreply(mf, t);
1886
1887         return NULL;
1888 }
1889
1890 void*
1891 emalloc(int size)
1892 {
1893         void *x;
1894
1895         x = calloc(size, 1);
1896         if(x == NULL)
1897                 abort();
1898         memset(x, 0, size);
1899         return x;
1900 }
1901
1902 char*
1903 estrdup(char *s)
1904 {
1905         int size;
1906         char *p;
1907
1908         size = strlen(s)+1;
1909         p = calloc(size, 1);
1910         if(p == NULL)
1911                 abort();
1912         memmove(p, s, size);
1913         return p;
1914 }