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