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