namepacket.c: Block SIGTERM correctly - we can only take them at defined points.
[samba.git] / source3 / nameservreply.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    NBT netbios routines and daemon - version 2
5    Copyright (C) Andrew Tridgell 1994-1997
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20    
21    Module name: nameservreply.c
22
23    Revision History:
24
25    14 jan 96: lkcl@pires.co.uk
26    added multiple workgroup domain master support
27
28    04 jul 96: lkcl@pires.co.uk
29    created module nameservreply containing NetBIOS reply functions
30
31 */
32
33 #include "includes.h"
34
35 extern int ClientNMB;
36
37 extern int DEBUGLEVEL;
38
39 extern struct in_addr wins_ip;
40
41
42 /****************************************************************************
43   add a netbios entry. respond to the (possibly new) owner.
44   **************************************************************************/
45 void add_name_respond(struct subnet_record *d, int fd, struct in_addr from_ip,
46                                 uint16 response_id,
47                                 struct nmb_name *name,
48                                 int nb_flags, int ttl, struct in_addr register_ip,
49                                 BOOL new_owner, struct in_addr reply_to_ip)
50 {
51         /* register the old or the new owners' ip */
52         add_netbios_entry(d,name->name,name->name_type,
53                                                 nb_flags,ttl,REGISTER,register_ip,False,True);
54
55         /* reply yes or no to the host that requested the name */
56         send_name_response(fd,from_ip, response_id, NMB_REG,
57                                 new_owner, True,
58                                 name, nb_flags, ttl, reply_to_ip);
59 }
60
61 /****************************************************************************
62 send a registration / release response: pos/neg
63 **************************************************************************/
64 void send_name_response(int fd, struct in_addr from_ip,
65                                 int name_trn_id, int opcode, BOOL success, BOOL recurse,
66                                 struct nmb_name *reply_name, int nb_flags, int ttl,
67                                 struct in_addr ip)
68 {
69   char rdata[6];
70   struct packet_struct p;
71
72   int rcode = 0;  
73
74   if (success == False)
75   {
76     /* NEGATIVE RESPONSE */
77     rcode = 6;
78   }
79   else if (opcode == NMB_REG && recurse == False)
80   {
81     /* END-NODE CHALLENGE REGISTRATION RESPONSE */
82         rcode = 0;
83   }
84   
85   rdata[0] = nb_flags;
86   rdata[1] = 0;
87   putip(&rdata[2],(char *)&ip);
88   
89   p.ip = from_ip;
90   p.port = NMB_PORT;
91   p.fd = fd;
92   p.timestamp = time(NULL);
93   p.packet_type = NMB_PACKET;
94
95   reply_netbios_packet(&p,name_trn_id,
96                        rcode,opcode,opcode,recurse,
97                        reply_name, 0x20, 0x1,
98                        ttl, 
99                        rdata, 6);
100 }
101
102
103 /****************************************************************************
104 reply to a name release
105 ****************************************************************************/
106 void reply_name_release(struct packet_struct *p)
107 {
108   struct nmb_packet *nmb = &p->packet.nmb;
109   struct in_addr ip;
110   int nb_flags = nmb->additional->rdata[0];
111   BOOL bcast = nmb->header.nm_flags.bcast;
112   struct name_record *n;
113   struct subnet_record *d = NULL;
114   int search = 0;
115   BOOL success = False;
116   
117   putip((char *)&ip,&nmb->additional->rdata[2]);  
118   
119   DEBUG(3,("Name release on name %s\n",
120            namestr(&nmb->question.question_name)));
121   
122   if (!(d = find_req_subnet(p->ip, bcast)))
123     {
124       DEBUG(3,("response packet: bcast %s not known\n",
125                inet_ntoa(p->ip)));
126       return;
127     }
128
129   if (bcast)
130     search |= FIND_LOCAL;
131   else
132     search |= FIND_WINS;
133
134   n = find_name_search(&d, &nmb->question.question_name, 
135                        search, ip);
136   
137   /* XXXX under what conditions should we reject the removal?? */
138   /* For now - remove if the names match and the group bit matches. */
139   if (n && (NAME_GROUP(n->ip_flgs[0].nb_flags) == NAME_GROUP(nb_flags)))
140     {
141       success = True;
142       
143       DEBUG(5, ("reply_name_release: Removing name %s on subnet %s\n",
144                 namestr(&nmb->question.question_name), inet_ntoa(d->bcast_ip)));
145       remove_name(d,n);
146       n = NULL;
147     }
148   
149   if (bcast) return;
150   
151   /* Send a NAME RELEASE RESPONSE (pos/neg) see rfc1002.txt 4.2.10-11 */
152   send_name_response(p->fd,p->ip, nmb->header.name_trn_id, NMB_REL,
153                      success, False,
154                      &nmb->question.question_name, nb_flags, 0, ip);
155 }
156
157
158 /****************************************************************************
159 reply to a reg request
160 **************************************************************************/
161 void reply_name_reg(struct packet_struct *p)
162 {
163   struct nmb_packet *nmb = &p->packet.nmb;
164   struct nmb_name *question = &nmb->question.question_name;
165   
166   struct nmb_name *reply_name = question;
167
168   char *qname      = question->name;
169   int   qname_type = question->name_type;
170  
171   BOOL bcast = nmb->header.nm_flags.bcast;
172   
173   int ttl = GET_TTL(nmb->additional->ttl);
174   int nb_flags = nmb->additional->rdata[0];
175   BOOL group = NAME_GROUP(nb_flags);
176
177   struct subnet_record *d = NULL;
178   struct name_record *n = NULL;
179
180   BOOL success = True;
181   BOOL secured_redirect = False;
182
183   struct in_addr ip, from_ip;
184   int search = 0;
185   
186   putip((char *)&from_ip,&nmb->additional->rdata[2]);
187   ip = from_ip;
188   
189   DEBUG(3,("Name registration for name %s at %s - ",
190                    namestr(question),inet_ntoa(ip)));
191   
192   if (group)
193     {
194       /* apparently we should return 255.255.255.255 for group queries
195          (email from MS) */
196       ip = wins_ip;
197     }
198   
199   if (!(d = find_req_subnet(p->ip, bcast)))
200   {
201     DEBUG(3,("reply_name_reg: subnet %s not known\n",
202                                 inet_ntoa(p->ip)));
203     return;
204   }
205
206   if (bcast)
207         search |= FIND_LOCAL;
208   else
209         search |= FIND_WINS;
210
211   /* see if the name already exists */
212   n = find_name_search(&d, question, search, from_ip);
213   
214   if (n)
215   {
216     DEBUG(3,("found\n"));
217     if (!group) /* unique names */
218         {
219           if (n->source == SELF || NAME_GROUP(n->ip_flgs[0].nb_flags))
220           {
221               /* no-one can register one of samba's names, nor can they
222                  register a name that's a group name as a unique name */
223               
224               success = False;
225           }
226           else if(!ip_equal(ip, n->ip_flgs[0].ip))
227           {
228               /* XXXX rfc1001.txt says:
229                * if we are doing secured WINS, we must send a Wait-Acknowledge
230                * packet (WACK) to the person who wants the name, then do a
231                * name query on the person who currently owns the unique name.
232                * if the current owner still says they own it, the person who wants
233                    * the name can't have it. if they do not, or are not alive, they can.
234                */
235
236           secured_redirect = True;
237
238               reply_name = &n->name;
239           }
240           else
241           {
242               n->ip_flgs[0].ip = ip;
243               n->death_time = ttl?p->timestamp+ttl*3:0;
244               DEBUG(3,("%s owner: %s\n",namestr(&n->name),inet_ntoa(n->ip_flgs[0].ip)));
245           }
246         }
247     else
248         {
249           /* refresh the name */
250           if (n->source != SELF)
251           {
252               n->death_time = ttl?p->timestamp + ttl*3:0;
253           }
254         }
255
256     /* XXXX bug reported by terryt@ren.pc.athabascau.ca */
257     /* names that people have checked for and not found get DNSFAILed. 
258        we need to update the name record if someone then registers */
259
260     if (n->source == DNSFAIL)
261       n->source = REGISTER;
262
263   }
264   else
265   {
266       DEBUG(3,("not found\n"));
267       /* add the name to our name/subnet, or WINS, database */
268       n = add_netbios_entry(d,qname,qname_type,nb_flags,ttl,REGISTER,ip,
269                                 True,!bcast);
270   }
271   
272   /* if samba owns a unique name on a subnet, then it must respond and
273      disallow the attempted registration. if the registration is
274      successful by broadcast, only then is there no need to respond
275      (implicit registration: see rfc1001.txt 15.2.1).
276    */
277
278   if (bcast && success) return;
279   
280   if (secured_redirect)
281   {
282     char rdata[2];
283
284     /* XXXX i am confused. RSVAL or SSVAL? assume NMB byte ordering */
285     RSSVAL(rdata,0,(nmb->header.opcode&0xf) + ((nb_flags&0xff) << 4));
286   
287     /* XXXX mistake in rfc1002.txt? 4.2.16: NULL is 0xa see 4.2.1.3 
288        type  = 0x0a; see rfc1002.txt 4.2.1.3 
289        class = 0x01; see rfc1002.txt 4.2.16
290      */
291
292     /* send WAIT ACKNOWLEDGEMENT see rfc1002.txt 4.2.16 */
293     reply_netbios_packet(p,nmb->header.name_trn_id,
294                        0,NMB_WAIT_ACK,NMB_WAIT_ACK,False,
295                        reply_name, 0x0a, 0x01,
296                        15*1000, /* 15 seconds long enough to wait? */
297                        rdata, 2);
298
299     /* initiate some enquiries to the current owner. */
300         queue_netbios_packet(d,ClientNMB,NMB_QUERY,
301                                                  NAME_REGISTER_CHALLENGE,
302                                                  reply_name->name,reply_name->name_type,
303                              nb_flags,0,0,NULL,NULL,
304                                                  False, False, n->ip_flgs[0].ip, p->ip);
305   }
306   else
307   {
308     /* Send a NAME REGISTRATION RESPONSE (pos/neg) see rfc1002.txt 4.2.13-14
309        or an END-NODE CHALLENGE REGISTRATION RESPONSE see rfc1002.txt 4.2.7
310      */
311
312         send_name_response(p->fd,p->ip, nmb->header.name_trn_id, NMB_REG,
313                                                 success, True,
314                                                 reply_name, nb_flags, ttl, ip);
315   }
316 }
317
318 /* this is used to sort names for a name status into a sensible order
319    we put our own names first, then in alphabetical order */
320 static int status_compare(char *n1,char *n2)
321 {
322   extern pstring myname;
323   int l1,l2,l3;
324
325   /* its a bit tricky because the names are space padded */
326   for (l1=0;l1<15 && n1[l1] && n1[l1] != ' ';l1++) ;
327   for (l2=0;l2<15 && n2[l2] && n2[l2] != ' ';l2++) ;
328   l3 = strlen(myname);
329
330   if ((l1==l3) && strncmp(n1,myname,l3) == 0 && 
331       (l2!=l3 || strncmp(n2,myname,l3) != 0))
332     return -1;
333
334   if ((l2==l3) && strncmp(n2,myname,l3) == 0 && 
335       (l1!=l3 || strncmp(n1,myname,l3) != 0))
336     return 1;
337
338   return memcmp(n1,n2,18);
339 }
340
341
342 /****************************************************************************
343   reply to a name status query
344
345   combine the list of the local interface on which the query was made with
346   the names registered via wins.
347   ****************************************************************************/
348 void reply_name_status(struct packet_struct *p)
349 {
350   struct nmb_packet *nmb = &p->packet.nmb;
351   char *qname   = nmb->question.question_name.name;
352   int ques_type = nmb->question.question_name.name_type;
353   char rdata[MAX_DGRAM_SIZE];
354   char *countptr, *buf, *bufend, *buf0;
355   int names_added,i;
356   struct name_record *n;
357   struct subnet_record *d = NULL;
358   int search = FIND_SELF | FIND_WINS | FIND_LOCAL;
359
360   /* NOTE: we always treat a name status lookup as a bcast */ 
361   if (!(d = find_req_subnet(p->ip, True)))
362   {
363     DEBUG(3,("Name status req: bcast %s not known\n",
364                         inet_ntoa(p->ip)));
365     return;
366   }
367
368   DEBUG(3,("Name status for name %s %s\n",
369            namestr(&nmb->question.question_name), 
370            inet_ntoa(p->ip)));
371
372   n = find_name_search(&d, &nmb->question.question_name,
373                                 search, p->ip);
374   
375   if (!n) return;
376   
377   /* XXXX hack, we should calculate exactly how many will fit */
378   bufend = &rdata[MAX_DGRAM_SIZE] - 18;
379   countptr = buf = rdata;
380   buf += 1;
381   buf0 = buf;
382
383   names_added = 0;
384
385   n = d->namelist;
386
387   while (buf < bufend) 
388   {
389     if (n->source == SELF)
390     {
391       int name_type = n->name.name_type;
392       
393       /* check if we want to exclude other workgroup names
394              from the response. if we don't exclude them, windows clients
395              get confused and will respond with an error for NET VIEW */
396       
397       if (!strequal(n->name.name,"*") &&
398           !strequal(n->name.name,"__SAMBA__") &&
399           (name_type < 0x1b || name_type >= 0x20 || 
400            ques_type < 0x1b || ques_type >= 0x20 ||
401            strequal(qname, n->name.name)))
402       {
403         /* start with first bit of putting info in buffer: the name */
404         bzero(buf,18);
405             sprintf(buf,"%-15.15s",n->name.name);
406         strupper(buf);
407         
408         /* put name type and netbios flags in buffer */
409         buf[15] = name_type;
410         buf[16]  = n->ip_flgs[0].nb_flags;
411         
412         buf += 18;
413       
414         names_added++;
415       }
416     }
417
418     /* remove duplicate names */
419     qsort(buf0,names_added,18,QSORT_CAST status_compare);
420
421     for (i=1;i<names_added;i++) {
422       if (memcmp(buf0 + 18*i,buf0 + 18*(i-1),16) == 0) {
423         names_added--;
424         if (names_added == i) break;
425         memmove(buf0 + 18*i,buf0 + 18*(i+1),18*(names_added-i));
426         i--;
427       }
428     }
429
430     buf = buf0 + 18*names_added;
431
432     n = n->next;
433
434     if (!n)
435     {
436       /* end of this name list: add wins names too? */
437       struct subnet_record *w_d;
438
439       if (!(w_d = wins_subnet)) break;
440
441       if (w_d != d)
442       {
443         d = w_d;
444         n = d->namelist; /* start on the wins name list */
445       }
446         }
447         if (!n) break;
448   }
449   
450   SCVAL(countptr,0,names_added);
451   
452   /* XXXXXXX we should fill in more fields of the statistics structure */
453   bzero(buf,64);
454   {
455     extern int num_good_sends,num_good_receives;
456     SIVAL(buf,20,num_good_sends);
457     SIVAL(buf,24,num_good_receives);
458   }
459   
460   buf += 46;
461   
462   /* Send a POSITIVE NAME STATUS RESPONSE */
463   reply_netbios_packet(p,nmb->header.name_trn_id,
464                            0,NMB_STATUS,0,True,
465                        &nmb->question.question_name,
466                        0x21, 0x01,
467                        0, rdata,PTR_DIFF(buf,rdata));
468 }
469
470
471 /***************************************************************************
472 reply to a name query.
473
474 with broadcast name queries:
475
476         - only reply if the query is for one of YOUR names. all other machines on
477           the network will be doing the same thing (that is, only replying to a
478           broadcast query if they own it)
479           NOTE: broadcast name queries should only be sent out by a machine
480           if they HAVEN'T been configured to use WINS. this is generally bad news
481           in a wide area tcp/ip network and should be rectified by the systems
482           administrator. USE WINS! :-)
483         - the exception to this is if the query is for a Primary Domain Controller
484           type name (0x1b), in which case, a reply is sent.
485
486         - NEVER send a negative response to a broadcast query. no-one else will!
487
488 with directed name queries:
489
490         - if you are the WINS server, you are expected to respond with either
491       a negative response, a positive response, or a wait-for-acknowledgement
492       packet, and then later on a pos/neg response.
493
494 ****************************************************************************/
495 void reply_name_query(struct packet_struct *p)
496 {
497   struct nmb_packet *nmb = &p->packet.nmb;
498   struct nmb_name *question = &nmb->question.question_name;
499   int name_type = question->name_type;
500   BOOL bcast = nmb->header.nm_flags.bcast;
501   int ttl=0;
502   int rcode = 0;
503   int nb_flags = 0;
504   struct in_addr retip;
505   char rdata[6];
506   struct subnet_record *d = NULL;
507   BOOL success = True;
508   struct name_record *n = NULL;
509
510   /* directed queries are for WINS server: broadcasts are local SELF queries.
511      the exception is Domain Master names.  */
512
513   int search = bcast ? FIND_LOCAL | FIND_WINS: FIND_WINS;
514
515   if (search & FIND_LOCAL)
516   {
517     if (!(d = find_req_subnet(p->ip, bcast)))
518     {
519       DEBUG(3,("name query: bcast %s not known\n",
520                                     inet_ntoa(p->ip)));
521       success = False;
522     }
523   }
524   else
525   {
526     if (!(d = wins_subnet))
527     {
528       DEBUG(3,("name query: wins search %s not known\n",
529                                     inet_ntoa(p->ip)));
530       success = False;
531     }
532   }
533
534   DEBUG(3,("Name query from %s for name %s<0x%x>\n", 
535                   inet_ntoa(p->ip), question->name, question->name_type));
536   
537   if (search == 0)
538   {
539     /* eh? no criterion for searching database. help! */
540     success = False;
541   }
542
543   if (!bcast && name_type == 0x1d)
544   {
545     /* see WINS manager HELP - 'How WINS Handles Special Names' */
546     /* a WINS query (unicasted) for a 0x1d name must always return False */
547     success = False;
548   }
549
550   if (success)
551   {
552     /* look up the name in the cache */
553     n = find_name_search(&d, question, search, p->ip);
554
555     /* it is a name that already failed DNS lookup or it's expired */
556     if (n && (n->source == DNSFAIL ||
557               (n->death_time && n->death_time < p->timestamp)))
558     {
559       success = False;
560     }
561    
562     /* do we want to do dns lookups? */
563     /* XXXX this DELAYS nmbd while it does a search. not a good idea
564        but there's no pleasant alternative. phil@hands.com suggested
565        making the name a full DNS name, which would succeed / fail
566        much quicker.
567      */
568     if (success && !n && (lp_wins_proxy() || !bcast))
569     {
570       n = dns_name_search(question, p->timestamp);
571     }
572   }
573
574   if (!n) success = False;
575   
576   if (success)
577   {
578       if (bcast && n->source != SELF && name_type != 0x1b)
579       {
580         /* don't respond to broadcast queries unless the query is for
581            a name we own or it is for a Primary Domain Controller name */
582
583             if (!lp_wins_proxy() || 
584             same_net(p->ip,n->ip_flgs[0].ip,*iface_nmask(p->ip)))
585         {
586               /* never reply with a negative response to broadcast queries */
587               return;
588             }
589           }
590       
591       /* name is directed query, or it's self, or it's a Domain Master type
592          name, or we're replying on behalf of a caller because they are on a
593          different subnet and cannot hear the broadcast. XXXX lp_wins_proxy
594          should be switched off in environments where broadcasts are forwarded
595        */
596
597       /* XXXX note: for proxy servers, we should forward the query on to
598          another WINS server if the name is not in our database, or we are
599          not a WINS server ourselves
600        */
601       ttl = n->death_time ? n->death_time - p->timestamp : GET_TTL(0);
602       retip = n->ip_flgs[0].ip;
603       nb_flags = n->ip_flgs[0].nb_flags;
604   }
605
606   if (!success && bcast) return; /* never reply negative response to bcasts */
607
608   /* if the IP is 0 then substitute my IP */
609   if (zero_ip(retip)) retip = *iface_ip(p->ip);
610
611   if (success)
612   {
613       rcode = 0;
614       DEBUG(3,("OK %s\n",inet_ntoa(retip)));      
615   }
616   else
617   {
618       rcode = 3;
619       DEBUG(3,("UNKNOWN\n"));      
620   }
621   
622   if (success)
623   {
624       rdata[0] = nb_flags;
625       rdata[1] = 0;
626       putip(&rdata[2],(char *)&retip);
627   }
628   
629   reply_netbios_packet(p,nmb->header.name_trn_id,
630                            rcode,NMB_QUERY,0,True,
631                        &nmb->question.question_name,
632                0x20, 0x01,
633                        ttl,
634                        rdata, success ? 6 : 0);
635 }