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