Remove a moron error in test/cs.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 <ndb.h>
23 #include <fcallfmt.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         register_printf_specifier('F', printf_fcall, printf_fcall_info);
255         ext[0] = 0;
256         argc--, argv++;
257         while (argc && **argv == '-'){
258                 switch(argv[0][1]){
259         case '4':
260                 ipv6lookups = 0;
261                 break;
262         case 'd':
263                 debug = 1;
264                 break;
265         case 'f':
266                 if (argc < 2)
267                         usage();
268                 dbfile = argv[1];
269                 argc--,argv++;
270                 break;
271         case 'n':
272                 justsetname = 1;
273                 break;
274         case 'x':
275                 if (argc < 2)
276                         usage();
277                 setnetmtpt(mntpt, sizeof(mntpt), argv[1]);
278                 argc--,argv++;
279                 setext(ext, sizeof(ext), mntpt);
280                 break;
281                 }
282                 argc--,argv++;
283         }
284
285         //rfork(RFREND|RFNOTEG);
286
287         snprintf(servefile, sizeof(servefile), "#s/cs%s", ext);
288         snprintf(netndb, sizeof(netndb), "%s/ndb", mntpt);
289         syscall(SYS_nunmount, (unsigned long)servefile, (unsigned long)mntpt);
290         remove(servefile);
291
292         ndbinit();
293         netinit(0);
294
295         if(!justsetname){
296                 mountinit(servefile, mntpt);
297                 io();
298         }
299         exit(0);
300 }
301
302 /*
303  *  if a mount point is specified, set the cs extention to be the mount point
304  *  with '_'s replacing '/'s
305  */
306 void
307 setext(char *ext, int n, char *p)
308 {
309         int i, c;
310
311         n--;
312         for(i = 0; i < n; i++){
313                 c = p[i];
314                 if(c == 0)
315                         break;
316                 if(c == '/')
317                         c = '_';
318                 ext[i] = c;
319         }
320         ext[i] = 0;
321 }
322
323 void
324 mountinit(char *service, char *mntpt)
325 {
326         int f;
327         int p[2];
328         char buf[32];
329         int ret;
330
331         ret = syscall(SYS_pipe, (unsigned long)p);
332         if (ret < 0){
333                 error(1, 0, "pipe: %r");
334                 exit(1);
335         }
336
337         /*
338          *  make a /srv/cs
339          * ORCLOSE means remove on last close. Handy. Not here yet. 
340          */
341         f = open(service, O_WRONLY|O_CREAT/*|ORCLOSE*/, 0666);
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 //      //lock(&joblock);
403         job->next = joblist;
404         joblist = job;
405         job->request.tag = -1;
406 //      //unlock(&joblock);
407         return job;
408 }
409
410 void
411 freejob(Job *job)
412 {
413         Job **l;
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                         fprintf(stderr, "convM2S went south: format error %ux %ux %ux %ux %ux",
523                                 mdata[0], mdata[1], mdata[2], mdata[3], mdata[4]);
524                         error(1, 0, "format error %ux %ux %ux %ux %ux",
525                                 mdata[0], mdata[1], mdata[2], mdata[3], mdata[4]);
526                         freejob(job);
527                         continue;
528                 }
529                 /* stash the thread in the job so we can join them all
530                  * later if we want to.
531                  */
532 #if 0
533                 if (pthread_create(&job->thread, NULL, &job_thread, job)) {
534                         error(1, 0, "%s: %r","Failed to create job");
535                         continue;
536                 }
537 #endif
538         job_thread(job);
539
540
541         }
542 }
543
544 void
545 rversion(Job *job)
546 {
547         if(job->request.msize > IOHDRSZ + Maxfdata)
548                 job->reply.msize = IOHDRSZ + Maxfdata;
549         else
550                 job->reply.msize = job->request.msize;
551         if(strncmp(job->request.version, "9P2000", 6) != 0)
552                 sendmsg(job, "unknown 9P version");
553         else{
554                 job->reply.version = "9P2000";
555                 sendmsg(job, 0);
556         }
557 }
558
559 void
560 rauth(Job *job)
561 {
562         sendmsg(job, "cs: authentication not required");
563 }
564
565 /*
566  *  don't flush till all the threads  are done
567  */
568 void
569 rflush(Job *job)
570 {
571         flushjob(job->request.oldtag);
572         sendmsg(job, 0);
573 }
574
575 void
576 rattach(Job *job, Mfile *mf)
577 {
578         if(mf->busy == 0){
579                 mf->busy = 1;
580                 mf->user = estrdup(job->request.uname);
581         }
582         mf->qid.vers = vers++;
583         mf->qid.type = QTDIR;
584         mf->qid.path = 0LL;
585         job->reply.qid = mf->qid;
586         sendmsg(job, 0);
587 }
588
589
590 char*
591 rwalk(Job *job, Mfile *mf)
592 {
593         char *err;
594         char **elems;
595         int nelems;
596         int i;
597         Mfile *nmf;
598         struct qid qid;
599
600         err = 0;
601         nmf = NULL;
602         elems = job->request.wname;
603         nelems = job->request.nwname;
604         job->reply.nwqid = 0;
605
606         if(job->request.newfid != job->request.fid){
607                 /* clone fid */
608                 nmf = newfid(job->request.newfid);
609                 if(nmf->busy){
610                         nmf = NULL;
611                         err = "clone to used channel";
612                         goto send;
613                 }
614                 *nmf = *mf;
615                 nmf->user = estrdup(mf->user);
616                 nmf->fid = job->request.newfid;
617                 nmf->qid.vers = vers++;
618                 mf = nmf;
619         }
620         /* else nmf will be nil */
621
622         qid = mf->qid;
623         if(nelems > 0){
624                 /* walk fid */
625                 for(i=0; i<nelems && i<MAXWELEM; i++){
626                         if((qid.type & QTDIR) == 0){
627                                 err = "not a directory";
628                                 break;
629                         }
630                         if(strcmp(elems[i], "..") == 0 || strcmp(elems[i], ".") == 0){
631                                 qid.type = QTDIR;
632                                 qid.path = Qdir;
633     Found:
634                                 job->reply.wqid[i] = qid;
635                                 job->reply.nwqid++;
636                                 continue;
637                         }
638                         if(strcmp(elems[i], "cs") == 0){
639                                 qid.type = QTFILE;
640                                 qid.path = Qcs;
641                                 goto Found;
642                         }
643                         err = "file does not exist";
644                         break;
645                 }
646         }
647
648     send:
649         if(nmf != NULL && (err!=NULL || job->reply.nwqid<nelems)){
650                 cleanmf(nmf);
651                 free(nmf->user);
652                 nmf->user = 0;
653                 nmf->busy = 0;
654                 nmf->fid = 0;
655         }
656         if(err == NULL)
657                 mf->qid = qid;
658         sendmsg(job, err);
659         return err;
660 }
661
662 void
663 ropen(Job *job, Mfile *mf)
664 {
665         int mode;
666         char *err;
667
668         err = 0;
669         mode = job->request.mode;
670         if(mf->qid.type & QTDIR){
671                 if(mode)
672                         err = "permission denied";
673         }
674         job->reply.qid = mf->qid;
675         job->reply.iounit = 0;
676         sendmsg(job, err);
677 }
678
679 void
680 rcreate(Job *job, Mfile *mf)
681 {
682         sendmsg(job, "creation permission denied");
683 }
684
685 void
686 rread(Job *job, Mfile *mf)
687 {
688         int i, n, cnt;
689         long off, toff, clock;
690         struct dir dir;
691         uint8_t buf[Maxfdata];
692         char *err;
693
694         n = 0;
695         err = 0;
696         off = job->request.offset;
697         cnt = job->request.count;
698         if(mf->qid.type & QTDIR){
699                 //      clock = time(0);
700                 if(off == 0){
701                         memset(&dir, 0, sizeof dir);
702                         dir.name = "cs";
703                         dir.qid.type = QTFILE;
704                         dir.qid.vers = vers;
705                         dir.qid.path = Qcs;
706                         dir.mode = 0666;
707                         dir.length = 0;
708                         dir.uid = mf->user;
709                         dir.gid = mf->user;
710                         dir.muid = mf->user;
711                         dir.atime = clock;      /* wrong */
712                         dir.mtime = clock;      /* wrong */
713                         n = convD2M(&dir, buf, sizeof buf);
714                 }
715                 job->reply.data = (char*)buf;
716         } else {
717                 for(;;){
718                         /* look for an answer at the right offset */
719                         toff = 0;
720                         for(i = 0; mf->reply[i] && i < mf->nreply; i++){
721                                 n = mf->replylen[i];
722                                 if(off < toff + n)
723                                         break;
724                                 toff += n;
725                         }
726                         if(i < mf->nreply)
727                                 break;          /* got something to return */
728
729                         /* try looking up more answers */
730                         if(lookup(mf) == 0){
731                                 /* no more */
732                                 n = 0;
733                                 goto send;
734                         }
735                 }
736
737                 /* give back a single reply (or part of one) */
738                 job->reply.data = mf->reply[i] + (off - toff);
739                 if(cnt > toff - off + n)
740                         n = toff - off + n;
741                 else
742                         n = cnt;
743         }
744 send:
745         job->reply.count = n;
746         sendmsg(job, err);
747 }
748 void
749 cleanmf(Mfile *mf)
750 {
751         int i;
752
753         if(mf->net != NULL){
754                 free(mf->net);
755                 mf->net = NULL;
756         }
757         if(mf->host != NULL){
758                 free(mf->host);
759                 mf->host = NULL;
760         }
761         if(mf->serv != NULL){
762                 free(mf->serv);
763                 mf->serv = NULL;
764         }
765         if(mf->rem != NULL){
766                 free(mf->rem);
767                 mf->rem = NULL;
768         }
769         for(i = 0; i < mf->nreply; i++){
770                 free(mf->reply[i]);
771                 mf->reply[i] = NULL;
772                 mf->replylen[i] = 0;
773         }
774         mf->nreply = 0;
775         mf->nextnet = netlist;
776 }
777
778 void
779 rwrite(Job *job, Mfile *mf)
780 {
781         int cnt, n;
782         char *err;
783         char *field[4];
784         char curerr[64];
785
786         err = 0;
787         cnt = job->request.count;
788         if(mf->qid.type & QTDIR){
789                 err = "can't write directory";
790                 goto send;
791         }
792         if(cnt >= Maxrequest){
793                 err = "request too long";
794                 goto send;
795         }
796         job->request.data[cnt] = 0;
797         /*
798          *  toggle debugging
799          */
800         if(strncmp(job->request.data, "debug", 5)==0){
801                 debug ^= 1;
802                 fprintf(stderr, "CS:debug %d", debug);
803                 goto send;
804         }
805
806         /*
807          *  toggle ipv6 lookups
808          */
809         if(strncmp(job->request.data, "ipv6", 4)==0){
810                 ipv6lookups ^= 1;
811                 fprintf(stderr, "CS:ipv6lookups %d", ipv6lookups);
812                 goto send;
813         }
814
815         /*
816          *  toggle debugging
817          */
818         if(strncmp(job->request.data, "paranoia", 8)==0){
819                 paranoia ^= 1;
820                 fprintf(stderr,  "CS:paranoia %d", paranoia);
821                 goto send;
822         }
823
824         /*
825          *  add networks to the default list
826          */
827         if(strncmp(job->request.data, "add ", 4)==0){
828                 if(job->request.data[cnt-1] == '\n')
829                         job->request.data[cnt-1] = 0;
830                 netadd(job->request.data+4);
831                 readipinterfaces();
832                 goto send;
833         }
834
835         /*
836          *  refresh all state
837          */
838         if(strncmp(job->request.data, "refresh", 7)==0){
839                 netinit(0/*1*/);
840                 goto send;
841         }
842
843         /* start transaction with a clean slate */
844         cleanmf(mf);
845
846         /*
847          *  look for a general query
848          */
849         if(*job->request.data == '!'){
850                 err = genquery(mf, job->request.data+1);
851                 goto send;
852         }
853
854         if(debug)
855                 fprintf(stderr,  "CS:write %s", job->request.data);
856         if(paranoia)
857                 fprintf(stderr,  "CS:write %s by %s", job->request.data, mf->user);
858
859         /*
860          *  break up name
861          */
862         n = getfields(job->request.data, field, 4, 1, "!");
863         switch(n){
864         case 1:
865                 mf->net = strdup("net");
866                 mf->host = strdup(field[0]);
867                 break;
868         case 4:
869                 mf->rem = strdup(field[3]);
870                 /* fall through */
871         case 3:
872                 mf->serv = strdup(field[2]);
873                 /* fall through */
874         case 2:
875                 mf->host = strdup(field[1]);
876                 mf->net = strdup(field[0]);
877                 break;
878         }
879         /*
880          *  do the first net worth of lookup
881          */
882         if(lookup(mf) == 0){
883                 snprintf(curerr, sizeof curerr, "%r");
884                 err = curerr;
885         }
886 send:
887         job->reply.count = cnt;
888         sendmsg(job, err);
889 }
890
891 void
892 rclunk(Job *job, Mfile *mf)
893 {
894         cleanmf(mf);
895         free(mf->user);
896         mf->user = 0;
897         mf->busy = 0;
898         mf->fid = 0;
899         sendmsg(job, 0);
900 }
901
902 void
903 rremove(Job *job, Mfile *mf)
904 {
905         sendmsg(job, "remove permission denied");
906 }
907
908 void
909 rstat(Job *job, Mfile *mf)
910 {
911         struct dir dir;
912         uint8_t buf[IOHDRSZ+Maxfdata];
913
914         memset(&dir, 0, sizeof dir);
915         if(mf->qid.type & QTDIR){
916                 dir.name = ".";
917                 dir.mode = DMDIR|0555;
918         } else {
919                 dir.name = "cs";
920                 dir.mode = 0666;
921         }
922         dir.qid = mf->qid;
923         dir.length = 0;
924         dir.uid = mf->user;
925         dir.gid = mf->user;
926         dir.muid = mf->user;
927         //dir.atime = dir.mtime = time(0);
928         job->reply.nstat = convD2M(&dir, buf, sizeof buf);
929         job->reply.stat = buf;
930         sendmsg(job, 0);
931 }
932
933 void
934 rwstat(Job *job, Mfile *mf)
935 {
936         sendmsg(job, "wstat permission denied");
937 }
938
939 void
940 sendmsg(Job *job, char *err)
941 {
942         int n;
943         uint8_t mdata[IOHDRSZ + Maxfdata];
944         char ename[ERRMAX];
945
946         if(err){
947                 job->reply.type = Rerror;
948                 snprintf(ename, sizeof(ename), "cs: %s", err);
949                 job->reply.ename = ename;
950         }else{
951                 job->reply.type = job->request.type+1;
952         }
953         job->reply.tag = job->request.tag;
954         n = convS2M(&job->reply, mdata, sizeof mdata);
955         if(n == 1){
956                 fprintf(stderr,  "CS:sendmsg convS2M of %F returns 0", &job->reply);
957                 abort();
958         }
959         //lock(&joblock);
960         if(job->flushed == 0)
961                 if(write(mfd[1], mdata, n)!=n)
962                         error(1, 0, "%s: %r","mount write");
963         //unlock(&joblock);
964         if(debug)
965                 fprintf(stderr,  "CS:%F %d", &job->reply, n);
966 }
967
968 static int
969 isvalidip(uint8_t *ip)
970 {
971         return ipcmp(ip, IPnoaddr) != 0 && ipcmp(ip, v4prefix) != 0;
972 }
973
974 static uint8_t loopbacknet[IPaddrlen] = {
975         0, 0, 0, 0,
976         0, 0, 0, 0,
977         0, 0, 0xff, 0xff,
978         127, 0, 0, 0
979 };
980 static uint8_t loopbackmask[IPaddrlen] = {
981         0xff, 0xff, 0xff, 0xff,
982         0xff, 0xff, 0xff, 0xff,
983         0xff, 0xff, 0xff, 0xff,
984         0xff, 0, 0, 0
985 };
986
987 void
988 readipinterfaces(void)
989 {
990         if(myipaddr(ipa, mntpt) != 0)
991                 ipmove(ipa, IPnoaddr);
992         snprintf(ipaddr, sizeof(ipaddr), "%I", ipa);
993         if (debug)
994                 fprintf(stderr, "CS:dns", "ipaddr is %s\n", ipaddr);
995 }
996
997 /*
998  *  get the system name
999  */
1000 void
1001 ipid(void)
1002 {
1003         uint8_t addr[6];
1004         struct ndbtuple *t, *tt;
1005         char *p, *attr;
1006         struct ndbs s;
1007         int f;
1008         char buf[Maxpath];
1009
1010         /* use environment, ether addr, or ipaddr to get system name */
1011         if(mysysname == 0){
1012                 /*
1013                  *  environment has priority.
1014                  *
1015                  *  on the sgi power the default system name
1016                  *  is the ip address.  ignore that.
1017                  *
1018                  */
1019                 p = getenv("sysname");
1020                 if(p && *p){
1021                         attr = ipattr(p);
1022                         if(strcmp(attr, "ip") != 0)
1023                                 mysysname = strdup(p);
1024                 }
1025
1026                 /*
1027                  *  the /net/ndb contains what the network
1028                  *  figured out from DHCP.  use that name if
1029                  *  there is one.
1030                  */
1031                 if(mysysname == 0 && netdb != NULL){
1032                         ndbreopen(netdb);
1033                         for(tt = t = ndbparse(netdb); t != NULL; t = t->entry){
1034                                 if(strcmp(t->attr, "sys") == 0){
1035                                         mysysname = strdup(t->val);
1036                                         break;
1037                                 }
1038                         }
1039                         ndbfree(tt);
1040                 }
1041
1042                 /* next network database, ip address, and ether address to find a name */
1043                 if(mysysname == 0){
1044                         t = NULL;
1045                         if(isvalidip(ipa))
1046                                 free(ndbgetvalue(db, &s, "ip", ipaddr, "sys", &t));
1047                         if(t == NULL){
1048                                 for(f = 0; f < 3; f++){
1049                                         snprintf(buf, sizeof buf, "%s/ether%d", mntpt, f);
1050                                         if(myetheraddr(addr, buf) >= 0){
1051                                                 snprintf(eaddr, sizeof(eaddr), "%E", addr);
1052                                                 free(ndbgetvalue(db, &s, "ether", eaddr, "sys", &t));
1053                                                 if(t != NULL)
1054                                                         break;
1055                                         }
1056                                 }
1057                         }
1058                         for(tt = t; tt != NULL; tt = tt->entry){
1059                                 if(strcmp(tt->attr, "sys") == 0){
1060                                         mysysname = strdup(tt->val);
1061                                         break;
1062                                 }
1063                         }
1064                         ndbfree(t);
1065                 }
1066
1067                 /* nothing else worked, use the ip address */
1068                 if(mysysname == 0 && isvalidip(ipa))
1069                         mysysname = strdup(ipaddr);
1070
1071
1072                 /* set /dev/sysname if we now know it */
1073                 if(mysysname){
1074                         f = open("/dev/sysname", O_RDWR);
1075                         if(f >= 0){
1076                                 write(f, mysysname, strlen(mysysname));
1077                                 close(f);
1078                         }
1079                 }
1080         }
1081 }
1082
1083 /*
1084  *  Set up a list of default networks by looking for
1085  *  /net/^*^/clone.
1086  *  For now, never background.
1087  */
1088 void
1089 netinit(int background)
1090 {
1091         char clone[Maxpath];
1092         Network *np;
1093         static int working;
1094
1095         /* add the mounted networks to the default list */
1096         for(np = network; np->net; np++){
1097                 int fuckup;
1098                 if(np->considered)
1099                         continue;
1100                 snprintf(clone, sizeof(clone), "%s/%s/clone", mntpt, np->net);
1101                 fuckup = open(clone, O_RDONLY);
1102                 if (fuckup < 0)
1103                         continue;
1104                 close(fuckup);
1105                 //if(access(clone, R_OK))
1106                         //continue;
1107                 if(netlist)
1108                         last->next = np;
1109                 else
1110                         netlist = np;
1111                 last = np;
1112                 np->next = 0;
1113                 np->considered = 1;
1114         }
1115
1116         /* find out what our ip address is */
1117         readipinterfaces();
1118
1119         /* set the system name if we need to, these days ip is all we have */
1120         ipid();
1121
1122         if(debug)
1123                 fprintf(stderr, logfile, "CS:mysysname %s eaddr %s ipaddr %s ipa %I\n",
1124                         mysysname?mysysname:"???", eaddr, ipaddr, ipa);
1125
1126 }
1127
1128 /*
1129  *  add networks to the standard list
1130  */
1131 void
1132 netadd(char *p)
1133 {
1134         Network *np;
1135         char *field[12];
1136         int i, n;
1137
1138         n = getfields(p, field, 12, 1, " ");
1139         for(i = 0; i < n; i++){
1140                 for(np = network; np->net; np++){
1141                         if(strcmp(field[i], np->net) != 0)
1142                                 continue;
1143                         if(np->considered)
1144                                 break;
1145                         if(netlist)
1146                                 last->next = np;
1147                         else
1148                                 netlist = np;
1149                         last = np;
1150                         np->next = 0;
1151                         np->considered = 1;
1152                 }
1153         }
1154 }
1155
1156 int
1157 lookforproto(struct ndbtuple *t, char *proto)
1158 {
1159         for(; t != NULL; t = t->entry)
1160                 if(strcmp(t->attr, "proto") == 0 && strcmp(t->val, proto) == 0)
1161                         return 1;
1162         return 0;
1163 }
1164
1165 /*
1166  *  lookup a request.  the network "net" means we should pick the
1167  *  best network to get there.
1168  */
1169 int
1170 lookup(Mfile *mf)
1171 {
1172         Network *np;
1173         char *cp;
1174         struct ndbtuple *nt, *t;
1175         char reply[Maxreply];
1176         int i, rv;
1177         int hack;
1178
1179         /* open up the standard db files */
1180         if(db == 0)
1181                 ndbinit();
1182         if(db == 0)
1183                 error(1, 0, "%s: %r","can't open mf->network database\n");
1184
1185         rv = 0;
1186
1187         if(mf->net == NULL)
1188                 return 0;       /* must have been a genquery */
1189
1190         if(strcmp(mf->net, "net") == 0){
1191                 /*
1192                  *  go through set of default nets
1193                  */
1194                 for(np = mf->nextnet; np; np = np->next){
1195                         nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1196                         if(nt == NULL)
1197                                 continue;
1198                         hack = np->fasttimeouthack && !lookforproto(nt, np->net);
1199                         for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1200                                 cp = (*np->trans)(t, np, mf->serv, mf->rem, hack);
1201                                 if(cp){
1202                                         /* avoid duplicates */
1203                                         for(i = 0; i < mf->nreply; i++)
1204                                                 if(strcmp(mf->reply[i], cp) == 0)
1205                                                         break;
1206                                         if(i == mf->nreply){
1207                                                 /* save the reply */
1208                                                 mf->replylen[mf->nreply] = strlen(cp);
1209                                                 mf->reply[mf->nreply++] = cp;
1210                                                 rv++;
1211                                         }
1212                                 }
1213                         }
1214                         ndbfree(nt);
1215                         np = np->next;
1216                         break;
1217                 }
1218                 mf->nextnet = np;
1219                 return rv;
1220         }
1221
1222         /*
1223          *  if not /net, we only get one lookup
1224          */
1225         if(mf->nreply != 0)
1226                 return 0;
1227         /*
1228          *  look for a specific network
1229          */
1230         for(np = netlist; np && np->net != NULL; np++){
1231                 if(np->fasttimeouthack)
1232                         continue;
1233                 if(strcmp(np->net, mf->net) == 0)
1234                         break;
1235         }
1236
1237         if(np && np->net != NULL){
1238                 /*
1239                  *  known network
1240                  */
1241                 nt = (*np->lookup)(np, mf->host, mf->serv, 1);
1242                 for(t = nt; mf->nreply < Nreply && t; t = t->entry){
1243                         cp = (*np->trans)(t, np, mf->serv, mf->rem, 0);
1244                         if(cp){
1245                                 mf->replylen[mf->nreply] = strlen(cp);
1246                                 mf->reply[mf->nreply++] = cp;
1247                                 rv++;
1248                         }
1249                 }
1250                 ndbfree(nt);
1251                 return rv;
1252         } else {
1253                 /*
1254                  *  not a known network, don't translate host or service
1255                  */
1256                 if(mf->serv)
1257                         snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s",
1258                                 mntpt, mf->net, mf->host, mf->serv);
1259                 else
1260                         snprintf(reply, sizeof(reply), "%s/%s/clone %s",
1261                                 mntpt, mf->net, mf->host);
1262                 mf->reply[0] = strdup(reply);
1263                 mf->replylen[0] = strlen(reply);
1264                 mf->nreply = 1;
1265                 return 1;
1266         }
1267 }
1268
1269 /*
1270  *  translate an ip service name into a port number.  If it's a numeric port
1271  *  number, look for restricted access.
1272  *
1273  *  the service '*' needs no translation.
1274  */
1275 char*
1276 ipserv(Network *np, char *name, char *buf, int blen)
1277 {
1278         char *p;
1279         int alpha = 0;
1280         int restr = 0;
1281         char port[10];
1282         struct ndbtuple *t, *nt;
1283         struct ndbs s;
1284
1285         /* '*' means any service */
1286         if(strcmp(name, "*")==0){
1287                 strcpy(buf, name);
1288                 return buf;
1289         }
1290
1291         /*  see if it's numeric or symbolic */
1292         port[0] = 0;
1293         for(p = name; *p; p++){
1294                 if(isdigit(*p))
1295                         {}
1296                 else if(isalpha(*p) || *p == '-' || *p == '$')
1297                         alpha = 1;
1298                 else
1299                         return 0;
1300         }
1301         t = NULL;
1302         p = NULL;
1303         if(alpha){
1304                 p = ndbgetvalue(db, &s, np->net, name, "port", &t);
1305                 if(p == NULL)
1306                         return 0;
1307         } else {
1308                 /* look up only for tcp ports < 1024 to get the restricted
1309                  * attribute
1310                  */
1311                 if(atoi(name) < 1024 && strcmp(np->net, "tcp") == 0)
1312                         p = ndbgetvalue(db, &s, "port", name, "port", &t);
1313                 if(p == NULL)
1314                         p = strdup(name);
1315         }
1316
1317         if(t){
1318                 for(nt = t; nt; nt = nt->entry)
1319                         if(strcmp(nt->attr, "restricted") == 0)
1320                                 restr = 1;
1321                 ndbfree(t);
1322         }
1323         snprintf(buf, blen, "%s%s", p, restr ? "!r" : "");
1324         free(p);
1325         return buf;
1326 }
1327
1328 /*
1329  *  lookup an ip attribute
1330  */
1331 int
1332 ipattrlookup(struct ndb *db, char *ipa, char *attr, char *val, int vlen)
1333 {
1334
1335         struct ndbtuple *t, *nt;
1336         char *alist[2];
1337
1338         alist[0] = attr;
1339         t = ndbipinfo(db, "ip", ipa, alist, 1);
1340         if(t == NULL)
1341                 return 0;
1342         for(nt = t; nt != NULL; nt = nt->entry){
1343                 if(strcmp(nt->attr, attr) == 0){
1344                         nstrcpy(val, nt->val, vlen);
1345                         ndbfree(t);
1346                         return 1;
1347                 }
1348         }
1349
1350         /* we shouldn't get here */
1351         ndbfree(t);
1352         return 0;
1353 }
1354
1355 /*
1356  *  lookup (and translate) an ip destination
1357  */
1358 struct ndbtuple*
1359 iplookup(Network *np, char *host, char *serv, int nolookup)
1360 {
1361         char *attr, *dnsname;
1362         struct ndbtuple *t, *nt;
1363         struct ndbs s;
1364         char ts[Maxservice];
1365         char dollar[Maxhost];
1366         uint8_t ip[IPaddrlen];
1367         uint8_t net[IPaddrlen];
1368         uint8_t tnet[IPaddrlen];
1369         struct ipifc *ifc;
1370         struct iplifc *lifc;
1371
1372         /*
1373          *  start with the service since it's the most likely to fail
1374          *  and costs the least
1375          */
1376         werrstr("can't translate address");
1377         if(serv==0 || ipserv(np, serv, ts, sizeof ts) == 0){
1378                 werrstr("can't translate service");
1379                 return 0;
1380         }
1381
1382         /* for dial strings with no host */
1383         if(strcmp(host, "*") == 0)
1384                 return ndbnew("ip", "*");
1385
1386         /*
1387          *  hack till we go v6 :: = 0.0.0.0
1388          */
1389         if(strcmp("::", host) == 0)
1390                 return ndbnew("ip", "*");
1391
1392         /*
1393          *  '$' means the rest of the name is an attribute that we
1394          *  need to search for
1395          */
1396         if(*host == '$'){
1397                 if(ipattrlookup(db, ipaddr, host+1, dollar, sizeof dollar))
1398                         host = dollar;
1399         }
1400
1401         /*
1402          *  turn '[ip address]' into just 'ip address'
1403          */
1404         if(*host == '[' && host[strlen(host)-1] == ']'){
1405                 host++;
1406                 host[strlen(host)-1] = 0;
1407         }
1408
1409         /*
1410          *  just accept addresses
1411          */
1412         attr = ipattr(host);
1413         if(strcmp(attr, "ip") == 0)
1414                 return ndbnew("ip", host);
1415
1416         /*
1417          *  give the domain name server the first opportunity to
1418          *  resolve domain names.  if that fails try the database.
1419          */
1420         t = 0;
1421         werrstr("can't translate address");
1422         if(strcmp(attr, "dom") == 0)
1423                 t = dnsiplookup(host, &s);
1424         if(t == 0)
1425                 free(ndbgetvalue(db, &s, attr, host, "ip", &t));
1426         if(t == 0){
1427                 dnsname = ndbgetvalue(db, &s, attr, host, "dom", NULL);
1428                 if(dnsname){
1429                         t = dnsiplookup(dnsname, &s);
1430                         free(dnsname);
1431                 }
1432         }
1433         if(t == 0)
1434                 t = dnsiplookup(host, &s);
1435         if(t == 0)
1436                 return 0;
1437
1438         /*
1439          *  reorder the tuple to have the matched line first and
1440          *  save that in the request structure.
1441          */
1442         t = reorder(t, s.t);
1443
1444         /*
1445          * reorder according to our interfaces
1446          */
1447         //lock(&ipifclock);
1448         for(ifc = ipifcs; ifc != NULL; ifc = ifc->next){
1449                 for(lifc = ifc->lifc; lifc != NULL; lifc = lifc->next){
1450                         maskip(lifc->ip, lifc->mask, net);
1451                         for(nt = t; nt; nt = nt->entry){
1452                                 if(strcmp(nt->attr, "ip") != 0)
1453                                         continue;
1454                                 parseip(ip, nt->val);
1455                                 maskip(ip, lifc->mask, tnet);
1456                                 if(memcmp(net, tnet, IPaddrlen) == 0){
1457                                         t = reorder(t, nt);
1458                                         //unlock(&ipifclock);
1459                                         return t;
1460                                 }
1461                         }
1462                 }
1463         }
1464         //unlock(&ipifclock);
1465
1466         return t;
1467 }
1468
1469 /*
1470  *  translate an ip address
1471  */
1472 char*
1473 iptrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int hack)
1474 {
1475         char ts[Maxservice];
1476         char reply[Maxreply];
1477         char x[Maxservice];
1478
1479         if(strcmp(t->attr, "ip") != 0)
1480                 return 0;
1481
1482         if(serv == 0 || ipserv(np, serv, ts, sizeof ts) == 0){
1483                 werrstr("can't translate service");
1484                 return 0;
1485         }
1486         if(rem != NULL)
1487                 snprintf(x, sizeof(x), "!%s", rem);
1488         else
1489                 *x = 0;
1490
1491         if(*t->val == '*')
1492                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s",
1493                         mntpt, np->net, ts, x);
1494         else
1495                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s%s",
1496                         mntpt, np->net, t->val, ts, x, hack? "!fasttimeout": "");
1497
1498         return strdup(reply);
1499 }
1500
1501 /*
1502  *  lookup a telephone number
1503  */
1504 struct ndbtuple*
1505 telcolookup(Network *np, char *host, char *serv, int nolookup)
1506 {
1507         struct ndbtuple *t;
1508         struct ndbs s;
1509
1510         werrstr("can't translate address");
1511         free(ndbgetvalue(db, &s, "sys", host, "telco", &t));
1512         if(t == 0)
1513                 return ndbnew("telco", host);
1514
1515         return reorder(t, s.t);
1516 }
1517
1518 /*
1519  *  translate a telephone address
1520  */
1521 char*
1522 telcotrans(struct ndbtuple *t, Network *np, char *serv, char *rem, int unused)
1523 {
1524         char reply[Maxreply];
1525         char x[Maxservice];
1526
1527         if(strcmp(t->attr, "telco") != 0)
1528                 return 0;
1529
1530         if(rem != NULL)
1531                 snprintf(x, sizeof(x), "!%s", rem);
1532         else
1533                 *x = 0;
1534         if(serv)
1535                 snprintf(reply, sizeof(reply), "%s/%s/clone %s!%s%s", mntpt, np->net,
1536                         t->val, serv, x);
1537         else
1538                 snprintf(reply, sizeof(reply), "%s/%s/clone %s%s", mntpt, np->net,
1539                         t->val, x);
1540         return strdup(reply);
1541 }
1542
1543 /*
1544  *  reorder the tuple to put x's line first in the entry
1545  */
1546 struct ndbtuple*
1547 reorder(struct ndbtuple *t, struct ndbtuple *x)
1548 {
1549         struct ndbtuple *nt;
1550         struct ndbtuple *line;
1551
1552         /* find start of this entry's line */
1553         for(line = x; line->entry == line->line; line = line->line)
1554                 ;
1555         line = line->line;
1556         if(line == t)
1557                 return t;       /* already the first line */
1558
1559         /* remove this line and everything after it from the entry */
1560         for(nt = t; nt->entry != line; nt = nt->entry)
1561                 ;
1562         nt->entry = 0;
1563
1564         /* make that the start of the entry */
1565         for(nt = line; nt->entry; nt = nt->entry)
1566                 ;
1567         nt->entry = t;
1568         return line;
1569 }
1570
1571 static struct ndbtuple*
1572 dnsip6lookup(char *mntpt, char *buf, struct ndbtuple *t)
1573 {
1574         struct ndbtuple *t6, *tt;
1575
1576         t6 = dnsquery(mntpt, buf, "ipv6");      /* lookup AAAA dns RRs */
1577         if (t6 == NULL)
1578                 return t;
1579
1580         /* convert ipv6 attr to ip */
1581         for (tt = t6; tt != NULL; tt = tt->entry)
1582                 if (strcmp(tt->attr, "ipv6") == 0)
1583                         strncpy(tt->attr, "ip", sizeof tt->attr - 1);
1584
1585         if (t == NULL)
1586                 return t6;
1587
1588         /* append t6 list to t list */
1589         for (tt = t; tt->entry != NULL; tt = tt->entry)
1590                 ;
1591         tt->entry = t6;
1592         return t;
1593 }
1594
1595 /*
1596  *  call the dns process and have it try to translate a name
1597  */
1598 struct ndbtuple*
1599 dnsiplookup(char *host, struct ndbs *s)
1600 {
1601         char buf[Maxreply];
1602         struct ndbtuple *t;
1603
1604         //unlock(&dblock);
1605
1606         /* save the name */
1607         snprintf(buf, sizeof(buf), "%s", host);
1608
1609         if(strcmp(ipattr(buf), "ip") == 0)
1610                 t = dnsquery(mntpt, buf, "ptr");
1611         else {
1612                 t = dnsquery(mntpt, buf, "ip");
1613                 /* special case: query ipv6 (AAAA dns RR) too */
1614                 if (ipv6lookups)
1615                         t = dnsip6lookup(mntpt, buf, t);
1616         }
1617         s->t = t;
1618
1619         if(t == NULL){
1620                 snprintf(buf, sizeof buf, "%r");
1621                 if(strstr(buf, "exist"))
1622                         werrstr("can't translate address: %s", buf);
1623                 else if(strstr(buf, "dns failure"))
1624                         werrstr("temporary problem: %s", buf);
1625         }
1626
1627         //lock(&dblock);
1628         return t;
1629 }
1630
1631 int
1632 qmatch(struct ndbtuple *t, char **attr, char **val, int n)
1633 {
1634         int i, found;
1635         struct ndbtuple *nt;
1636
1637         for(i = 1; i < n; i++){
1638                 found = 0;
1639                 for(nt = t; nt; nt = nt->entry)
1640                         if(strcmp(attr[i], nt->attr) == 0)
1641                                 if(strcmp(val[i], "*") == 0
1642                                 || strcmp(val[i], nt->val) == 0){
1643                                         found = 1;
1644                                         break;
1645                                 }
1646                 if(found == 0)
1647                         break;
1648         }
1649         return i == n;
1650 }
1651
1652 /* this is awful but I don't want to bring in libstring just for this.
1653  * you want real strings don't use C
1654  */
1655 void
1656 qreply(Mfile *mf, struct ndbtuple *t)
1657 {
1658         struct ndbtuple *nt;
1659         char *s, *cur;
1660         int len, amt;
1661
1662         s = malloc(4096);
1663         cur = s;
1664         len = 4096;
1665
1666         for(nt = t; mf->nreply < Nreply && nt; nt = nt->entry){
1667                 amt = snprintf(cur, len, "%s=%s", nt->attr, nt->val);
1668
1669                 if (amt < 0)
1670                         len = 0;
1671                 else {
1672                         len -= amt;
1673                         cur += amt;
1674                 }
1675
1676                 if(nt->line != nt->entry){
1677                         mf->replylen[mf->nreply] = strlen(s);
1678                         mf->reply[mf->nreply++] = strdup(s);
1679                         cur = s;
1680                         len = 4096;
1681                 } else {
1682                         amt = snprintf(cur, len, " ");
1683                         if (amt < 0)
1684                                 len = 0;
1685                         else {
1686                                 len -= amt;
1687                                 cur += amt;
1688                         }
1689                 }
1690
1691         }
1692         free(s);
1693 }
1694
1695 enum
1696 {
1697         Maxattr=        32,
1698 };
1699
1700 /*
1701  *  generic query lookup.  The query is of one of the following
1702  *  forms:
1703  *
1704  *  attr1=val1 attr2=val2 attr3=val3 ...
1705  *
1706  *  returns the matching tuple
1707  *
1708  *  ipinfo attr=val attr1 attr2 attr3 ...
1709  *
1710  *  is like ipinfo and returns the attr{1-n}
1711  *  associated with the ip address.
1712  */
1713 char*
1714 genquery(Mfile *mf, char *query)
1715 {
1716         int i, n;
1717         char *p;
1718         char *attr[Maxattr];
1719         char *val[Maxattr];
1720         struct ndbtuple *t;
1721         struct ndbs s;
1722
1723         n = getfields(query, attr, ARRAY_SIZE(attr), 1, " ");
1724         if(n == 0)
1725                 return "bad query";
1726
1727         if(strcmp(attr[0], "ipinfo") == 0)
1728                 return ipinfoquery(mf, attr, n);
1729
1730         /* parse pairs */
1731         for(i = 0; i < n; i++){
1732                 p = strchr(attr[i], '=');
1733                 if(p == 0)
1734                         return "bad query";
1735                 *p++ = 0;
1736                 val[i] = p;
1737         }
1738
1739         /* give dns a chance */
1740         if((strcmp(attr[0], "dom") == 0 || strcmp(attr[0], "ip") == 0) && val[0]){
1741                 t = dnsiplookup(val[0], &s);
1742                 if(t){
1743                         if(qmatch(t, attr, val, n)){
1744                                 qreply(mf, t);
1745                                 ndbfree(t);
1746                                 return 0;
1747                         }
1748                         ndbfree(t);
1749                 }
1750         }
1751
1752         /* first pair is always the key.  It can't be a '*' */
1753         t = ndbsearch(db, &s, attr[0], val[0]);
1754
1755         /* search is the and of all the pairs */
1756         while(t){
1757                 if(qmatch(t, attr, val, n)){
1758                         qreply(mf, t);
1759                         ndbfree(t);
1760                         return 0;
1761                 }
1762
1763                 ndbfree(t);
1764                 t = ndbsnext(&s, attr[0], val[0]);
1765         }
1766
1767         return "no match";
1768 }
1769
1770 /*
1771  *  resolve an ip address
1772  */
1773 static struct ndbtuple*
1774 ipresolve(char *attr, char *host)
1775 {
1776         struct ndbtuple *t, *nt, **l;
1777
1778         t = iplookup(&network[Ntcp], host, "*", 0);
1779         for(l = &t; *l != NULL; ){
1780                 nt = *l;
1781                 if(strcmp(nt->attr, "ip") != 0){
1782                         *l = nt->entry;
1783                         nt->entry = NULL;
1784                         ndbfree(nt);
1785                         continue;
1786                 }
1787                 strcpy(nt->attr, attr);
1788                 l = &nt->entry;
1789         }
1790         return t;
1791 }
1792
1793 char*
1794 ipinfoquery(Mfile *mf, char **list, int n)
1795 {
1796         int i, nresolve;
1797         int resolve[Maxattr];
1798         struct ndbtuple *t, *nt, **l;
1799         char *attr, *val;
1800
1801         /* skip 'ipinfo' */
1802         list++; n--;
1803
1804         if(n < 1)
1805                 return "bad query";
1806
1807         /* get search attribute=value, or assume ip=myipaddr */
1808         attr = *list;
1809         if((val = strchr(attr, '=')) != NULL){
1810                 *val++ = 0;
1811                 list++;
1812                 n--;
1813         }else{
1814                 attr = "ip";
1815                 val = ipaddr;
1816         }
1817
1818         if(n < 1)
1819                 return "bad query";
1820
1821         /*
1822          *  don't let ndbipinfo resolve the addresses, we're
1823          *  better at it.
1824          */
1825         nresolve = 0;
1826         for(i = 0; i < n; i++)
1827                 if(*list[i] == '@'){            /* @attr=val ? */
1828                         list[i]++;
1829                         resolve[i] = 1;         /* we'll resolve it */
1830                         nresolve++;
1831                 } else
1832                         resolve[i] = 0;
1833
1834         t = ndbipinfo(db, attr, val, list, n);
1835         if(t == NULL)
1836                 return "no match";
1837
1838         if(nresolve != 0){
1839                 for(l = &t; *l != NULL;){
1840                         nt = *l;
1841
1842                         /* already an address? */
1843                         if(strcmp(ipattr(nt->val), "ip") == 0){
1844                                 l = &(*l)->entry;
1845                                 continue;
1846                         }
1847
1848                         /* user wants it resolved? */
1849                         for(i = 0; i < n; i++)
1850                                 if(strcmp(list[i], nt->attr) == 0)
1851                                         break;
1852                         if(i >= n || resolve[i] == 0){
1853                                 l = &(*l)->entry;
1854                                 continue;
1855                         }
1856
1857                         /* resolve address and replace entry */
1858                         *l = ipresolve(nt->attr, nt->val);
1859                         while(*l != NULL)
1860                                 l = &(*l)->entry;
1861                         *l = nt->entry;
1862
1863                         nt->entry = NULL;
1864                         ndbfree(nt);
1865                 }
1866         }
1867
1868         /* make it all one line */
1869         for(nt = t; nt != NULL; nt = nt->entry){
1870                 if(nt->entry == NULL)
1871                         nt->line = t;
1872                 else
1873                         nt->line = nt->entry;
1874         }
1875
1876         qreply(mf, t);
1877
1878         return NULL;
1879 }
1880
1881 void*
1882 emalloc(int size)
1883 {
1884         void *x;
1885
1886         x = calloc(size, 1);
1887         if(x == NULL)
1888                 abort();
1889         memset(x, 0, size);
1890         return x;
1891 }
1892
1893 char*
1894 estrdup(char *s)
1895 {
1896         int size;
1897         char *p;
1898
1899         size = strlen(s)+1;
1900         p = calloc(size, 1);
1901         if(p == NULL)
1902                 abort();
1903         memmove(p, s, size);
1904         return p;
1905 }