d7bd7b49a0bd0567e42b3f1a8fa6282c58130db9
[samba.git] / source3 / libsmb / nmblib.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    NBT netbios library routines
5    Copyright (C) Andrew Tridgell 1994-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20    
21 */
22
23 #include "includes.h"
24
25 int num_good_sends = 0;
26 int num_good_receives = 0;
27
28 static struct opcode_names {
29         char *nmb_opcode_name;
30         int opcode;
31 } nmb_header_opcode_names[] = {
32       {"Query",           0 },
33       {"Registration",      5 },
34       {"Release",           6 },
35       {"WACK",              7 },
36       {"Refresh",           8 },
37       {"Refresh(altcode)",  9 },
38       {"Multi-homed Registration", 15 },
39       {0, -1 }
40 };
41
42 /****************************************************************************
43  * Lookup a nmb opcode name.
44  ****************************************************************************/
45 static char *lookup_opcode_name( int opcode )
46 {
47   struct opcode_names *op_namep;
48   int i;
49
50   for(i = 0; nmb_header_opcode_names[i].nmb_opcode_name != 0; i++) {
51     op_namep = &nmb_header_opcode_names[i];
52     if(opcode == op_namep->opcode)
53       return op_namep->nmb_opcode_name;
54   }
55   return "<unknown opcode>";
56 }
57
58 /****************************************************************************
59   print out a res_rec structure
60   ****************************************************************************/
61 static void debug_nmb_res_rec(struct res_rec *res, char *hdr)
62 {
63   int i, j;
64
65   DEBUGADD( 4, ( "    %s: nmb_name=%s rr_type=%d rr_class=%d ttl=%d\n",
66                  hdr,
67                  nmb_namestr(&res->rr_name),
68                  res->rr_type,
69                  res->rr_class,
70                  res->ttl ) );
71
72   if( res->rdlength == 0 || res->rdata == NULL )
73     return;
74
75   for (i = 0; i < res->rdlength; i+= 16)
76     {
77       DEBUGADD(4, ("    %s %3x char ", hdr, i));
78
79       for (j = 0; j < 16; j++)
80         {
81           uchar x = res->rdata[i+j];
82           if (x < 32 || x > 127) x = '.';
83           
84           if (i+j >= res->rdlength) break;
85           DEBUGADD(4, ("%c", x));
86         }
87       
88       DEBUGADD(4, ("   hex "));
89
90       for (j = 0; j < 16; j++)
91         {
92           if (i+j >= res->rdlength) break;
93           DEBUGADD(4, ("%02X", (uchar)res->rdata[i+j]));
94         }
95       
96       DEBUGADD(4, ("\n"));
97     }
98 }
99
100 /****************************************************************************
101   process a nmb packet
102   ****************************************************************************/
103 void debug_nmb_packet(struct packet_struct *p)
104 {
105   struct nmb_packet *nmb = &p->packet.nmb;
106
107   if( DEBUGLVL( 4 ) )
108     {
109     dbgtext( "nmb packet from %s(%d) header: id=%d opcode=%s(%d) response=%s\n",
110              inet_ntoa(p->ip), p->port,
111              nmb->header.name_trn_id,
112              lookup_opcode_name(nmb->header.opcode),
113              nmb->header.opcode,
114              BOOLSTR(nmb->header.response) );
115     dbgtext( "    header: flags: bcast=%s rec_avail=%s rec_des=%s trunc=%s auth=%s\n",
116              BOOLSTR(nmb->header.nm_flags.bcast),
117              BOOLSTR(nmb->header.nm_flags.recursion_available),
118              BOOLSTR(nmb->header.nm_flags.recursion_desired),
119              BOOLSTR(nmb->header.nm_flags.trunc),
120              BOOLSTR(nmb->header.nm_flags.authoritative) );
121     dbgtext( "    header: rcode=%d qdcount=%d ancount=%d nscount=%d arcount=%d\n",
122              nmb->header.rcode,
123              nmb->header.qdcount,
124              nmb->header.ancount,
125              nmb->header.nscount,
126              nmb->header.arcount );
127     }
128
129   if (nmb->header.qdcount)
130     {
131       DEBUGADD( 4, ( "    question: q_name=%s q_type=%d q_class=%d\n",
132                      nmb_namestr(&nmb->question.question_name),
133                      nmb->question.question_type,
134                      nmb->question.question_class) );
135     }
136
137   if (nmb->answers && nmb->header.ancount)
138     {
139       debug_nmb_res_rec(nmb->answers,"answers");
140     }
141   if (nmb->nsrecs && nmb->header.nscount)
142     {
143       debug_nmb_res_rec(nmb->nsrecs,"nsrecs");
144     }
145   if (nmb->additional && nmb->header.arcount)
146     {
147       debug_nmb_res_rec(nmb->additional,"additional");
148     }
149 }
150
151 /*******************************************************************
152   handle "compressed" name pointers
153   ******************************************************************/
154 static BOOL handle_name_ptrs(uchar *ubuf,int *offset,int length,
155                              BOOL *got_pointer,int *ret)
156 {
157   int loop_count=0;
158   
159   while ((ubuf[*offset] & 0xC0) == 0xC0) {
160     if (!*got_pointer) (*ret) += 2;
161     (*got_pointer)=True;
162     (*offset) = ((ubuf[*offset] & ~0xC0)<<8) | ubuf[(*offset)+1];
163     if (loop_count++ == 10 || (*offset) < 0 || (*offset)>(length-2)) {
164       return(False);
165     }
166   }
167   return(True);
168 }
169
170 /*******************************************************************
171   parse a nmb name from "compressed" format to something readable
172   return the space taken by the name, or 0 if the name is invalid
173   ******************************************************************/
174 static int parse_nmb_name(char *inbuf,int offset,int length, struct nmb_name *name)
175 {
176   int m,n=0;
177   uchar *ubuf = (uchar *)inbuf;
178   int ret = 0;
179   BOOL got_pointer=False;
180   int loop_count=0;
181
182   if (length - offset < 2)
183     return(0);  
184
185   /* handle initial name pointers */
186   if (!handle_name_ptrs(ubuf,&offset,length,&got_pointer,&ret))
187     return(0);
188   
189   m = ubuf[offset];
190
191   if (!m)
192     return(0);
193   if ((m & 0xC0) || offset+m+2 > length)
194     return(0);
195
196   memset((char *)name,'\0',sizeof(*name));
197
198   /* the "compressed" part */
199   if (!got_pointer)
200     ret += m + 2;
201   offset++;
202   while (m > 0) {
203     uchar c1,c2;
204     c1 = ubuf[offset++]-'A';
205     c2 = ubuf[offset++]-'A';
206     if ((c1 & 0xF0) || (c2 & 0xF0) || (n > sizeof(name->name)-1))
207       return(0);
208     name->name[n++] = (c1<<4) | c2;
209     m -= 2;
210   }
211   name->name[n] = 0;
212
213   if (n==16) {
214     /* parse out the name type, 
215        its always in the 16th byte of the name */
216     name->name_type = ((uchar)name->name[15]) & 0xff;
217   
218     /* remove trailing spaces */
219     name->name[15] = 0;
220     n = 14;
221     while (n && name->name[n]==' ')
222       name->name[n--] = 0;  
223   }
224
225   /* now the domain parts (if any) */
226   n = 0;
227   while (ubuf[offset]) {
228     /* we can have pointers within the domain part as well */
229     if (!handle_name_ptrs(ubuf,&offset,length,&got_pointer,&ret))
230       return(0);
231
232     m = ubuf[offset];
233     /*
234      * Don't allow null domain parts.
235      */
236     if (!m)
237       return(0);
238     if (!got_pointer)
239       ret += m+1;
240     if (n)
241       name->scope[n++] = '.';
242     if (m+2+offset>length || n+m+1>sizeof(name->scope))
243       return(0);
244     offset++;
245     while (m--)
246       name->scope[n++] = (char)ubuf[offset++];
247
248     /*
249      * Watch for malicious loops.
250      */
251     if (loop_count++ == 10)
252       return 0;
253   }
254   name->scope[n++] = 0;  
255
256   return(ret);
257 }
258
259
260 /*******************************************************************
261   put a compressed nmb name into a buffer. return the length of the
262   compressed name
263
264   compressed names are really weird. The "compression" doubles the
265   size. The idea is that it also means that compressed names conform
266   to the doman name system. See RFC1002.
267   ******************************************************************/
268 static int put_nmb_name(char *buf,int offset,struct nmb_name *name)
269 {
270   int ret,m;
271   fstring buf1;
272   char *p;
273
274   if (strcmp(name->name,"*") == 0) {
275     /* special case for wildcard name */
276     memset(buf1,'\0',20);
277     buf1[0] = '*';
278     buf1[15] = name->name_type;
279   } else {
280     slprintf(buf1, sizeof(buf1) - 1,"%-15.15s%c",name->name,name->name_type);
281   }
282
283   buf[offset] = 0x20;
284
285   ret = 34;
286
287   for (m=0;m<16;m++) {
288     buf[offset+1+2*m] = 'A' + ((buf1[m]>>4)&0xF);
289     buf[offset+2+2*m] = 'A' + (buf1[m]&0xF);
290   }
291   offset += 33;
292
293   buf[offset] = 0;
294
295   if (name->scope[0]) {
296     /* XXXX this scope handling needs testing */
297     ret += strlen(name->scope) + 1;
298     pstrcpy(&buf[offset+1],name->scope);  
299   
300     p = &buf[offset+1];
301     while ((p = strchr_m(p,'.'))) {
302       buf[offset] = PTR_DIFF(p,&buf[offset+1]);
303       offset += (buf[offset] + 1);
304       p = &buf[offset+1];
305     }
306     buf[offset] = strlen(&buf[offset+1]);
307   }
308
309   return(ret);
310 }
311
312 /*******************************************************************
313   useful for debugging messages
314   ******************************************************************/
315 char *nmb_namestr(struct nmb_name *n)
316 {
317   static int i=0;
318   static fstring ret[4];
319   char *p = ret[i];
320
321   if (!n->scope[0])
322     slprintf(p,sizeof(fstring)-1, "%s<%02x>",n->name,n->name_type);
323   else
324     slprintf(p,sizeof(fstring)-1, "%s<%02x>.%s",n->name,n->name_type,n->scope);
325
326   i = (i+1)%4;
327   return(p);
328 }
329
330 /*******************************************************************
331   allocate and parse some resource records
332   ******************************************************************/
333 static BOOL parse_alloc_res_rec(char *inbuf,int *offset,int length,
334                                 struct res_rec **recs, int count)
335 {
336   int i;
337   *recs = (struct res_rec *)malloc(sizeof(**recs)*count);
338   if (!*recs) return(False);
339
340   memset((char *)*recs,'\0',sizeof(**recs)*count);
341
342   for (i=0;i<count;i++) {
343     int l = parse_nmb_name(inbuf,*offset,length,&(*recs)[i].rr_name);
344     (*offset) += l;
345     if (!l || (*offset)+10 > length) {
346       SAFE_FREE(*recs);
347       return(False);
348     }
349     (*recs)[i].rr_type = RSVAL(inbuf,(*offset));
350     (*recs)[i].rr_class = RSVAL(inbuf,(*offset)+2);
351     (*recs)[i].ttl = RIVAL(inbuf,(*offset)+4);
352     (*recs)[i].rdlength = RSVAL(inbuf,(*offset)+8);
353     (*offset) += 10;
354     if ((*recs)[i].rdlength>sizeof((*recs)[i].rdata) || 
355         (*offset)+(*recs)[i].rdlength > length) {
356       SAFE_FREE(*recs);
357       return(False);
358     }
359     memcpy((*recs)[i].rdata,inbuf+(*offset),(*recs)[i].rdlength);
360     (*offset) += (*recs)[i].rdlength;    
361   }
362   return(True);
363 }
364
365 /*******************************************************************
366   put a resource record into a packet
367   ******************************************************************/
368 static int put_res_rec(char *buf,int offset,struct res_rec *recs,int count)
369 {
370   int ret=0;
371   int i;
372
373   for (i=0;i<count;i++) {
374     int l = put_nmb_name(buf,offset,&recs[i].rr_name);
375     offset += l;
376     ret += l;
377     RSSVAL(buf,offset,recs[i].rr_type);
378     RSSVAL(buf,offset+2,recs[i].rr_class);
379     RSIVAL(buf,offset+4,recs[i].ttl);
380     RSSVAL(buf,offset+8,recs[i].rdlength);
381     memcpy(buf+offset+10,recs[i].rdata,recs[i].rdlength);
382     offset += 10+recs[i].rdlength;
383     ret += 10+recs[i].rdlength;
384   }
385
386   return(ret);
387 }
388
389 /*******************************************************************
390   put a compressed name pointer record into a packet
391   ******************************************************************/
392 static int put_compressed_name_ptr(uchar *buf,int offset,struct res_rec *rec,int ptr_offset)
393 {  
394   int ret=0;
395   buf[offset] = (0xC0 | ((ptr_offset >> 8) & 0xFF));
396   buf[offset+1] = (ptr_offset & 0xFF);
397   offset += 2;
398   ret += 2;
399   RSSVAL(buf,offset,rec->rr_type);
400   RSSVAL(buf,offset+2,rec->rr_class);
401   RSIVAL(buf,offset+4,rec->ttl);
402   RSSVAL(buf,offset+8,rec->rdlength);
403   memcpy(buf+offset+10,rec->rdata,rec->rdlength);
404   offset += 10+rec->rdlength;
405   ret += 10+rec->rdlength;
406     
407   return(ret);
408 }
409
410 /*******************************************************************
411   parse a dgram packet. Return False if the packet can't be parsed 
412   or is invalid for some reason, True otherwise 
413
414   this is documented in section 4.4.1 of RFC1002
415   ******************************************************************/
416 static BOOL parse_dgram(char *inbuf,int length,struct dgram_packet *dgram)
417 {
418   int offset;
419   int flags;
420
421   memset((char *)dgram,'\0',sizeof(*dgram));
422
423   if (length < 14) return(False);
424
425   dgram->header.msg_type = CVAL(inbuf,0);
426   flags = CVAL(inbuf,1);
427   dgram->header.flags.node_type = (enum node_type)((flags>>2)&3);
428   if (flags & 1) dgram->header.flags.more = True;
429   if (flags & 2) dgram->header.flags.first = True;
430   dgram->header.dgm_id = RSVAL(inbuf,2);
431   putip((char *)&dgram->header.source_ip,inbuf+4);
432   dgram->header.source_port = RSVAL(inbuf,8);
433   dgram->header.dgm_length = RSVAL(inbuf,10);
434   dgram->header.packet_offset = RSVAL(inbuf,12);
435
436   offset = 14;
437
438   if (dgram->header.msg_type == 0x10 ||
439       dgram->header.msg_type == 0x11 ||
440       dgram->header.msg_type == 0x12) {      
441     offset += parse_nmb_name(inbuf,offset,length,&dgram->source_name);
442     offset += parse_nmb_name(inbuf,offset,length,&dgram->dest_name);
443   }
444
445   if (offset >= length || (length-offset > sizeof(dgram->data))) 
446     return(False);
447
448   dgram->datasize = length-offset;
449   memcpy(dgram->data,inbuf+offset,dgram->datasize);
450
451   return(True);
452 }
453
454
455 /*******************************************************************
456   parse a nmb packet. Return False if the packet can't be parsed 
457   or is invalid for some reason, True otherwise 
458   ******************************************************************/
459 static BOOL parse_nmb(char *inbuf,int length,struct nmb_packet *nmb)
460 {
461   int nm_flags,offset;
462
463   memset((char *)nmb,'\0',sizeof(*nmb));
464
465   if (length < 12) return(False);
466
467   /* parse the header */
468   nmb->header.name_trn_id = RSVAL(inbuf,0);
469
470   DEBUG(10,("parse_nmb: packet id = %d\n", nmb->header.name_trn_id));
471
472   nmb->header.opcode = (CVAL(inbuf,2) >> 3) & 0xF;
473   nmb->header.response = ((CVAL(inbuf,2)>>7)&1)?True:False;
474   nm_flags = ((CVAL(inbuf,2) & 0x7) << 4) + (CVAL(inbuf,3)>>4);
475   nmb->header.nm_flags.bcast = (nm_flags&1)?True:False;
476   nmb->header.nm_flags.recursion_available = (nm_flags&8)?True:False;
477   nmb->header.nm_flags.recursion_desired = (nm_flags&0x10)?True:False;
478   nmb->header.nm_flags.trunc = (nm_flags&0x20)?True:False;
479   nmb->header.nm_flags.authoritative = (nm_flags&0x40)?True:False;  
480   nmb->header.rcode = CVAL(inbuf,3) & 0xF;
481   nmb->header.qdcount = RSVAL(inbuf,4);
482   nmb->header.ancount = RSVAL(inbuf,6);
483   nmb->header.nscount = RSVAL(inbuf,8);
484   nmb->header.arcount = RSVAL(inbuf,10);
485   
486   if (nmb->header.qdcount) {
487     offset = parse_nmb_name(inbuf,12,length,&nmb->question.question_name);
488     if (!offset) return(False);
489
490     if (length - (12+offset) < 4) return(False);
491     nmb->question.question_type = RSVAL(inbuf,12+offset);
492     nmb->question.question_class = RSVAL(inbuf,12+offset+2);
493
494     offset += 12+4;
495   } else {
496     offset = 12;
497   }
498
499   /* and any resource records */
500   if (nmb->header.ancount && 
501       !parse_alloc_res_rec(inbuf,&offset,length,&nmb->answers,
502                            nmb->header.ancount))
503     return(False);
504
505   if (nmb->header.nscount && 
506       !parse_alloc_res_rec(inbuf,&offset,length,&nmb->nsrecs,
507                            nmb->header.nscount))
508     return(False);
509   
510   if (nmb->header.arcount && 
511       !parse_alloc_res_rec(inbuf,&offset,length,&nmb->additional,
512                            nmb->header.arcount))
513     return(False);
514
515   return(True);
516 }
517
518 /*******************************************************************
519   'Copy constructor' for an nmb packet
520   ******************************************************************/
521 static struct packet_struct *copy_nmb_packet(struct packet_struct *packet)
522 {  
523   struct nmb_packet *nmb;
524   struct nmb_packet *copy_nmb;
525   struct packet_struct *pkt_copy;
526
527   if(( pkt_copy = (struct packet_struct *)malloc(sizeof(*packet))) == NULL)
528   {
529     DEBUG(0,("copy_nmb_packet: malloc fail.\n"));
530     return NULL;
531   }
532
533   /* Structure copy of entire thing. */
534
535   *pkt_copy = *packet;
536
537   /* Ensure this copy is not locked. */
538   pkt_copy->locked = False;
539
540   /* Ensure this copy has no resource records. */
541   nmb = &packet->packet.nmb;
542   copy_nmb = &pkt_copy->packet.nmb;
543
544   copy_nmb->answers = NULL;
545   copy_nmb->nsrecs = NULL;
546   copy_nmb->additional = NULL;
547
548   /* Now copy any resource records. */
549
550   if (nmb->answers)
551   {
552     if((copy_nmb->answers = (struct res_rec *)
553                   malloc(nmb->header.ancount * sizeof(struct res_rec))) == NULL)
554       goto free_and_exit;
555     memcpy((char *)copy_nmb->answers, (char *)nmb->answers, 
556            nmb->header.ancount * sizeof(struct res_rec));
557   }
558   if (nmb->nsrecs)
559   {
560     if((copy_nmb->nsrecs = (struct res_rec *)
561                   malloc(nmb->header.nscount * sizeof(struct res_rec))) == NULL)
562       goto free_and_exit;
563     memcpy((char *)copy_nmb->nsrecs, (char *)nmb->nsrecs, 
564            nmb->header.nscount * sizeof(struct res_rec));
565   }
566   if (nmb->additional)
567   {
568     if((copy_nmb->additional = (struct res_rec *)
569                   malloc(nmb->header.arcount * sizeof(struct res_rec))) == NULL)
570       goto free_and_exit;
571     memcpy((char *)copy_nmb->additional, (char *)nmb->additional, 
572            nmb->header.arcount * sizeof(struct res_rec));
573   }
574
575   return pkt_copy;
576
577 free_and_exit:
578
579   SAFE_FREE(copy_nmb->answers);
580   SAFE_FREE(copy_nmb->nsrecs);
581   SAFE_FREE(copy_nmb->additional);
582   SAFE_FREE(pkt_copy);
583
584   DEBUG(0,("copy_nmb_packet: malloc fail in resource records.\n"));
585   return NULL;
586 }
587
588 /*******************************************************************
589   'Copy constructor' for a dgram packet
590   ******************************************************************/
591 static struct packet_struct *copy_dgram_packet(struct packet_struct *packet)
592
593   struct packet_struct *pkt_copy;
594
595   if(( pkt_copy = (struct packet_struct *)malloc(sizeof(*packet))) == NULL)
596   {
597     DEBUG(0,("copy_dgram_packet: malloc fail.\n"));
598     return NULL;
599   }
600
601   /* Structure copy of entire thing. */
602
603   *pkt_copy = *packet;
604
605   /* Ensure this copy is not locked. */
606   pkt_copy->locked = False;
607
608   /* There are no additional pointers in a dgram packet,
609      we are finished. */
610   return pkt_copy;
611 }
612
613 /*******************************************************************
614   'Copy constructor' for a generic packet
615   ******************************************************************/
616 struct packet_struct *copy_packet(struct packet_struct *packet)
617 {  
618   if(packet->packet_type == NMB_PACKET)
619     return copy_nmb_packet(packet);
620   else if (packet->packet_type == DGRAM_PACKET)
621     return copy_dgram_packet(packet);
622   return NULL;
623 }
624  
625 /*******************************************************************
626   free up any resources associated with an nmb packet
627   ******************************************************************/
628 static void free_nmb_packet(struct nmb_packet *nmb)
629 {  
630   SAFE_FREE(nmb->answers);
631   SAFE_FREE(nmb->nsrecs);
632   SAFE_FREE(nmb->additional);
633 }
634
635 /*******************************************************************
636   free up any resources associated with a dgram packet
637   ******************************************************************/
638 static void free_dgram_packet(struct dgram_packet *nmb)
639 {  
640   /* We have nothing to do for a dgram packet. */
641 }
642
643 /*******************************************************************
644   free up any resources associated with a packet
645   ******************************************************************/
646 void free_packet(struct packet_struct *packet)
647 {  
648   if (packet->locked) 
649     return;
650   if (packet->packet_type == NMB_PACKET)
651     free_nmb_packet(&packet->packet.nmb);
652   else if (packet->packet_type == DGRAM_PACKET)
653     free_dgram_packet(&packet->packet.dgram);
654   ZERO_STRUCTPN(packet);
655   SAFE_FREE(packet);
656 }
657
658 /*******************************************************************
659 parse a packet buffer into a packet structure
660   ******************************************************************/
661 struct packet_struct *parse_packet(char *buf,int length,
662                                    enum packet_type packet_type)
663 {
664         extern struct in_addr lastip;
665         extern int lastport;
666         struct packet_struct *p;
667         BOOL ok=False;
668
669         p = (struct packet_struct *)malloc(sizeof(*p));
670         if (!p) return(NULL);
671
672         p->next = NULL;
673         p->prev = NULL;
674         p->ip = lastip;
675         p->port = lastport;
676         p->locked = False;
677         p->timestamp = time(NULL);
678         p->packet_type = packet_type;
679
680         switch (packet_type) {
681         case NMB_PACKET:
682                 ok = parse_nmb(buf,length,&p->packet.nmb);
683                 break;
684                 
685         case DGRAM_PACKET:
686                 ok = parse_dgram(buf,length,&p->packet.dgram);
687                 break;
688         }
689
690         if (!ok) {
691                 free_packet(p);
692                 return NULL;
693         }
694
695         return p;
696 }
697
698 /*******************************************************************
699   read a packet from a socket and parse it, returning a packet ready
700   to be used or put on the queue. This assumes a UDP socket
701   ******************************************************************/
702 struct packet_struct *read_packet(int fd,enum packet_type packet_type)
703 {
704         struct packet_struct *packet;
705         char buf[MAX_DGRAM_SIZE];
706         int length;
707         
708         length = read_udp_socket(fd,buf,sizeof(buf));
709         if (length < MIN_DGRAM_SIZE) return(NULL);
710         
711         packet = parse_packet(buf, length, packet_type);
712         if (!packet) return NULL;
713
714         packet->fd = fd;
715         
716         num_good_receives++;
717         
718         DEBUG(5,("Received a packet of len %d from (%s) port %d\n",
719                  length, inet_ntoa(packet->ip), packet->port ) );
720         
721         return(packet);
722 }
723                                          
724
725 /*******************************************************************
726   send a udp packet on a already open socket
727   ******************************************************************/
728 static BOOL send_udp(int fd,char *buf,int len,struct in_addr ip,int port)
729 {
730   BOOL ret = False;
731   int i;
732   struct sockaddr_in sock_out;
733
734   /* set the address and port */
735   memset((char *)&sock_out,'\0',sizeof(sock_out));
736   putip((char *)&sock_out.sin_addr,(char *)&ip);
737   sock_out.sin_port = htons( port );
738   sock_out.sin_family = AF_INET;
739   
740   DEBUG( 5, ( "Sending a packet of len %d to (%s) on port %d\n",
741               len, inet_ntoa(ip), port ) );
742
743   /*
744    * Patch to fix asynch error notifications from Linux kernel.
745    */
746         
747   for (i = 0; i < 5; i++) {
748     ret = (sendto(fd,buf,len,0,(struct sockaddr *)&sock_out, sizeof(sock_out)) >= 0);
749     if (ret || errno != ECONNREFUSED)
750       break;
751   }
752
753   if (!ret)
754     DEBUG(0,("Packet send failed to %s(%d) ERRNO=%s\n",
755              inet_ntoa(ip),port,strerror(errno)));
756
757   if (ret)
758     num_good_sends++;
759
760   return(ret);
761 }
762
763 /*******************************************************************
764   build a dgram packet ready for sending
765
766   XXXX This currently doesn't handle packets too big for one
767   datagram. It should split them and use the packet_offset, more and
768   first flags to handle the fragmentation. Yuck.
769   ******************************************************************/
770 static int build_dgram(char *buf,struct packet_struct *p)
771 {
772   struct dgram_packet *dgram = &p->packet.dgram;
773   uchar *ubuf = (uchar *)buf;
774   int offset=0;
775
776   /* put in the header */
777   ubuf[0] = dgram->header.msg_type;
778   ubuf[1] = (((int)dgram->header.flags.node_type)<<2);
779   if (dgram->header.flags.more) ubuf[1] |= 1;
780   if (dgram->header.flags.first) ubuf[1] |= 2;
781   RSSVAL(ubuf,2,dgram->header.dgm_id);
782   putip(ubuf+4,(char *)&dgram->header.source_ip);
783   RSSVAL(ubuf,8,dgram->header.source_port);
784   RSSVAL(ubuf,12,dgram->header.packet_offset);
785
786   offset = 14;
787
788   if (dgram->header.msg_type == 0x10 ||
789       dgram->header.msg_type == 0x11 ||
790       dgram->header.msg_type == 0x12) {      
791     offset += put_nmb_name((char *)ubuf,offset,&dgram->source_name);
792     offset += put_nmb_name((char *)ubuf,offset,&dgram->dest_name);
793   }
794
795   memcpy(ubuf+offset,dgram->data,dgram->datasize);
796   offset += dgram->datasize;
797
798   /* automatically set the dgm_length */
799   dgram->header.dgm_length = offset;
800   RSSVAL(ubuf,10,dgram->header.dgm_length); 
801
802   return(offset);
803 }
804
805 /*******************************************************************
806   build a nmb name
807  *******************************************************************/
808 void make_nmb_name( struct nmb_name *n, const char *name, int type)
809 {
810         extern pstring global_scope;
811         memset( (char *)n, '\0', sizeof(struct nmb_name) );
812         push_ascii(n->name, name, 16, STR_TERMINATE|STR_UPPER);
813         n->name_type = (unsigned int)type & 0xFF;
814         StrnCpy( n->scope, global_scope, 63 );
815         strupper( n->scope );
816 }
817
818 /*******************************************************************
819   Compare two nmb names
820   ******************************************************************/
821
822 BOOL nmb_name_equal(struct nmb_name *n1, struct nmb_name *n2)
823 {
824   return ((n1->name_type == n2->name_type) &&
825          strequal(n1->name ,n2->name ) &&
826          strequal(n1->scope,n2->scope));
827 }
828
829 /*******************************************************************
830   build a nmb packet ready for sending
831
832   XXXX this currently relies on not being passed something that expands
833   to a packet too big for the buffer. Eventually this should be
834   changed to set the trunc bit so the receiver can request the rest
835   via tcp (when that becomes supported)
836   ******************************************************************/
837 static int build_nmb(char *buf,struct packet_struct *p)
838 {
839   struct nmb_packet *nmb = &p->packet.nmb;
840   uchar *ubuf = (uchar *)buf;
841   int offset=0;
842
843   /* put in the header */
844   RSSVAL(ubuf,offset,nmb->header.name_trn_id);
845   ubuf[offset+2] = (nmb->header.opcode & 0xF) << 3;
846   if (nmb->header.response) ubuf[offset+2] |= (1<<7);
847   if (nmb->header.nm_flags.authoritative && 
848       nmb->header.response) ubuf[offset+2] |= 0x4;
849   if (nmb->header.nm_flags.trunc) ubuf[offset+2] |= 0x2;
850   if (nmb->header.nm_flags.recursion_desired) ubuf[offset+2] |= 0x1;
851   if (nmb->header.nm_flags.recursion_available &&
852       nmb->header.response) ubuf[offset+3] |= 0x80;
853   if (nmb->header.nm_flags.bcast) ubuf[offset+3] |= 0x10;
854   ubuf[offset+3] |= (nmb->header.rcode & 0xF);
855
856   RSSVAL(ubuf,offset+4,nmb->header.qdcount);
857   RSSVAL(ubuf,offset+6,nmb->header.ancount);
858   RSSVAL(ubuf,offset+8,nmb->header.nscount);
859   RSSVAL(ubuf,offset+10,nmb->header.arcount);
860   
861   offset += 12;
862   if (nmb->header.qdcount) {
863     /* XXXX this doesn't handle a qdcount of > 1 */
864     offset += put_nmb_name((char *)ubuf,offset,&nmb->question.question_name);
865     RSSVAL(ubuf,offset,nmb->question.question_type);
866     RSSVAL(ubuf,offset+2,nmb->question.question_class);
867     offset += 4;
868   }
869
870   if (nmb->header.ancount)
871     offset += put_res_rec((char *)ubuf,offset,nmb->answers,
872                           nmb->header.ancount);
873
874   if (nmb->header.nscount)
875     offset += put_res_rec((char *)ubuf,offset,nmb->nsrecs,
876                           nmb->header.nscount);
877
878   /*
879    * The spec says we must put compressed name pointers
880    * in the following outgoing packets :
881    * NAME_REGISTRATION_REQUEST, NAME_REFRESH_REQUEST,
882    * NAME_RELEASE_REQUEST.
883    */
884
885   if((nmb->header.response == False) &&
886      ((nmb->header.opcode == NMB_NAME_REG_OPCODE) ||
887       (nmb->header.opcode == NMB_NAME_RELEASE_OPCODE) ||
888       (nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_8) ||
889       (nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_9) ||
890       (nmb->header.opcode == NMB_NAME_MULTIHOMED_REG_OPCODE)) &&
891      (nmb->header.arcount == 1)) {
892
893     offset += put_compressed_name_ptr(ubuf,offset,nmb->additional,12);
894
895   } else if (nmb->header.arcount) {
896     offset += put_res_rec((char *)ubuf,offset,nmb->additional,
897                           nmb->header.arcount);  
898   }
899   return(offset);
900 }
901
902
903 /*******************************************************************
904 linearise a packet
905   ******************************************************************/
906 int build_packet(char *buf, struct packet_struct *p)
907 {
908         int len = 0;
909
910         switch (p->packet_type) {
911         case NMB_PACKET:
912                 len = build_nmb(buf,p);
913                 break;
914
915         case DGRAM_PACKET:
916                 len = build_dgram(buf,p);
917                 break;
918         }
919
920         return len;
921 }
922
923 /*******************************************************************
924   send a packet_struct
925   ******************************************************************/
926 BOOL send_packet(struct packet_struct *p)
927 {
928   char buf[1024];
929   int len=0;
930
931   memset(buf,'\0',sizeof(buf));
932
933   len = build_packet(buf, p);
934
935   if (!len) return(False);
936
937   return(send_udp(p->fd,buf,len,p->ip,p->port));
938 }
939
940 /****************************************************************************
941   receive a packet with timeout on a open UDP filedescriptor
942   The timeout is in milliseconds
943   ***************************************************************************/
944 struct packet_struct *receive_packet(int fd,enum packet_type type,int t)
945 {
946         fd_set fds;
947         struct timeval timeout;
948         int ret;
949
950         FD_ZERO(&fds);
951         FD_SET(fd,&fds);
952         timeout.tv_sec = t/1000;
953         timeout.tv_usec = 1000*(t%1000);
954
955         if ((ret = sys_select_intr(fd+1,&fds,&timeout)) == -1) {
956                 /* errno should be EBADF or EINVAL. */
957                 DEBUG(0,("select returned -1, errno = %s (%d)\n", strerror(errno), errno));
958                 return NULL;
959         }
960
961         if (ret == 0) /* timeout */
962                 return NULL;
963
964         if (FD_ISSET(fd,&fds)) 
965                 return(read_packet(fd,type));
966         
967         return(NULL);
968 }
969
970
971 /****************************************************************************
972   receive a UDP/137 packet either via UDP or from the unexpected packet
973   queue. The packet must be a reply packet and have the specified trn_id
974   The timeout is in milliseconds
975   ***************************************************************************/
976 struct packet_struct *receive_nmb_packet(int fd, int t, int trn_id)
977 {
978         struct packet_struct *p;
979
980         p = receive_packet(fd, NMB_PACKET, t);
981
982         if (p && p->packet.nmb.header.response &&
983             p->packet.nmb.header.name_trn_id == trn_id) {
984                 return p;
985         }
986         if (p) free_packet(p);
987
988         /* try the unexpected packet queue */
989         return receive_unexpected(NMB_PACKET, trn_id, NULL);
990 }
991
992 /****************************************************************************
993   receive a UDP/138 packet either via UDP or from the unexpected packet
994   queue. The packet must be a reply packet and have the specified mailslot name
995   The timeout is in milliseconds
996   ***************************************************************************/
997 struct packet_struct *receive_dgram_packet(int fd, int t, char *mailslot_name)
998 {
999         struct packet_struct *p;
1000
1001         p = receive_packet(fd, DGRAM_PACKET, t);
1002
1003         if (p && match_mailslot_name(p, mailslot_name)) {
1004                 return p;
1005         }
1006         if (p) free_packet(p);
1007
1008         /* try the unexpected packet queue */
1009         return receive_unexpected(DGRAM_PACKET, 0, mailslot_name);
1010 }
1011
1012
1013 /****************************************************************************
1014  see if a datagram has the right mailslot name
1015 ***************************************************************************/
1016 BOOL match_mailslot_name(struct packet_struct *p, char *mailslot_name)
1017 {
1018         struct dgram_packet *dgram = &p->packet.dgram;
1019         char *buf;
1020
1021         buf = &dgram->data[0];
1022         buf -= 4;
1023
1024         buf = smb_buf(buf);
1025
1026         if (memcmp(buf, mailslot_name, strlen(mailslot_name)+1) == 0) {
1027                 return True;
1028         }
1029
1030         return False;
1031 }
1032
1033
1034 /****************************************************************************
1035 return the number of bits that match between two 4 character buffers
1036   ***************************************************************************/
1037 static int matching_bits(uchar *p1, uchar *p2)
1038 {
1039         int i, j, ret = 0;
1040         for (i=0; i<4; i++) {
1041                 if (p1[i] != p2[i]) break;
1042                 ret += 8;
1043         }
1044
1045         if (i==4) return ret;
1046
1047         for (j=0; j<8; j++) {
1048                 if ((p1[i] & (1<<(7-j))) != (p2[i] & (1<<(7-j)))) break;
1049                 ret++;
1050         }       
1051         
1052         return ret;
1053 }
1054
1055
1056 static uchar sort_ip[4];
1057
1058 /****************************************************************************
1059 compare two query reply records
1060   ***************************************************************************/
1061 static int name_query_comp(uchar *p1, uchar *p2)
1062 {
1063         return matching_bits(p2+2, sort_ip) - matching_bits(p1+2, sort_ip);
1064 }
1065
1066 /****************************************************************************
1067 sort a set of 6 byte name query response records so that the IPs that
1068 have the most leading bits in common with the specified address come first
1069   ***************************************************************************/
1070 void sort_query_replies(char *data, int n, struct in_addr ip)
1071 {
1072         if (n <= 1) return;
1073
1074         putip(sort_ip, (char *)&ip);
1075
1076         qsort(data, n, 6, QSORT_CAST name_query_comp);
1077 }
1078
1079
1080 #define TRUNCATE_NETBIOS_NAME 1
1081
1082 /*******************************************************************
1083  convert, possibly using a stupid microsoft-ism which has destroyed
1084  the transport independence of netbios (for CIFS vendors that usually
1085  use the Win95-type methods, not for NT to NT communication, which uses
1086  DCE/RPC and therefore full-length unicode strings...) a dns name into
1087  a netbios name.
1088
1089  the netbios name (NOT necessarily null-terminated) is truncated to 15
1090  characters.
1091
1092  ******************************************************************/
1093 char *dns_to_netbios_name(char *dns_name)
1094 {
1095         static char netbios_name[16];
1096         int i;
1097         StrnCpy(netbios_name, dns_name, 15);
1098         netbios_name[15] = 0;
1099         
1100 #ifdef TRUNCATE_NETBIOS_NAME
1101         /* ok.  this is because of a stupid microsoft-ism.  if the called host
1102            name contains a '.', microsoft clients expect you to truncate the
1103            netbios name up to and including the '.'  this even applies, by
1104            mistake, to workgroup (domain) names, which is _really_ daft.
1105          */
1106         for (i = 15; i >= 0; i--)
1107         {
1108                 if (netbios_name[i] == '.')
1109                 {
1110                         netbios_name[i] = 0;
1111                         break;
1112                 }
1113         }
1114 #endif /* TRUNCATE_NETBIOS_NAME */
1115
1116         return netbios_name;
1117 }
1118
1119
1120 /****************************************************************************
1121 interpret the weird netbios "name". Return the name type
1122 ****************************************************************************/
1123 static int name_interpret(char *in,char *out)
1124 {
1125   int ret;
1126   int len = (*in++) / 2;
1127
1128   *out=0;
1129
1130   if (len > 30 || len<1) return(0);
1131
1132   while (len--)
1133     {
1134       if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
1135         *out = 0;
1136         return(0);
1137       }
1138       *out = ((in[0]-'A')<<4) + (in[1]-'A');
1139       in += 2;
1140       out++;
1141     }
1142   *out = 0;
1143   ret = out[-1];
1144
1145 #ifdef NETBIOS_SCOPE
1146   /* Handle any scope names */
1147   while(*in) 
1148     {
1149       *out++ = '.'; /* Scope names are separated by periods */
1150       len = *(uchar *)in++;
1151       StrnCpy(out, in, len);
1152       out += len;
1153       *out=0;
1154       in += len;
1155     }
1156 #endif
1157   return(ret);
1158 }
1159
1160 /****************************************************************************
1161 mangle a name into netbios format
1162
1163   Note:  <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
1164 ****************************************************************************/
1165 int name_mangle( char *In, char *Out, char name_type )
1166   {
1167   int   i;
1168   int   c;
1169   int   len;
1170   char  buf[20];
1171   char *p = Out;
1172   extern pstring global_scope;
1173
1174   /* Safely copy the input string, In, into buf[]. */
1175   (void)memset( buf, 0, 20 );
1176   if (strcmp(In,"*") == 0)
1177     buf[0] = '*';
1178   else
1179     (void)slprintf( buf, sizeof(buf) - 1, "%-15.15s%c", In, name_type );
1180
1181   /* Place the length of the first field into the output buffer. */
1182   p[0] = 32;
1183   p++;
1184
1185   /* Now convert the name to the rfc1001/1002 format. */
1186   for( i = 0; i < 16; i++ )
1187     {
1188     c = toupper( buf[i] );
1189     p[i*2]     = ( (c >> 4) & 0x000F ) + 'A';
1190     p[(i*2)+1] = (c & 0x000F) + 'A';
1191     }
1192   p += 32;
1193   p[0] = '\0';
1194
1195   /* Add the scope string. */
1196   for( i = 0, len = 0; NULL != global_scope; i++, len++ )
1197     {
1198     switch( global_scope[i] )
1199       {
1200       case '\0':
1201         p[0]     = len;
1202         if( len > 0 )
1203           p[len+1] = 0;
1204         return( name_len(Out) );
1205       case '.':
1206         p[0] = len;
1207         p   += (len + 1);
1208         len  = -1;
1209         break;
1210       default:
1211         p[len+1] = global_scope[i];
1212         break;
1213       }
1214     }
1215
1216   return( name_len(Out) );
1217   } /* name_mangle */
1218
1219
1220 /****************************************************************************
1221 find a pointer to a netbios name
1222 ****************************************************************************/
1223 static char *name_ptr(char *buf,int ofs)
1224 {
1225   uchar c = *(uchar *)(buf+ofs);
1226
1227   if ((c & 0xC0) == 0xC0)
1228     {
1229       uint16 l = RSVAL(buf, ofs) & 0x3FFF;
1230       DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
1231       return(buf + l);
1232     }
1233   else
1234     return(buf+ofs);
1235 }  
1236
1237 /****************************************************************************
1238 extract a netbios name from a buf
1239 ****************************************************************************/
1240 int name_extract(char *buf,int ofs,char *name)
1241 {
1242   char *p = name_ptr(buf,ofs);
1243   int d = PTR_DIFF(p,buf+ofs);
1244   pstrcpy(name,"");
1245   if (d < -50 || d > 50) return(0);
1246   return(name_interpret(p,name));
1247 }
1248   
1249 /****************************************************************************
1250 return the total storage length of a mangled name
1251 ****************************************************************************/
1252 int name_len(char *s1)
1253 {
1254         /* NOTE: this argument _must_ be unsigned */
1255         uchar *s = (uchar *)s1;
1256         int len;
1257
1258         /* If the two high bits of the byte are set, return 2. */
1259         if (0xC0 == (*s & 0xC0))
1260                 return(2);
1261
1262         /* Add up the length bytes. */
1263         for (len = 1; (*s); s += (*s) + 1) {
1264                 len += *s + 1;
1265                 SMB_ASSERT(len < 80);
1266         }
1267
1268         return(len);
1269 } /* name_len */