move to SAFE_FREE()
[samba.git] / source / nmbd / nmbd_namelistdb.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-1998
6    Copyright (C) Luke Kenneth Casson Leighton 1994-1998
7    Copyright (C) Jeremy Allison 1994-1998
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22    
23 */
24
25 #include "includes.h"
26
27 extern int DEBUGLEVEL;
28
29 extern char **my_netbios_names;
30
31 uint16 samba_nb_type = 0; /* samba's NetBIOS name type */
32
33
34 /* ************************************************************************** **
35  * Set Samba's NetBIOS name type.
36  * ************************************************************************** **
37  */
38 void set_samba_nb_type(void)
39   {
40   if( lp_wins_support() || wins_srv_count() )
41     samba_nb_type = NB_MFLAG;               /* samba is a 'hybrid' node type. */
42   else
43     samba_nb_type = NB_BFLAG;           /* samba is broadcast-only node type. */
44   } /* set_samba_nb_type */
45
46 /* ************************************************************************** **
47  * Convert a NetBIOS name to upper case.
48  * ************************************************************************** **
49  */
50 static void upcase_name( struct nmb_name *target, struct nmb_name *source )
51   {
52   int i;
53
54   if( NULL != source )
55     (void)memcpy( target, source, sizeof( struct nmb_name ) );
56
57   strupper( target->name );
58   strupper( target->scope );
59
60   /* fudge... We're using a byte-by-byte compare, so we must be sure that
61    * unused space doesn't have garbage in it.
62    */
63   for( i = strlen( target->name ); i < sizeof( target->name ); i++ )
64     target->name[i] = '\0';
65   for( i = strlen( target->scope ); i < sizeof( target->scope ); i++ )
66     target->scope[i] = '\0';
67   } /* upcase_name */
68
69 /* ************************************************************************** **
70  * Add a new or overwrite an existing namelist entry.
71  * ************************************************************************** **
72  */
73 static void update_name_in_namelist( struct subnet_record *subrec,
74                               struct name_record   *namerec )
75   {
76   struct name_record *oldrec = NULL;
77
78   (void)ubi_trInsert( subrec->namelist, namerec, &(namerec->name), &oldrec );
79   if( oldrec )
80     {
81     SAFE_FREE( oldrec->data.ip );
82     SAFE_FREE( oldrec );
83     }
84   } /* update_name_in_namelist */
85
86 /* ************************************************************************** **
87  * Remove a name from the namelist.
88  * ************************************************************************** **
89  */
90 void remove_name_from_namelist( struct subnet_record *subrec, 
91                                 struct name_record   *namerec )
92   {
93   (void)ubi_trRemove( subrec->namelist, namerec );
94
95   SAFE_FREE(namerec->data.ip);
96
97   ZERO_STRUCTP(namerec);
98   SAFE_FREE(namerec);
99
100   subrec->namelist_changed = True;
101   } /* remove_name_from_namelist */
102
103 /* ************************************************************************** **
104  * Find a name in a subnet.
105  * ************************************************************************** **
106  */
107 struct name_record *find_name_on_subnet( struct subnet_record *subrec,
108                                          struct nmb_name      *nmbname,
109                                          BOOL                  self_only )
110   {
111   struct nmb_name     uc_name[1];
112   struct name_record *name_ret;
113
114   upcase_name( uc_name, nmbname );
115   name_ret = (struct name_record *)ubi_trFind( subrec->namelist, uc_name );
116   if( name_ret )
117     {
118     /* Self names only - these include permanent names. */
119     if( self_only
120      && (name_ret->data.source != SELF_NAME)
121      && (name_ret->data.source != PERMANENT_NAME) )
122       {
123       DEBUG( 9, 
124              ( "find_name_on_subnet: on subnet %s - self name %s NOT FOUND\n",
125                subrec->subnet_name, nmb_namestr(nmbname) ) );
126       return( NULL );
127       }
128     DEBUG( 9, ("find_name_on_subnet: on subnet %s - found name %s source=%d\n",
129                subrec->subnet_name, nmb_namestr(nmbname), name_ret->data.source) );
130     return( name_ret );
131     }
132   DEBUG( 9, 
133          ( "find_name_on_subnet: on subnet %s - name %s NOT FOUND\n",
134            subrec->subnet_name, nmb_namestr(nmbname) ) );
135   return( NULL );
136   } /* find_name_on_subnet */
137
138 /* ************************************************************************** **
139  * Find a name over all known broadcast subnets.
140  * ************************************************************************** **
141  */
142 struct name_record *find_name_for_remote_broadcast_subnet(
143                                                    struct nmb_name *nmbname,
144                                                    BOOL             self_only )
145   {
146   struct subnet_record *subrec;
147   struct name_record   *namerec = NULL;
148
149   for( subrec = FIRST_SUBNET;
150        subrec;
151        subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec) )
152     {
153     if( NULL != (namerec = find_name_on_subnet(subrec, nmbname, self_only)) )
154       break;
155     }
156
157   return( namerec );
158   } /* find_name_for_remote_broadcast_subnet */
159   
160 /* ************************************************************************** **
161  * Update the ttl of an entry in a subnet name list.
162  * ************************************************************************** **
163  */
164 void update_name_ttl( struct name_record *namerec, int ttl )
165 {
166   time_t time_now = time(NULL);
167
168   if( namerec->data.death_time != PERMANENT_TTL )
169     namerec->data.death_time = time_now + ttl;
170
171   namerec->data.refresh_time = time_now + MIN((ttl/2), MAX_REFRESH_TIME);
172
173   namerec->subnet->namelist_changed = True;
174 } /* update_name_ttl */
175
176 /* ************************************************************************** **
177  * Add an entry to a subnet name list.
178  * ************************************************************************** **
179  */
180 struct name_record *add_name_to_subnet( struct subnet_record *subrec,
181                                         char                 *name,
182                                         int                   type,
183                                         uint16                nb_flags,
184                                         int                   ttl,
185                                         enum name_source      source,
186                                         int                   num_ips,
187                                         struct in_addr       *iplist)
188 {
189   struct name_record *namerec;
190   time_t time_now = time(NULL);
191
192   namerec = (struct name_record *)malloc( sizeof(*namerec) );
193   if( NULL == namerec )
194   {
195     DEBUG( 0, ( "add_name_to_subnet: malloc fail.\n" ) );
196     return( NULL );
197   }
198
199   memset( (char *)namerec, '\0', sizeof(*namerec) );
200   namerec->data.ip = (struct in_addr *)malloc( sizeof(struct in_addr) 
201                                                * num_ips );
202   if( NULL == namerec->data.ip )
203   {
204      DEBUG( 0, ( "add_name_to_subnet: malloc fail when creating ip_flgs.\n" ) );
205
206      ZERO_STRUCTP(namerec);
207      SAFE_FREE(namerec);
208      return NULL;
209   }
210
211   namerec->subnet = subrec;
212
213   make_nmb_name(&namerec->name, name, type);
214   upcase_name(&namerec->name, NULL );
215
216   /* Enter the name as active. */
217   namerec->data.nb_flags = nb_flags | NB_ACTIVE;
218
219   /* If it's our primary name, flag it as so. */
220   if( strequal( my_netbios_names[0], name ) )
221     namerec->data.nb_flags |= NB_PERM;
222
223   /* Copy the IPs. */
224   namerec->data.num_ips = num_ips;
225   memcpy( (namerec->data.ip), iplist, num_ips * sizeof(struct in_addr) );
226
227   /* Data source. */
228   namerec->data.source = source;
229
230   /* Setup the death_time and refresh_time. */
231   if( ttl == PERMANENT_TTL )
232     namerec->data.death_time = PERMANENT_TTL;
233   else
234     namerec->data.death_time = time_now + ttl;
235
236   namerec->data.refresh_time = time_now + MIN((ttl/2), MAX_REFRESH_TIME);
237
238   /* Now add the record to the name list. */    
239   update_name_in_namelist( subrec, namerec );
240
241   DEBUG( 3, ( "add_name_to_subnet: Added netbios name %s with first IP %s \
242 ttl=%d nb_flags=%2x to subnet %s\n",
243             nmb_namestr( &namerec->name ),
244             inet_ntoa( *iplist ),
245             ttl,
246             (unsigned int)nb_flags,
247             subrec->subnet_name ) );
248
249   subrec->namelist_changed = True;
250
251   return(namerec);
252 }
253
254 /*******************************************************************
255  Utility function automatically called when a name refresh or register 
256  succeeds. By definition this is a SELF_NAME (or we wouldn't be registering
257  it).
258  ******************************************************************/
259
260 void standard_success_register(struct subnet_record *subrec, 
261                              struct userdata_struct *userdata,
262                              struct nmb_name *nmbname, uint16 nb_flags, int ttl,
263                              struct in_addr registered_ip)
264 {
265   struct name_record *namerec;
266
267   namerec = find_name_on_subnet( subrec, nmbname, FIND_SELF_NAME );
268   if( NULL == namerec )
269     (void)add_name_to_subnet( subrec, nmbname->name, nmbname->name_type,
270                               nb_flags, ttl, SELF_NAME, 1, &registered_ip );
271   else
272     update_name_ttl( namerec, ttl );
273 }
274
275 /*******************************************************************
276  Utility function automatically called when a name refresh or register 
277  fails. Note that this is only ever called on a broadcast subnet with
278  one IP address per name. This is why it can just delete the name 
279  without enumerating the IP adresses. JRA.
280  ******************************************************************/
281
282 void standard_fail_register( struct subnet_record   *subrec,
283                              struct response_record *rrec,
284                              struct nmb_name        *nmbname )
285 {
286   struct name_record *namerec;
287
288   namerec = find_name_on_subnet( subrec, nmbname, FIND_SELF_NAME );
289
290   DEBUG( 0, ( "standard_fail_register: Failed to register/refresh name %s \
291 on subnet %s\n",
292             nmb_namestr(nmbname), subrec->subnet_name) );
293
294   /* Remove the name from the subnet. */
295   if( namerec )
296     remove_name_from_namelist(subrec, namerec);
297 }
298
299 /*******************************************************************
300  Utility function to remove an IP address from a name record.
301  ******************************************************************/
302
303 static void remove_nth_ip_in_record( struct name_record *namerec, int ind)
304 {
305   if( ind != namerec->data.num_ips )
306     memmove( (char *)(&namerec->data.ip[ind]),
307              (char *)(&namerec->data.ip[ind+1]), 
308              ( namerec->data.num_ips - ind - 1) * sizeof(struct in_addr) );
309
310   namerec->data.num_ips--;
311   namerec->subnet->namelist_changed = True;
312 }
313
314 /*******************************************************************
315  Utility function to check if an IP address exists in a name record.
316  ******************************************************************/
317
318 BOOL find_ip_in_name_record( struct name_record *namerec, struct in_addr ip )
319 {
320   int i;
321
322   for(i = 0; i < namerec->data.num_ips; i++)
323     if(ip_equal( namerec->data.ip[i], ip))
324       return True;
325
326   return False;
327 }
328
329 /*******************************************************************
330  Utility function to add an IP address to a name record.
331  ******************************************************************/
332
333 void add_ip_to_name_record( struct name_record *namerec, struct in_addr new_ip )
334 {
335   struct in_addr *new_list;
336
337   /* Don't add one we already have. */
338   if( find_ip_in_name_record( namerec, new_ip ) )
339     return;
340   
341   new_list = (struct in_addr *)malloc( (namerec->data.num_ips + 1)
342                                        * sizeof(struct in_addr) );
343   if( NULL == new_list )
344   {
345     DEBUG(0,("add_ip_to_name_record: Malloc fail !\n"));
346     return;
347   }
348
349   memcpy( (char *)new_list,
350           (char *)namerec->data.ip,
351           namerec->data.num_ips * sizeof(struct in_addr) );
352   new_list[namerec->data.num_ips] = new_ip;
353
354   SAFE_FREE(namerec->data.ip);
355   namerec->data.ip = new_list;
356   namerec->data.num_ips += 1;
357
358   namerec->subnet->namelist_changed = True;
359 }
360
361 /*******************************************************************
362  Utility function to remove an IP address from a name record.
363  ******************************************************************/
364
365 void remove_ip_from_name_record( struct name_record *namerec,
366                                  struct in_addr      remove_ip )
367 {
368   /* Try and find the requested ip address - remove it. */
369   int i;
370   int orig_num = namerec->data.num_ips;
371
372   for(i = 0; i < orig_num; i++)
373     if( ip_equal( remove_ip, namerec->data.ip[i]) )
374     {
375       remove_nth_ip_in_record( namerec, i);
376       break;
377     }
378 }
379
380 /*******************************************************************
381  Utility function that release_name callers can plug into as the
382  success function when a name release is successful. Used to save
383  duplication of success_function code.
384  ******************************************************************/
385
386 void standard_success_release( struct subnet_record   *subrec,
387                                struct userdata_struct *userdata,
388                                struct nmb_name        *nmbname,
389                                struct in_addr          released_ip )
390 {
391   struct name_record *namerec;
392
393   namerec = find_name_on_subnet( subrec, nmbname, FIND_ANY_NAME );
394
395   if( namerec == NULL )
396   {
397     DEBUG( 0, ( "standard_success_release: Name release for name %s IP %s \
398 on subnet %s. Name was not found on subnet.\n",
399                 nmb_namestr(nmbname),
400                 inet_ntoa(released_ip),
401                 subrec->subnet_name) );
402     return;
403   }
404   else
405   {
406     int orig_num = namerec->data.num_ips;
407
408     remove_ip_from_name_record( namerec, released_ip );
409
410     if( namerec->data.num_ips == orig_num )
411       DEBUG( 0, ( "standard_success_release: Name release for name %s IP %s \
412 on subnet %s. This ip is not known for this name.\n",
413                 nmb_namestr(nmbname),
414                 inet_ntoa(released_ip),
415                 subrec->subnet_name ) );
416   }
417
418   if( namerec->data.num_ips == 0 )
419     remove_name_from_namelist( subrec, namerec );
420 }
421
422 /*******************************************************************
423   Expires old names in a subnet namelist.
424   ******************************************************************/
425
426 void expire_names_on_subnet(struct subnet_record *subrec, time_t t)
427 {
428   struct name_record *namerec;
429   struct name_record *next_namerec;
430
431   for( namerec = (struct name_record *)ubi_trFirst( subrec->namelist );
432        namerec;
433        namerec = next_namerec )
434   {
435     next_namerec = (struct name_record *)ubi_trNext( namerec );
436     if( (namerec->data.death_time != PERMANENT_TTL)
437      && (namerec->data.death_time < t) )
438     {
439       if( namerec->data.source == SELF_NAME )
440       {
441         DEBUG( 3, ( "expire_names_on_subnet: Subnet %s not expiring SELF \
442 name %s\n", 
443                     subrec->subnet_name, nmb_namestr(&namerec->name) ) );
444         namerec->data.death_time += 300;
445         namerec->subnet->namelist_changed = True;
446         continue;
447       }
448       DEBUG(3,("expire_names_on_subnet: Subnet %s - removing expired name %s\n",
449                  subrec->subnet_name, nmb_namestr(&namerec->name)));
450   
451       remove_name_from_namelist( subrec, namerec );
452     }
453   }
454 }
455
456 /*******************************************************************
457   Expires old names in all subnet namelists.
458   ******************************************************************/
459
460 void expire_names(time_t t)
461 {
462   struct subnet_record *subrec;
463
464   for( subrec = FIRST_SUBNET;
465        subrec;
466        subrec = NEXT_SUBNET_INCLUDING_UNICAST(subrec) )
467   {
468     expire_names_on_subnet( subrec, t );
469   }
470 }
471
472 /****************************************************************************
473   Add the magic samba names, useful for finding samba servers.
474   These go directly into the name list for a particular subnet,
475   without going through the normal registration process.
476   When adding them to the unicast subnet, add them as a list of
477   all broadcast subnet IP addresses.
478 **************************************************************************/
479
480 void add_samba_names_to_subnet( struct subnet_record *subrec )
481 {
482   struct in_addr *iplist = &subrec->myip;
483   int num_ips = 1;
484
485   /* These names are added permanently (ttl of zero) and will NOT be
486      refreshed.  */
487
488   if( (subrec == unicast_subnet)
489    || (subrec == wins_server_subnet)
490    || (subrec == remote_broadcast_subnet) )
491   {
492     struct subnet_record *bcast_subrecs;
493     int i;
494     /* Create an IP list containing all our known subnets. */
495
496     num_ips = iface_count();
497     iplist = (struct in_addr *)malloc( num_ips * sizeof(struct in_addr) );
498     if( NULL == iplist )
499     {
500       DEBUG(0,("add_samba_names_to_subnet: Malloc fail !\n"));
501       return;
502     }
503
504     for( bcast_subrecs = FIRST_SUBNET, i = 0;
505          bcast_subrecs; 
506          bcast_subrecs = NEXT_SUBNET_EXCLUDING_UNICAST(bcast_subrecs), i++ )
507       iplist[i] = bcast_subrecs->myip;
508
509   }
510
511   (void)add_name_to_subnet(subrec,"*",0x0,samba_nb_type, PERMANENT_TTL,
512                            PERMANENT_NAME, num_ips, iplist);
513   (void)add_name_to_subnet(subrec,"*",0x20,samba_nb_type,PERMANENT_TTL,
514                            PERMANENT_NAME, num_ips, iplist);
515   (void)add_name_to_subnet(subrec,"__SAMBA__",0x20,samba_nb_type,PERMANENT_TTL,
516                            PERMANENT_NAME, num_ips, iplist);
517   (void)add_name_to_subnet(subrec,"__SAMBA__",0x00,samba_nb_type,PERMANENT_TTL,
518                            PERMANENT_NAME, num_ips, iplist);
519
520   if(iplist != &subrec->myip)
521     SAFE_FREE(iplist);
522 }
523
524 /****************************************************************************
525  Dump the contents of the namelists on all the subnets (including unicast)
526  into a file. Initiated by SIGHUP - used to debug the state of the namelists.
527 **************************************************************************/
528
529 static void dump_subnet_namelist( struct subnet_record *subrec, XFILE *fp)
530 {
531   struct name_record *namerec;
532   char *src_type;
533   struct tm *tm;
534   int i;
535
536   x_fprintf(fp, "Subnet %s\n----------------------\n", subrec->subnet_name);
537   for( namerec = (struct name_record *)ubi_trFirst( subrec->namelist );
538        namerec;
539        namerec = (struct name_record *)ubi_trNext( namerec ) )
540   {
541     x_fprintf(fp,"\tName = %s\t", nmb_namestr(&namerec->name));
542     switch(namerec->data.source)
543     {
544       case LMHOSTS_NAME:
545         src_type = "LMHOSTS_NAME";
546         break;
547       case WINS_PROXY_NAME:
548         src_type = "WINS_PROXY_NAME";
549         break;
550       case REGISTER_NAME:
551         src_type = "REGISTER_NAME";
552         break;
553       case SELF_NAME:
554         src_type = "SELF_NAME";
555         break;
556       case DNS_NAME:
557         src_type = "DNS_NAME";
558         break;
559       case DNSFAIL_NAME:
560         src_type = "DNSFAIL_NAME";
561         break;
562       case PERMANENT_NAME:
563         src_type = "PERMANENT_NAME";
564         break;
565       default:
566         src_type = "unknown!";
567         break;
568     }
569     x_fprintf(fp,"Source = %s\nb_flags = %x\t", src_type, namerec->data.nb_flags);
570
571     if(namerec->data.death_time != PERMANENT_TTL)
572     {
573       tm = LocalTime(&namerec->data.death_time);
574       x_fprintf(fp, "death_time = %s\t", asctime(tm));
575     }
576     else
577       x_fprintf(fp, "death_time = PERMANENT\t");
578
579     if(namerec->data.refresh_time != PERMANENT_TTL)
580     {
581       tm = LocalTime(&namerec->data.refresh_time);
582       x_fprintf(fp, "refresh_time = %s\n", asctime(tm));
583     }
584     else
585       x_fprintf(fp, "refresh_time = PERMANENT\n");
586
587     x_fprintf(fp, "\t\tnumber of IPS = %d", namerec->data.num_ips);
588     for(i = 0; i < namerec->data.num_ips; i++)
589       x_fprintf(fp, "\t%s", inet_ntoa(namerec->data.ip[i]));
590
591     x_fprintf(fp, "\n\n");
592   }
593 }
594
595 /****************************************************************************
596  Dump the contents of the namelists on all the subnets (including unicast)
597  into a file. Initiated by SIGHUP - used to debug the state of the namelists.
598 **************************************************************************/
599
600 void dump_all_namelists(void)
601 {
602   XFILE *fp; 
603   struct subnet_record *subrec;
604
605   fp = x_fopen(lock_path("namelist.debug"),O_WRONLY|O_CREAT|O_TRUNC, 0644);
606      
607   if (!fp)
608   { 
609     DEBUG(0,("dump_all_namelists: Can't open file %s. Error was %s\n",
610               "namelist.debug",strerror(errno)));
611     return;
612   }
613       
614   for( subrec = FIRST_SUBNET;
615        subrec;
616        subrec = NEXT_SUBNET_INCLUDING_UNICAST(subrec) )
617     dump_subnet_namelist( subrec, fp );
618
619   if( !we_are_a_wins_client() )
620     dump_subnet_namelist( unicast_subnet, fp );
621
622   if( remote_broadcast_subnet->namelist != NULL )
623     dump_subnet_namelist( remote_broadcast_subnet, fp );
624
625   if( wins_server_subnet != NULL )
626     dump_subnet_namelist( wins_server_subnet, fp );
627   x_fclose( fp );
628 }