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