s4:sam.py - assign valid values when performing the special-attributes constraint...
[Samba.git] / source3 / libsmb / nmblib.c
blob943cbcbe6db463e232a7325a52c7af4986faa63c
1 /*
2 Unix SMB/CIFS implementation.
3 NBT netbios library routines
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 2007
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.
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.
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/>.
22 #include "includes.h"
23 #include "../lib/util/select.h"
25 static const struct opcode_names {
26 const char *nmb_opcode_name;
27 int opcode;
28 } nmb_header_opcode_names[] = {
29 {"Query", 0 },
30 {"Registration", 5 },
31 {"Release", 6 },
32 {"WACK", 7 },
33 {"Refresh", 8 },
34 {"Refresh(altcode)", 9 },
35 {"Multi-homed Registration", 15 },
36 {0, -1 }
39 /****************************************************************************
40 Lookup a nmb opcode name.
41 ****************************************************************************/
43 static const char *lookup_opcode_name( int opcode )
45 const struct opcode_names *op_namep;
46 int i;
48 for(i = 0; nmb_header_opcode_names[i].nmb_opcode_name != 0; i++) {
49 op_namep = &nmb_header_opcode_names[i];
50 if(opcode == op_namep->opcode)
51 return op_namep->nmb_opcode_name;
53 return "<unknown opcode>";
56 /****************************************************************************
57 Print out a res_rec structure.
58 ****************************************************************************/
60 static void debug_nmb_res_rec(struct res_rec *res, const char *hdr)
62 int i, j;
64 DEBUGADD( 4, ( " %s: nmb_name=%s rr_type=%d rr_class=%d ttl=%d\n",
65 hdr,
66 nmb_namestr(&res->rr_name),
67 res->rr_type,
68 res->rr_class,
69 res->ttl ) );
71 if( res->rdlength == 0 || res->rdata == NULL )
72 return;
74 for (i = 0; i < res->rdlength; i+= MAX_NETBIOSNAME_LEN) {
75 DEBUGADD(4, (" %s %3x char ", hdr, i));
77 for (j = 0; j < MAX_NETBIOSNAME_LEN; j++) {
78 unsigned char x = res->rdata[i+j];
79 if (x < 32 || x > 127)
80 x = '.';
82 if (i+j >= res->rdlength)
83 break;
84 DEBUGADD(4, ("%c", x));
87 DEBUGADD(4, (" hex "));
89 for (j = 0; j < MAX_NETBIOSNAME_LEN; j++) {
90 if (i+j >= res->rdlength)
91 break;
92 DEBUGADD(4, ("%02X", (unsigned char)res->rdata[i+j]));
95 DEBUGADD(4, ("\n"));
99 /****************************************************************************
100 Process a nmb packet.
101 ****************************************************************************/
103 void debug_nmb_packet(struct packet_struct *p)
105 struct nmb_packet *nmb = &p->packet.nmb;
107 if( DEBUGLVL( 4 ) ) {
108 dbgtext( "nmb packet from %s(%d) header: id=%d "
109 "opcode=%s(%d) response=%s\n",
110 inet_ntoa(p->ip), p->port,
111 nmb->header.name_trn_id,
112 lookup_opcode_name(nmb->header.opcode),
113 nmb->header.opcode,
114 BOOLSTR(nmb->header.response) );
115 dbgtext( " header: flags: bcast=%s rec_avail=%s "
116 "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 "
123 "nscount=%d arcount=%d\n",
124 nmb->header.rcode,
125 nmb->header.qdcount,
126 nmb->header.ancount,
127 nmb->header.nscount,
128 nmb->header.arcount );
131 if (nmb->header.qdcount) {
132 DEBUGADD( 4, ( " question: q_name=%s q_type=%d q_class=%d\n",
133 nmb_namestr(&nmb->question.question_name),
134 nmb->question.question_type,
135 nmb->question.question_class) );
138 if (nmb->answers && nmb->header.ancount) {
139 debug_nmb_res_rec(nmb->answers,"answers");
141 if (nmb->nsrecs && nmb->header.nscount) {
142 debug_nmb_res_rec(nmb->nsrecs,"nsrecs");
144 if (nmb->additional && nmb->header.arcount) {
145 debug_nmb_res_rec(nmb->additional,"additional");
149 /*******************************************************************
150 Handle "compressed" name pointers.
151 ******************************************************************/
153 static bool handle_name_ptrs(unsigned char *ubuf,int *offset,int length,
154 bool *got_pointer,int *ret)
156 int loop_count=0;
158 while ((ubuf[*offset] & 0xC0) == 0xC0) {
159 if (!*got_pointer)
160 (*ret) += 2;
161 (*got_pointer)=True;
162 (*offset) = ((ubuf[*offset] & ~0xC0)<<8) | ubuf[(*offset)+1];
163 if (loop_count++ == 10 ||
164 (*offset) < 0 || (*offset)>(length-2)) {
165 return False;
168 return True;
171 /*******************************************************************
172 Parse a nmb name from "compressed" format to something readable
173 return the space taken by the name, or 0 if the name is invalid
174 ******************************************************************/
176 static int parse_nmb_name(char *inbuf,int ofs,int length, struct nmb_name *name)
178 int m,n=0;
179 unsigned char *ubuf = (unsigned char *)inbuf;
180 int ret = 0;
181 bool got_pointer=False;
182 int loop_count=0;
183 int offset = ofs;
185 if (length - offset < 2)
186 return(0);
188 /* handle initial name pointers */
189 if (!handle_name_ptrs(ubuf,&offset,length,&got_pointer,&ret))
190 return(0);
192 m = ubuf[offset];
194 if (!m)
195 return(0);
196 if ((m & 0xC0) || offset+m+2 > length)
197 return(0);
199 memset((char *)name,'\0',sizeof(*name));
201 /* the "compressed" part */
202 if (!got_pointer)
203 ret += m + 2;
204 offset++;
205 while (m > 0) {
206 unsigned char c1,c2;
207 c1 = ubuf[offset++]-'A';
208 c2 = ubuf[offset++]-'A';
209 if ((c1 & 0xF0) || (c2 & 0xF0) || (n > sizeof(name->name)-1))
210 return(0);
211 name->name[n++] = (c1<<4) | c2;
212 m -= 2;
214 name->name[n] = 0;
216 if (n==MAX_NETBIOSNAME_LEN) {
217 /* parse out the name type, its always
218 * in the 16th byte of the name */
219 name->name_type = ((unsigned char)name->name[15]) & 0xff;
221 /* remove trailing spaces */
222 name->name[15] = 0;
223 n = 14;
224 while (n && name->name[n]==' ')
225 name->name[n--] = 0;
228 /* now the domain parts (if any) */
229 n = 0;
230 while (ubuf[offset]) {
231 /* we can have pointers within the domain part as well */
232 if (!handle_name_ptrs(ubuf,&offset,length,&got_pointer,&ret))
233 return(0);
235 m = ubuf[offset];
237 * Don't allow null domain parts.
239 if (!m)
240 return(0);
241 if (!got_pointer)
242 ret += m+1;
243 if (n)
244 name->scope[n++] = '.';
245 if (m+2+offset>length || n+m+1>sizeof(name->scope))
246 return(0);
247 offset++;
248 while (m--)
249 name->scope[n++] = (char)ubuf[offset++];
252 * Watch for malicious loops.
254 if (loop_count++ == 10)
255 return 0;
257 name->scope[n++] = 0;
259 return(ret);
262 /****************************************************************************
263 Put a netbios name, padding(s) and a name type into a 16 character buffer.
264 name is already in DOS charset.
265 [15 bytes name + padding][1 byte name type].
266 ****************************************************************************/
268 void put_name(char *dest, const char *name, int pad, unsigned int name_type)
270 size_t len = strlen(name);
272 memcpy(dest, name, (len < MAX_NETBIOSNAME_LEN) ?
273 len : MAX_NETBIOSNAME_LEN - 1);
274 if (len < MAX_NETBIOSNAME_LEN - 1) {
275 memset(dest + len, pad, MAX_NETBIOSNAME_LEN - 1 - len);
277 dest[MAX_NETBIOSNAME_LEN - 1] = name_type;
280 /*******************************************************************
281 Put a compressed nmb name into a buffer. Return the length of the
282 compressed name.
284 Compressed names are really weird. The "compression" doubles the
285 size. The idea is that it also means that compressed names conform
286 to the doman name system. See RFC1002.
288 If buf == NULL this is a length calculation.
289 ******************************************************************/
291 static int put_nmb_name(char *buf,int offset,struct nmb_name *name)
293 int ret,m;
294 nstring buf1;
295 char *p;
297 if (strcmp(name->name,"*") == 0) {
298 /* special case for wildcard name */
299 put_name(buf1, "*", '\0', name->name_type);
300 } else {
301 put_name(buf1, name->name, ' ', name->name_type);
304 if (buf) {
305 buf[offset] = 0x20;
308 ret = 34;
310 for (m=0;m<MAX_NETBIOSNAME_LEN;m++) {
311 if (buf) {
312 buf[offset+1+2*m] = 'A' + ((buf1[m]>>4)&0xF);
313 buf[offset+2+2*m] = 'A' + (buf1[m]&0xF);
316 offset += 33;
318 if (buf) {
319 buf[offset] = 0;
322 if (name->scope[0]) {
323 /* XXXX this scope handling needs testing */
324 ret += strlen(name->scope) + 1;
325 if (buf) {
326 safe_strcpy(&buf[offset+1],name->scope,
327 sizeof(name->scope));
329 p = &buf[offset+1];
330 while ((p = strchr_m(p,'.'))) {
331 buf[offset] = PTR_DIFF(p,&buf[offset+1]);
332 offset += (buf[offset] + 1);
333 p = &buf[offset+1];
335 buf[offset] = strlen(&buf[offset+1]);
339 return ret;
342 /*******************************************************************
343 Useful for debugging messages.
344 ******************************************************************/
346 char *nmb_namestr(const struct nmb_name *n)
348 fstring name;
349 char *result;
351 pull_ascii_fstring(name, n->name);
352 if (!n->scope[0])
353 result = talloc_asprintf(talloc_tos(), "%s<%02x>", name,
354 n->name_type);
355 else
356 result = talloc_asprintf(talloc_tos(), "%s<%02x>.%s", name,
357 n->name_type, n->scope);
359 SMB_ASSERT(result != NULL);
360 return result;
363 /*******************************************************************
364 Allocate and parse some resource records.
365 ******************************************************************/
367 static bool parse_alloc_res_rec(char *inbuf,int *offset,int length,
368 struct res_rec **recs, int count)
370 int i;
372 *recs = SMB_MALLOC_ARRAY(struct res_rec, count);
373 if (!*recs)
374 return(False);
376 memset((char *)*recs,'\0',sizeof(**recs)*count);
378 for (i=0;i<count;i++) {
379 int l = parse_nmb_name(inbuf,*offset,length,
380 &(*recs)[i].rr_name);
381 (*offset) += l;
382 if (!l || (*offset)+10 > length) {
383 SAFE_FREE(*recs);
384 return(False);
386 (*recs)[i].rr_type = RSVAL(inbuf,(*offset));
387 (*recs)[i].rr_class = RSVAL(inbuf,(*offset)+2);
388 (*recs)[i].ttl = RIVAL(inbuf,(*offset)+4);
389 (*recs)[i].rdlength = RSVAL(inbuf,(*offset)+8);
390 (*offset) += 10;
391 if ((*recs)[i].rdlength>sizeof((*recs)[i].rdata) ||
392 (*offset)+(*recs)[i].rdlength > length) {
393 SAFE_FREE(*recs);
394 return(False);
396 memcpy((*recs)[i].rdata,inbuf+(*offset),(*recs)[i].rdlength);
397 (*offset) += (*recs)[i].rdlength;
399 return(True);
402 /*******************************************************************
403 Put a resource record into a packet.
404 If buf == NULL this is a length calculation.
405 ******************************************************************/
407 static int put_res_rec(char *buf,int offset,struct res_rec *recs,int count)
409 int ret=0;
410 int i;
412 for (i=0;i<count;i++) {
413 int l = put_nmb_name(buf,offset,&recs[i].rr_name);
414 offset += l;
415 ret += l;
416 if (buf) {
417 RSSVAL(buf,offset,recs[i].rr_type);
418 RSSVAL(buf,offset+2,recs[i].rr_class);
419 RSIVAL(buf,offset+4,recs[i].ttl);
420 RSSVAL(buf,offset+8,recs[i].rdlength);
421 memcpy(buf+offset+10,recs[i].rdata,recs[i].rdlength);
423 offset += 10+recs[i].rdlength;
424 ret += 10+recs[i].rdlength;
427 return ret;
430 /*******************************************************************
431 Put a compressed name pointer record into a packet.
432 If buf == NULL this is a length calculation.
433 ******************************************************************/
435 static int put_compressed_name_ptr(unsigned char *buf,
436 int offset,
437 struct res_rec *rec,
438 int ptr_offset)
440 int ret=0;
441 if (buf) {
442 buf[offset] = (0xC0 | ((ptr_offset >> 8) & 0xFF));
443 buf[offset+1] = (ptr_offset & 0xFF);
445 offset += 2;
446 ret += 2;
447 if (buf) {
448 RSSVAL(buf,offset,rec->rr_type);
449 RSSVAL(buf,offset+2,rec->rr_class);
450 RSIVAL(buf,offset+4,rec->ttl);
451 RSSVAL(buf,offset+8,rec->rdlength);
452 memcpy(buf+offset+10,rec->rdata,rec->rdlength);
454 offset += 10+rec->rdlength;
455 ret += 10+rec->rdlength;
457 return ret;
460 /*******************************************************************
461 Parse a dgram packet. Return False if the packet can't be parsed
462 or is invalid for some reason, True otherwise.
464 This is documented in section 4.4.1 of RFC1002.
465 ******************************************************************/
467 static bool parse_dgram(char *inbuf,int length,struct dgram_packet *dgram)
469 int offset;
470 int flags;
472 memset((char *)dgram,'\0',sizeof(*dgram));
474 if (length < 14)
475 return(False);
477 dgram->header.msg_type = CVAL(inbuf,0);
478 flags = CVAL(inbuf,1);
479 dgram->header.flags.node_type = (enum node_type)((flags>>2)&3);
480 if (flags & 1)
481 dgram->header.flags.more = True;
482 if (flags & 2)
483 dgram->header.flags.first = True;
484 dgram->header.dgm_id = RSVAL(inbuf,2);
485 putip((char *)&dgram->header.source_ip,inbuf+4);
486 dgram->header.source_port = RSVAL(inbuf,8);
487 dgram->header.dgm_length = RSVAL(inbuf,10);
488 dgram->header.packet_offset = RSVAL(inbuf,12);
490 offset = 14;
492 if (dgram->header.msg_type == 0x10 ||
493 dgram->header.msg_type == 0x11 ||
494 dgram->header.msg_type == 0x12) {
495 offset += parse_nmb_name(inbuf,offset,length,
496 &dgram->source_name);
497 offset += parse_nmb_name(inbuf,offset,length,
498 &dgram->dest_name);
501 if (offset >= length || (length-offset > sizeof(dgram->data)))
502 return(False);
504 dgram->datasize = length-offset;
505 memcpy(dgram->data,inbuf+offset,dgram->datasize);
507 /* Paranioa. Ensure the last 2 bytes in the dgram buffer are
508 zero. This should be true anyway, just enforce it for
509 paranioa sake. JRA. */
510 SMB_ASSERT(dgram->datasize <= (sizeof(dgram->data)-2));
511 memset(&dgram->data[sizeof(dgram->data)-2], '\0', 2);
513 return(True);
516 /*******************************************************************
517 Parse a nmb packet. Return False if the packet can't be parsed
518 or is invalid for some reason, True otherwise.
519 ******************************************************************/
521 static bool parse_nmb(char *inbuf,int length,struct nmb_packet *nmb)
523 int nm_flags,offset;
525 memset((char *)nmb,'\0',sizeof(*nmb));
527 if (length < 12)
528 return(False);
530 /* parse the header */
531 nmb->header.name_trn_id = RSVAL(inbuf,0);
533 DEBUG(10,("parse_nmb: packet id = %d\n", nmb->header.name_trn_id));
535 nmb->header.opcode = (CVAL(inbuf,2) >> 3) & 0xF;
536 nmb->header.response = ((CVAL(inbuf,2)>>7)&1)?True:False;
537 nm_flags = ((CVAL(inbuf,2) & 0x7) << 4) + (CVAL(inbuf,3)>>4);
538 nmb->header.nm_flags.bcast = (nm_flags&1)?True:False;
539 nmb->header.nm_flags.recursion_available = (nm_flags&8)?True:False;
540 nmb->header.nm_flags.recursion_desired = (nm_flags&0x10)?True:False;
541 nmb->header.nm_flags.trunc = (nm_flags&0x20)?True:False;
542 nmb->header.nm_flags.authoritative = (nm_flags&0x40)?True:False;
543 nmb->header.rcode = CVAL(inbuf,3) & 0xF;
544 nmb->header.qdcount = RSVAL(inbuf,4);
545 nmb->header.ancount = RSVAL(inbuf,6);
546 nmb->header.nscount = RSVAL(inbuf,8);
547 nmb->header.arcount = RSVAL(inbuf,10);
549 if (nmb->header.qdcount) {
550 offset = parse_nmb_name(inbuf,12,length,
551 &nmb->question.question_name);
552 if (!offset)
553 return(False);
555 if (length - (12+offset) < 4)
556 return(False);
557 nmb->question.question_type = RSVAL(inbuf,12+offset);
558 nmb->question.question_class = RSVAL(inbuf,12+offset+2);
560 offset += 12+4;
561 } else {
562 offset = 12;
565 /* and any resource records */
566 if (nmb->header.ancount &&
567 !parse_alloc_res_rec(inbuf,&offset,length,&nmb->answers,
568 nmb->header.ancount))
569 return(False);
571 if (nmb->header.nscount &&
572 !parse_alloc_res_rec(inbuf,&offset,length,&nmb->nsrecs,
573 nmb->header.nscount))
574 return(False);
576 if (nmb->header.arcount &&
577 !parse_alloc_res_rec(inbuf,&offset,length,
578 &nmb->additional, nmb->header.arcount))
579 return(False);
581 return(True);
584 /*******************************************************************
585 'Copy constructor' for an nmb packet.
586 ******************************************************************/
588 static struct packet_struct *copy_nmb_packet(struct packet_struct *packet)
590 struct nmb_packet *nmb;
591 struct nmb_packet *copy_nmb;
592 struct packet_struct *pkt_copy;
594 if(( pkt_copy = SMB_MALLOC_P(struct packet_struct)) == NULL) {
595 DEBUG(0,("copy_nmb_packet: malloc fail.\n"));
596 return NULL;
599 /* Structure copy of entire thing. */
601 *pkt_copy = *packet;
603 /* Ensure this copy is not locked. */
604 pkt_copy->locked = False;
605 pkt_copy->recv_fd = -1;
606 pkt_copy->send_fd = -1;
608 /* Ensure this copy has no resource records. */
609 nmb = &packet->packet.nmb;
610 copy_nmb = &pkt_copy->packet.nmb;
612 copy_nmb->answers = NULL;
613 copy_nmb->nsrecs = NULL;
614 copy_nmb->additional = NULL;
616 /* Now copy any resource records. */
618 if (nmb->answers) {
619 if((copy_nmb->answers = SMB_MALLOC_ARRAY(
620 struct res_rec,nmb->header.ancount)) == NULL)
621 goto free_and_exit;
622 memcpy((char *)copy_nmb->answers, (char *)nmb->answers,
623 nmb->header.ancount * sizeof(struct res_rec));
625 if (nmb->nsrecs) {
626 if((copy_nmb->nsrecs = SMB_MALLOC_ARRAY(
627 struct res_rec, nmb->header.nscount)) == NULL)
628 goto free_and_exit;
629 memcpy((char *)copy_nmb->nsrecs, (char *)nmb->nsrecs,
630 nmb->header.nscount * sizeof(struct res_rec));
632 if (nmb->additional) {
633 if((copy_nmb->additional = SMB_MALLOC_ARRAY(
634 struct res_rec, nmb->header.arcount)) == NULL)
635 goto free_and_exit;
636 memcpy((char *)copy_nmb->additional, (char *)nmb->additional,
637 nmb->header.arcount * sizeof(struct res_rec));
640 return pkt_copy;
642 free_and_exit:
644 SAFE_FREE(copy_nmb->answers);
645 SAFE_FREE(copy_nmb->nsrecs);
646 SAFE_FREE(copy_nmb->additional);
647 SAFE_FREE(pkt_copy);
649 DEBUG(0,("copy_nmb_packet: malloc fail in resource records.\n"));
650 return NULL;
653 /*******************************************************************
654 'Copy constructor' for a dgram packet.
655 ******************************************************************/
657 static struct packet_struct *copy_dgram_packet(struct packet_struct *packet)
659 struct packet_struct *pkt_copy;
661 if(( pkt_copy = SMB_MALLOC_P(struct packet_struct)) == NULL) {
662 DEBUG(0,("copy_dgram_packet: malloc fail.\n"));
663 return NULL;
666 /* Structure copy of entire thing. */
668 *pkt_copy = *packet;
670 /* Ensure this copy is not locked. */
671 pkt_copy->locked = False;
672 pkt_copy->recv_fd = -1;
673 pkt_copy->send_fd = -1;
675 /* There are no additional pointers in a dgram packet,
676 we are finished. */
677 return pkt_copy;
680 /*******************************************************************
681 'Copy constructor' for a generic packet.
682 ******************************************************************/
684 struct packet_struct *copy_packet(struct packet_struct *packet)
686 if(packet->packet_type == NMB_PACKET)
687 return copy_nmb_packet(packet);
688 else if (packet->packet_type == DGRAM_PACKET)
689 return copy_dgram_packet(packet);
690 return NULL;
693 /*******************************************************************
694 Free up any resources associated with an nmb packet.
695 ******************************************************************/
697 static void free_nmb_packet(struct nmb_packet *nmb)
699 SAFE_FREE(nmb->answers);
700 SAFE_FREE(nmb->nsrecs);
701 SAFE_FREE(nmb->additional);
704 /*******************************************************************
705 Free up any resources associated with a dgram packet.
706 ******************************************************************/
708 static void free_dgram_packet(struct dgram_packet *nmb)
710 /* We have nothing to do for a dgram packet. */
713 /*******************************************************************
714 Free up any resources associated with a packet.
715 ******************************************************************/
717 void free_packet(struct packet_struct *packet)
719 if (packet->locked)
720 return;
721 if (packet->packet_type == NMB_PACKET)
722 free_nmb_packet(&packet->packet.nmb);
723 else if (packet->packet_type == DGRAM_PACKET)
724 free_dgram_packet(&packet->packet.dgram);
725 ZERO_STRUCTPN(packet);
726 SAFE_FREE(packet);
729 /*******************************************************************
730 Parse a packet buffer into a packet structure.
731 ******************************************************************/
733 struct packet_struct *parse_packet(char *buf,int length,
734 enum packet_type packet_type,
735 struct in_addr ip,
736 int port)
738 struct packet_struct *p;
739 bool ok=False;
741 p = SMB_MALLOC_P(struct packet_struct);
742 if (!p)
743 return(NULL);
745 ZERO_STRUCTP(p); /* initialize for possible padding */
747 p->next = NULL;
748 p->prev = NULL;
749 p->ip = ip;
750 p->port = port;
751 p->locked = False;
752 p->timestamp = time(NULL);
753 p->packet_type = packet_type;
755 switch (packet_type) {
756 case NMB_PACKET:
757 ok = parse_nmb(buf,length,&p->packet.nmb);
758 break;
760 case DGRAM_PACKET:
761 ok = parse_dgram(buf,length,&p->packet.dgram);
762 break;
765 if (!ok) {
766 free_packet(p);
767 return NULL;
770 return p;
773 /*******************************************************************
774 Read a packet from a socket and parse it, returning a packet ready
775 to be used or put on the queue. This assumes a UDP socket.
776 ******************************************************************/
778 struct packet_struct *read_packet(int fd,enum packet_type packet_type)
780 struct packet_struct *packet;
781 struct sockaddr_storage sa;
782 struct sockaddr_in *si = (struct sockaddr_in *)&sa;
783 char buf[MAX_DGRAM_SIZE];
784 int length;
786 length = read_udp_v4_socket(fd,buf,sizeof(buf),&sa);
787 if (length < MIN_DGRAM_SIZE || sa.ss_family != AF_INET) {
788 return NULL;
791 packet = parse_packet(buf,
792 length,
793 packet_type,
794 si->sin_addr,
795 ntohs(si->sin_port));
796 if (!packet)
797 return NULL;
799 packet->recv_fd = fd;
800 packet->send_fd = -1;
802 DEBUG(5,("Received a packet of len %d from (%s) port %d\n",
803 length, inet_ntoa(packet->ip), packet->port ) );
805 return(packet);
808 /*******************************************************************
809 Send a udp packet on a already open socket.
810 ******************************************************************/
812 static bool send_udp(int fd,char *buf,int len,struct in_addr ip,int port)
814 bool ret = False;
815 int i;
816 struct sockaddr_in sock_out;
818 /* set the address and port */
819 memset((char *)&sock_out,'\0',sizeof(sock_out));
820 putip((char *)&sock_out.sin_addr,(char *)&ip);
821 sock_out.sin_port = htons( port );
822 sock_out.sin_family = AF_INET;
824 DEBUG( 5, ( "Sending a packet of len %d to (%s) on port %d\n",
825 len, inet_ntoa(ip), port ) );
828 * Patch to fix asynch error notifications from Linux kernel.
831 for (i = 0; i < 5; i++) {
832 ret = (sendto(fd,buf,len,0,(struct sockaddr *)&sock_out,
833 sizeof(sock_out)) >= 0);
834 if (ret || errno != ECONNREFUSED)
835 break;
838 if (!ret)
839 DEBUG(0,("Packet send failed to %s(%d) ERRNO=%s\n",
840 inet_ntoa(ip),port,strerror(errno)));
842 return(ret);
845 /*******************************************************************
846 Build a dgram packet ready for sending.
847 If buf == NULL this is a length calculation.
848 ******************************************************************/
850 static int build_dgram(char *buf, size_t len, struct dgram_packet *dgram)
852 unsigned char *ubuf = (unsigned char *)buf;
853 int offset=0;
855 /* put in the header */
856 if (buf) {
857 ubuf[0] = dgram->header.msg_type;
858 ubuf[1] = (((int)dgram->header.flags.node_type)<<2);
859 if (dgram->header.flags.more)
860 ubuf[1] |= 1;
861 if (dgram->header.flags.first)
862 ubuf[1] |= 2;
863 RSSVAL(ubuf,2,dgram->header.dgm_id);
864 putip(ubuf+4,(char *)&dgram->header.source_ip);
865 RSSVAL(ubuf,8,dgram->header.source_port);
866 RSSVAL(ubuf,12,dgram->header.packet_offset);
869 offset = 14;
871 if (dgram->header.msg_type == 0x10 ||
872 dgram->header.msg_type == 0x11 ||
873 dgram->header.msg_type == 0x12) {
874 offset += put_nmb_name((char *)ubuf,offset,&dgram->source_name);
875 offset += put_nmb_name((char *)ubuf,offset,&dgram->dest_name);
878 if (buf) {
879 memcpy(ubuf+offset,dgram->data,dgram->datasize);
881 offset += dgram->datasize;
883 /* automatically set the dgm_length
884 * NOTE: RFC1002 says the dgm_length does *not*
885 * include the fourteen-byte header. crh
887 dgram->header.dgm_length = (offset - 14);
888 if (buf) {
889 RSSVAL(ubuf,10,dgram->header.dgm_length);
892 return offset;
895 /*******************************************************************
896 Build a nmb name
897 *******************************************************************/
899 void make_nmb_name( struct nmb_name *n, const char *name, int type)
901 fstring unix_name;
902 memset( (char *)n, '\0', sizeof(struct nmb_name) );
903 fstrcpy(unix_name, name);
904 strupper_m(unix_name);
905 push_ascii(n->name, unix_name, sizeof(n->name), STR_TERMINATE);
906 n->name_type = (unsigned int)type & 0xFF;
907 push_ascii(n->scope, global_scope(), 64, STR_TERMINATE);
910 /*******************************************************************
911 Compare two nmb names
912 ******************************************************************/
914 bool nmb_name_equal(struct nmb_name *n1, struct nmb_name *n2)
916 return ((n1->name_type == n2->name_type) &&
917 strequal(n1->name ,n2->name ) &&
918 strequal(n1->scope,n2->scope));
921 /*******************************************************************
922 Build a nmb packet ready for sending.
923 If buf == NULL this is a length calculation.
924 ******************************************************************/
926 static int build_nmb(char *buf, size_t len, struct nmb_packet *nmb)
928 unsigned char *ubuf = (unsigned char *)buf;
929 int offset=0;
931 if (len && len < 12) {
932 return 0;
935 /* put in the header */
936 if (buf) {
937 RSSVAL(ubuf,offset,nmb->header.name_trn_id);
938 ubuf[offset+2] = (nmb->header.opcode & 0xF) << 3;
939 if (nmb->header.response)
940 ubuf[offset+2] |= (1<<7);
941 if (nmb->header.nm_flags.authoritative &&
942 nmb->header.response)
943 ubuf[offset+2] |= 0x4;
944 if (nmb->header.nm_flags.trunc)
945 ubuf[offset+2] |= 0x2;
946 if (nmb->header.nm_flags.recursion_desired)
947 ubuf[offset+2] |= 0x1;
948 if (nmb->header.nm_flags.recursion_available &&
949 nmb->header.response)
950 ubuf[offset+3] |= 0x80;
951 if (nmb->header.nm_flags.bcast)
952 ubuf[offset+3] |= 0x10;
953 ubuf[offset+3] |= (nmb->header.rcode & 0xF);
955 RSSVAL(ubuf,offset+4,nmb->header.qdcount);
956 RSSVAL(ubuf,offset+6,nmb->header.ancount);
957 RSSVAL(ubuf,offset+8,nmb->header.nscount);
958 RSSVAL(ubuf,offset+10,nmb->header.arcount);
961 offset += 12;
962 if (nmb->header.qdcount) {
963 /* XXXX this doesn't handle a qdcount of > 1 */
964 if (len) {
965 /* Length check. */
966 int extra = put_nmb_name(NULL,offset,
967 &nmb->question.question_name);
968 if (offset + extra > len) {
969 return 0;
972 offset += put_nmb_name((char *)ubuf,offset,
973 &nmb->question.question_name);
974 if (buf) {
975 RSSVAL(ubuf,offset,nmb->question.question_type);
976 RSSVAL(ubuf,offset+2,nmb->question.question_class);
978 offset += 4;
981 if (nmb->header.ancount) {
982 if (len) {
983 /* Length check. */
984 int extra = put_res_rec(NULL,offset,nmb->answers,
985 nmb->header.ancount);
986 if (offset + extra > len) {
987 return 0;
990 offset += put_res_rec((char *)ubuf,offset,nmb->answers,
991 nmb->header.ancount);
994 if (nmb->header.nscount) {
995 if (len) {
996 /* Length check. */
997 int extra = put_res_rec(NULL,offset,nmb->nsrecs,
998 nmb->header.nscount);
999 if (offset + extra > len) {
1000 return 0;
1003 offset += put_res_rec((char *)ubuf,offset,nmb->nsrecs,
1004 nmb->header.nscount);
1008 * The spec says we must put compressed name pointers
1009 * in the following outgoing packets :
1010 * NAME_REGISTRATION_REQUEST, NAME_REFRESH_REQUEST,
1011 * NAME_RELEASE_REQUEST.
1014 if((nmb->header.response == False) &&
1015 ((nmb->header.opcode == NMB_NAME_REG_OPCODE) ||
1016 (nmb->header.opcode == NMB_NAME_RELEASE_OPCODE) ||
1017 (nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_8) ||
1018 (nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_9) ||
1019 (nmb->header.opcode == NMB_NAME_MULTIHOMED_REG_OPCODE)) &&
1020 (nmb->header.arcount == 1)) {
1022 if (len) {
1023 /* Length check. */
1024 int extra = put_compressed_name_ptr(NULL,offset,
1025 nmb->additional,12);
1026 if (offset + extra > len) {
1027 return 0;
1030 offset += put_compressed_name_ptr(ubuf,offset,
1031 nmb->additional,12);
1032 } else if (nmb->header.arcount) {
1033 if (len) {
1034 /* Length check. */
1035 int extra = put_res_rec(NULL,offset,nmb->additional,
1036 nmb->header.arcount);
1037 if (offset + extra > len) {
1038 return 0;
1041 offset += put_res_rec((char *)ubuf,offset,nmb->additional,
1042 nmb->header.arcount);
1044 return offset;
1047 /*******************************************************************
1048 Linearise a packet.
1049 ******************************************************************/
1051 int build_packet(char *buf, size_t buflen, struct packet_struct *p)
1053 int len = 0;
1055 switch (p->packet_type) {
1056 case NMB_PACKET:
1057 len = build_nmb(buf,buflen,&p->packet.nmb);
1058 break;
1060 case DGRAM_PACKET:
1061 len = build_dgram(buf,buflen,&p->packet.dgram);
1062 break;
1065 return len;
1068 /*******************************************************************
1069 Send a packet_struct.
1070 ******************************************************************/
1072 bool send_packet(struct packet_struct *p)
1074 char buf[1024];
1075 int len=0;
1077 memset(buf,'\0',sizeof(buf));
1079 len = build_packet(buf, sizeof(buf), p);
1081 if (!len)
1082 return(False);
1084 return(send_udp(p->send_fd,buf,len,p->ip,p->port));
1087 /****************************************************************************
1088 Receive a packet with timeout on a open UDP filedescriptor.
1089 The timeout is in milliseconds
1090 ***************************************************************************/
1092 struct packet_struct *receive_packet(int fd,enum packet_type type,int t)
1094 fd_set fds;
1095 struct timeval timeout;
1096 int ret;
1098 FD_ZERO(&fds);
1099 FD_SET(fd,&fds);
1100 timeout.tv_sec = t/1000;
1101 timeout.tv_usec = 1000*(t%1000);
1103 if ((ret = sys_select_intr(fd+1,&fds,NULL,NULL,&timeout)) == -1) {
1104 /* errno should be EBADF or EINVAL. */
1105 DEBUG(0,("select returned -1, errno = %s (%d)\n",
1106 strerror(errno), errno));
1107 return NULL;
1110 if (ret == 0) /* timeout */
1111 return NULL;
1113 if (FD_ISSET(fd,&fds))
1114 return(read_packet(fd,type));
1116 return(NULL);
1119 /****************************************************************************
1120 Receive a UDP/137 packet either via UDP or from the unexpected packet
1121 queue. The packet must be a reply packet and have the specified trn_id.
1122 The timeout is in milliseconds.
1123 ***************************************************************************/
1125 struct packet_struct *receive_nmb_packet(int fd, int t, int trn_id)
1127 struct packet_struct *p;
1129 p = receive_packet(fd, NMB_PACKET, t);
1131 if (p && p->packet.nmb.header.response &&
1132 p->packet.nmb.header.name_trn_id == trn_id) {
1133 return p;
1135 if (p)
1136 free_packet(p);
1138 /* try the unexpected packet queue */
1139 return receive_unexpected(NMB_PACKET, trn_id, NULL);
1142 /****************************************************************************
1143 Receive a UDP/138 packet either via UDP or from the unexpected packet
1144 queue. The packet must be a reply packet and have the specified mailslot name
1145 The timeout is in milliseconds.
1146 ***************************************************************************/
1148 struct packet_struct *receive_dgram_packet(int fd, int t,
1149 const char *mailslot_name)
1151 struct packet_struct *p;
1153 p = receive_packet(fd, DGRAM_PACKET, t);
1155 if (p && match_mailslot_name(p, mailslot_name)) {
1156 return p;
1158 if (p)
1159 free_packet(p);
1161 /* try the unexpected packet queue */
1162 return receive_unexpected(DGRAM_PACKET, 0, mailslot_name);
1165 /****************************************************************************
1166 See if a datagram has the right mailslot name.
1167 ***************************************************************************/
1169 bool match_mailslot_name(struct packet_struct *p, const char *mailslot_name)
1171 struct dgram_packet *dgram = &p->packet.dgram;
1172 char *buf;
1174 buf = &dgram->data[0];
1175 buf -= 4;
1177 buf = smb_buf(buf);
1179 if (memcmp(buf, mailslot_name, strlen(mailslot_name)+1) == 0) {
1180 return True;
1183 return False;
1186 /****************************************************************************
1187 Return the number of bits that match between two len character buffers
1188 ***************************************************************************/
1190 int matching_len_bits(unsigned char *p1, unsigned char *p2, size_t len)
1192 size_t i, j;
1193 int ret = 0;
1194 for (i=0; i<len; i++) {
1195 if (p1[i] != p2[i])
1196 break;
1197 ret += 8;
1200 if (i==len)
1201 return ret;
1203 for (j=0; j<8; j++) {
1204 if ((p1[i] & (1<<(7-j))) != (p2[i] & (1<<(7-j))))
1205 break;
1206 ret++;
1209 return ret;
1212 static unsigned char sort_ip[4];
1214 /****************************************************************************
1215 Compare two query reply records.
1216 ***************************************************************************/
1218 static int name_query_comp(unsigned char *p1, unsigned char *p2)
1220 return matching_len_bits(p2+2, sort_ip, 4) -
1221 matching_len_bits(p1+2, sort_ip, 4);
1224 /****************************************************************************
1225 Sort a set of 6 byte name query response records so that the IPs that
1226 have the most leading bits in common with the specified address come first.
1227 ***************************************************************************/
1229 void sort_query_replies(char *data, int n, struct in_addr ip)
1231 if (n <= 1)
1232 return;
1234 putip(sort_ip, (char *)&ip);
1236 /* TODO:
1237 this can't use TYPESAFE_QSORT() as the types are wrong.
1238 It should be fixed to use a real type instead of char*
1240 qsort(data, n, 6, QSORT_CAST name_query_comp);
1243 /****************************************************************************
1244 Interpret the weird netbios "name" into a unix fstring. Return the name type.
1245 Returns -1 on error.
1246 ****************************************************************************/
1248 static int name_interpret(unsigned char *buf, size_t buf_len,
1249 unsigned char *in, fstring name)
1251 unsigned char *end_ptr = buf + buf_len;
1252 int ret;
1253 unsigned int len;
1254 fstring out_string;
1255 unsigned char *out = (unsigned char *)out_string;
1257 *out=0;
1259 if (in >= end_ptr) {
1260 return -1;
1262 len = (*in++) / 2;
1264 if (len<1) {
1265 return -1;
1268 while (len--) {
1269 if (&in[1] >= end_ptr) {
1270 return -1;
1272 if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
1273 *out = 0;
1274 return(0);
1276 *out = ((in[0]-'A')<<4) + (in[1]-'A');
1277 in += 2;
1278 out++;
1279 if (PTR_DIFF(out,out_string) >= sizeof(fstring)) {
1280 return -1;
1283 ret = out[-1];
1284 out[-1] = 0;
1286 pull_ascii_fstring(name, out_string);
1288 return(ret);
1291 /****************************************************************************
1292 Mangle a name into netbios format.
1293 Note: <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
1294 ****************************************************************************/
1296 char *name_mangle(TALLOC_CTX *mem_ctx, char *In, char name_type)
1298 int i;
1299 int len;
1300 nstring buf;
1301 char *result;
1302 char *p;
1304 result = talloc_array(mem_ctx, char, 33 + strlen(global_scope()) + 2);
1305 if (result == NULL) {
1306 return NULL;
1308 p = result;
1310 /* Safely copy the input string, In, into buf[]. */
1311 if (strcmp(In,"*") == 0)
1312 put_name(buf, "*", '\0', 0x00);
1313 else {
1314 /* We use an fstring here as mb dos names can expend x3 when
1315 going to utf8. */
1316 fstring buf_unix;
1317 nstring buf_dos;
1319 pull_ascii_fstring(buf_unix, In);
1320 strupper_m(buf_unix);
1322 push_ascii_nstring(buf_dos, buf_unix);
1323 put_name(buf, buf_dos, ' ', name_type);
1326 /* Place the length of the first field into the output buffer. */
1327 p[0] = 32;
1328 p++;
1330 /* Now convert the name to the rfc1001/1002 format. */
1331 for( i = 0; i < MAX_NETBIOSNAME_LEN; i++ ) {
1332 p[i*2] = ( (buf[i] >> 4) & 0x000F ) + 'A';
1333 p[(i*2)+1] = (buf[i] & 0x000F) + 'A';
1335 p += 32;
1336 p[0] = '\0';
1338 /* Add the scope string. */
1339 for( i = 0, len = 0; *(global_scope()) != '\0'; i++, len++ ) {
1340 switch( (global_scope())[i] ) {
1341 case '\0':
1342 p[0] = len;
1343 if( len > 0 )
1344 p[len+1] = 0;
1345 return result;
1346 case '.':
1347 p[0] = len;
1348 p += (len + 1);
1349 len = -1;
1350 break;
1351 default:
1352 p[len+1] = (global_scope())[i];
1353 break;
1357 return result;
1360 /****************************************************************************
1361 Find a pointer to a netbios name.
1362 ****************************************************************************/
1364 static unsigned char *name_ptr(unsigned char *buf, size_t buf_len, unsigned int ofs)
1366 unsigned char c = 0;
1368 if (ofs > buf_len || buf_len < 1) {
1369 return NULL;
1372 c = *(unsigned char *)(buf+ofs);
1373 if ((c & 0xC0) == 0xC0) {
1374 uint16 l = 0;
1376 if (ofs > buf_len - 1) {
1377 return NULL;
1379 l = RSVAL(buf, ofs) & 0x3FFF;
1380 if (l > buf_len) {
1381 return NULL;
1383 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
1384 return(buf + l);
1385 } else {
1386 return(buf+ofs);
1390 /****************************************************************************
1391 Extract a netbios name from a buf (into a unix string) return name type.
1392 Returns -1 on error.
1393 ****************************************************************************/
1395 int name_extract(unsigned char *buf, size_t buf_len, unsigned int ofs, fstring name)
1397 unsigned char *p = name_ptr(buf,buf_len,ofs);
1399 name[0] = '\0';
1400 if (p == NULL) {
1401 return -1;
1403 return(name_interpret(buf,buf_len,p,name));
1406 /****************************************************************************
1407 Return the total storage length of a mangled name.
1408 Returns -1 on error.
1409 ****************************************************************************/
1411 int name_len(unsigned char *s1, size_t buf_len)
1413 /* NOTE: this argument _must_ be unsigned */
1414 unsigned char *s = (unsigned char *)s1;
1415 int len = 0;
1417 if (buf_len < 1) {
1418 return -1;
1420 /* If the two high bits of the byte are set, return 2. */
1421 if (0xC0 == (*s & 0xC0)) {
1422 if (buf_len < 2) {
1423 return -1;
1425 return(2);
1428 /* Add up the length bytes. */
1429 for (len = 1; (*s); s += (*s) + 1) {
1430 len += *s + 1;
1431 if (len > buf_len) {
1432 return -1;
1436 return(len);