r4054: got rid of Realloc(), replacing it with the type safe macro realloc_p()
[samba.git] / source / lib / util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2002
6    Copyright (C) Simo Sorce 2001
7    Copyright (C) Jim McDonough (jmcd@us.ibm.com)  2003.
8    Copyright (C) James J Myers 2003
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "dynconfig.h"
27 #include "system/network.h"
28 #include "system/iconv.h"
29
30 /**************************************************************************n
31  Find a suitable temporary directory. The result should be copied immediately
32  as it may be overwritten by a subsequent call.
33 ****************************************************************************/
34 const char *tmpdir(void)
35 {
36         char *p;
37         if ((p = getenv("TMPDIR")))
38                 return p;
39         return "/tmp";
40 }
41
42
43 /*******************************************************************
44  Check if a file exists - call vfs_file_exist for samba files.
45 ********************************************************************/
46 BOOL file_exist(const char *fname, struct stat *sbuf)
47 {
48         struct stat st;
49         if (!sbuf)
50                 sbuf = &st;
51   
52         if (stat(fname,sbuf) != 0) 
53                 return(False);
54
55         return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
56 }
57
58 /*******************************************************************
59  Check a files mod time.
60 ********************************************************************/
61
62 time_t file_modtime(const char *fname)
63 {
64         struct stat st;
65   
66         if (stat(fname,&st) != 0) 
67                 return(0);
68
69         return(st.st_mtime);
70 }
71
72 /*******************************************************************
73  Check if a directory exists.
74 ********************************************************************/
75
76 BOOL directory_exist(const char *dname,struct stat *st)
77 {
78         struct stat st2;
79         BOOL ret;
80
81         if (!st)
82                 st = &st2;
83
84         if (stat(dname,st) != 0) 
85                 return(False);
86
87         ret = S_ISDIR(st->st_mode);
88         if(!ret)
89                 errno = ENOTDIR;
90         return ret;
91 }
92
93 /*******************************************************************
94  Returns the size in bytes of the named file.
95 ********************************************************************/
96 off_t get_file_size(char *file_name)
97 {
98         struct stat buf;
99         buf.st_size = 0;
100         if(stat(file_name,&buf) != 0)
101                 return (off_t)-1;
102         return(buf.st_size);
103 }
104
105 /*******************************************************************
106  Close the low 3 fd's and open dev/null in their place.
107 ********************************************************************/
108 void close_low_fds(BOOL stderr_too)
109 {
110 #ifndef VALGRIND
111         int fd;
112         int i;
113
114         close(0);
115         close(1); 
116
117         if (stderr_too)
118                 close(2);
119
120         /* try and use up these file descriptors, so silly
121                 library routines writing to stdout etc won't cause havoc */
122         for (i=0;i<3;i++) {
123                 if (i == 2 && !stderr_too)
124                         continue;
125
126                 fd = open("/dev/null",O_RDWR,0);
127                 if (fd < 0)
128                         fd = open("/dev/null",O_WRONLY,0);
129                 if (fd < 0) {
130                         DEBUG(0,("Can't open /dev/null\n"));
131                         return;
132                 }
133                 if (fd != i) {
134                         DEBUG(0,("Didn't get file descriptor %d\n",i));
135                         return;
136                 }
137         }
138 #endif
139 }
140
141 /****************************************************************************
142  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
143  else
144   if SYSV use O_NDELAY
145   if BSD use FNDELAY
146 ****************************************************************************/
147
148 int set_blocking(int fd, BOOL set)
149 {
150         int val;
151 #ifdef O_NONBLOCK
152 #define FLAG_TO_SET O_NONBLOCK
153 #else
154 #ifdef SYSV
155 #define FLAG_TO_SET O_NDELAY
156 #else /* BSD */
157 #define FLAG_TO_SET FNDELAY
158 #endif
159 #endif
160
161         if((val = fcntl(fd, F_GETFL, 0)) == -1)
162                 return -1;
163         if(set) /* Turn blocking on - ie. clear nonblock flag */
164                 val &= ~FLAG_TO_SET;
165         else
166                 val |= FLAG_TO_SET;
167         return fcntl( fd, F_SETFL, val);
168 #undef FLAG_TO_SET
169 }
170
171
172 /*******************************************************************
173  Sleep for a specified number of milliseconds.
174 ********************************************************************/
175
176 void msleep(uint_t t)
177 {
178         struct timeval tval;  
179
180         tval.tv_sec = t/1000;
181         tval.tv_usec = 1000*(t%1000);
182         /* this should be the real select - do NOT replace
183            with sys_select() */
184         select(0,NULL,NULL,NULL,&tval);
185 }
186
187 /****************************************************************************
188  Become a daemon, discarding the controlling terminal.
189 ****************************************************************************/
190
191 void become_daemon(BOOL Fork)
192 {
193         if (Fork) {
194                 if (fork()) {
195                         _exit(0);
196                 }
197         }
198
199   /* detach from the terminal */
200 #ifdef HAVE_SETSID
201         setsid();
202 #elif defined(TIOCNOTTY)
203         {
204                 int i = open("/dev/tty", O_RDWR, 0);
205                 if (i != -1) {
206                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
207                         close(i);
208                 }
209         }
210 #endif /* HAVE_SETSID */
211
212         /* Close fd's 0,1,2. Needed if started by rsh */
213         close_low_fds(False);  /* Don't close stderr, let the debug system
214                                   attach it to the logfile */
215 }
216
217
218 /****************************************************************************
219  Free memory, checks for NULL.
220  Use directly SAFE_FREE()
221  Exists only because we need to pass a function pointer somewhere --SSS
222 ****************************************************************************/
223
224 void safe_free(void *p)
225 {
226         SAFE_FREE(p);
227 }
228
229
230 /*
231   see if a string matches either our primary or one of our secondary 
232   netbios aliases. do a case insensitive match
233 */
234 BOOL is_myname(const char *name)
235 {
236         const char **aliases;
237         int i;
238
239         if (strcasecmp(name, lp_netbios_name()) == 0) {
240                 return True;
241         }
242
243         aliases = lp_netbios_aliases();
244         for (i=0; aliases && aliases[i]; i++) {
245                 if (strcasecmp(name, aliases[i]) == 0) {
246                         return True;
247                 }
248         }
249
250         return False;
251 }
252
253
254 /****************************************************************************
255  Get my own name, return in malloc'ed storage.
256 ****************************************************************************/
257
258 char* get_myname(void)
259 {
260         char *hostname;
261         const int host_name_max = 255;
262         char *p;
263
264         hostname = malloc(host_name_max+1);
265         *hostname = 0;
266
267         /* get my host name */
268         if (gethostname(hostname, host_name_max+1) == -1) {
269                 DEBUG(0,("gethostname failed\n"));
270                 return NULL;
271         } 
272
273         /* Ensure null termination. */
274         hostname[host_name_max] = '\0';
275
276         /* split off any parts after an initial . */
277         p = strchr_m(hostname,'.');
278
279         if (p)
280                 *p = 0;
281         
282         return hostname;
283 }
284
285 /****************************************************************************
286  Get my own name, including domain.
287 ****************************************************************************/
288
289 BOOL get_myfullname(char *my_name)
290 {
291         pstring hostname;
292
293         *hostname = 0;
294
295         /* get my host name */
296         if (gethostname(hostname, sizeof(hostname)) == -1) {
297                 DEBUG(0,("gethostname failed\n"));
298                 return False;
299         } 
300
301         /* Ensure null termination. */
302         hostname[sizeof(hostname)-1] = '\0';
303
304         if (my_name)
305                 fstrcpy(my_name, hostname);
306         return True;
307 }
308
309 /****************************************************************************
310  Get my own domain name.
311 ****************************************************************************/
312
313 BOOL get_mydomname(fstring my_domname)
314 {
315         pstring hostname;
316         char *p;
317
318         *hostname = 0;
319         /* get my host name */
320         if (gethostname(hostname, sizeof(hostname)) == -1) {
321                 DEBUG(0,("gethostname failed\n"));
322                 return False;
323         } 
324
325         /* Ensure null termination. */
326         hostname[sizeof(hostname)-1] = '\0';
327
328         p = strchr_m(hostname, '.');
329
330         if (!p)
331                 return False;
332
333         p++;
334         
335         if (my_domname)
336                 fstrcpy(my_domname, p);
337
338         return True;
339 }
340
341 /****************************************************************************
342  Interpret a protocol description string, with a default.
343 ****************************************************************************/
344
345 int interpret_protocol(char *str,int def)
346 {
347         if (strequal(str,"NT1"))
348                 return(PROTOCOL_NT1);
349         if (strequal(str,"LANMAN2"))
350                 return(PROTOCOL_LANMAN2);
351         if (strequal(str,"LANMAN1"))
352                 return(PROTOCOL_LANMAN1);
353         if (strequal(str,"CORE"))
354                 return(PROTOCOL_CORE);
355         if (strequal(str,"COREPLUS"))
356                 return(PROTOCOL_COREPLUS);
357         if (strequal(str,"CORE+"))
358                 return(PROTOCOL_COREPLUS);
359   
360         DEBUG(0,("Unrecognised protocol level %s\n",str));
361   
362         return(def);
363 }
364
365 /****************************************************************************
366  Return true if a string could be a pure IP address.
367 ****************************************************************************/
368
369 BOOL is_ipaddress(const char *str)
370 {
371         BOOL pure_address = True;
372         int i;
373   
374         for (i=0; pure_address && str[i]; i++)
375                 if (!(isdigit((int)str[i]) || str[i] == '.'))
376                         pure_address = False;
377
378         /* Check that a pure number is not misinterpreted as an IP */
379         pure_address = pure_address && (strchr_m(str, '.') != NULL);
380
381         return pure_address;
382 }
383
384 /****************************************************************************
385  Interpret an internet address or name into an IP address in 4 byte form.
386 ****************************************************************************/
387 uint32_t interpret_addr(const char *str)
388 {
389         struct hostent *hp;
390         uint32_t res;
391
392         if (str == NULL || 
393             strcmp(str,"0.0.0.0") == 0) {
394                 return 0;
395         }
396         if (strcmp(str,"255.255.255.255") == 0) {
397                 return 0xFFFFFFFF;
398         }
399
400         /* if it's in the form of an IP address then get the lib to interpret it */
401         if (is_ipaddress(str)) {
402                 res = sys_inet_addr(str);
403         } else {
404                 /* otherwise assume it's a network name of some sort and use 
405                         sys_gethostbyname */
406                 if ((hp = sys_gethostbyname(str)) == 0) {
407                         DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
408                         return 0;
409                 }
410
411                 if(hp->h_addr == NULL) {
412                         DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
413                         return 0;
414                 }
415                 putip((char *)&res,(char *)hp->h_addr);
416         }
417
418         if (res == (uint32_t)-1)
419                 return(0);
420
421         return(res);
422 }
423
424 /*******************************************************************
425  A convenient addition to interpret_addr().
426 ******************************************************************/
427 struct ipv4_addr interpret_addr2(const char *str)
428 {
429         struct ipv4_addr ret;
430         uint32_t a = interpret_addr(str);
431         ret.addr = a;
432         return ret;
433 }
434
435 /*******************************************************************
436  Check if an IP is the 0.0.0.0.
437 ******************************************************************/
438
439 BOOL is_zero_ip(struct ipv4_addr ip)
440 {
441         uint32_t a;
442         putip((char *)&a,(char *)&ip);
443         return(a == 0);
444 }
445
446 /*******************************************************************
447  Set an IP to 0.0.0.0.
448 ******************************************************************/
449
450 void zero_ip(struct ipv4_addr *ip)
451 {
452         *ip = sys_inet_makeaddr(0,0);
453         return;
454 }
455
456
457 /*******************************************************************
458  Are two IPs on the same subnet?
459 ********************************************************************/
460
461 BOOL same_net(struct ipv4_addr ip1,struct ipv4_addr ip2,struct ipv4_addr mask)
462 {
463         uint32_t net1,net2,nmask;
464
465         nmask = ntohl(mask.addr);
466         net1  = ntohl(ip1.addr);
467         net2  = ntohl(ip2.addr);
468             
469         return((net1 & nmask) == (net2 & nmask));
470 }
471
472
473 /****************************************************************************
474  Check if a process exists. Does this work on all unixes?
475 ****************************************************************************/
476
477 BOOL process_exists(pid_t pid)
478 {
479         /* Doing kill with a non-positive pid causes messages to be
480          * sent to places we don't want. */
481         SMB_ASSERT(pid > 0);
482         return(kill(pid,0) == 0 || errno != ESRCH);
483 }
484
485 /****************************************************************************
486  Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
487  is dealt with in posix.c
488 ****************************************************************************/
489
490 BOOL fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
491 {
492         struct flock lock;
493         int ret;
494
495         DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
496
497         lock.l_type = type;
498         lock.l_whence = SEEK_SET;
499         lock.l_start = offset;
500         lock.l_len = count;
501         lock.l_pid = 0;
502
503         ret = fcntl(fd,op,&lock);
504
505         if (ret == -1 && errno != 0)
506                 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
507
508         /* a lock query */
509         if (op == F_GETLK) {
510                 if ((ret != -1) &&
511                                 (lock.l_type != F_UNLCK) && 
512                                 (lock.l_pid != 0) && 
513                                 (lock.l_pid != getpid())) {
514                         DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
515                         return(True);
516                 }
517
518                 /* it must be not locked or locked by me */
519                 return(False);
520         }
521
522         /* a lock set or unset */
523         if (ret == -1) {
524                 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
525                         (double)offset,(double)count,op,type,strerror(errno)));
526                 return(False);
527         }
528
529         /* everything went OK */
530         DEBUG(8,("fcntl_lock: Lock call successful\n"));
531
532         return(True);
533 }
534
535
536 static void print_asc(int level, const uint8_t *buf,int len)
537 {
538         int i;
539         for (i=0;i<len;i++)
540                 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
541 }
542
543 void dump_data(int level, const uint8_t *buf,int len)
544 {
545         int i=0;
546         if (len<=0) return;
547
548         if (!DEBUGLVL(level)) return;
549         
550         DEBUGADD(level,("[%03X] ",i));
551         for (i=0;i<len;) {
552                 DEBUGADD(level,("%02X ",(int)buf[i]));
553                 i++;
554                 if (i%8 == 0) DEBUGADD(level,(" "));
555                 if (i%16 == 0) {      
556                         print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
557                         print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
558                         if (i<len) DEBUGADD(level,("[%03X] ",i));
559                 }
560         }
561         if (i%16) {
562                 int n;
563                 n = 16 - (i%16);
564                 DEBUGADD(level,(" "));
565                 if (n>8) DEBUGADD(level,(" "));
566                 while (n--) DEBUGADD(level,("   "));
567                 n = MIN(8,i%16);
568                 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
569                 n = (i%16) - n;
570                 if (n>0) print_asc(level,&buf[i-n],n); 
571                 DEBUGADD(level,("\n"));    
572         }       
573 }
574
575 /*****************************************************************
576  Possibly replace mkstemp if it is broken.
577 *****************************************************************/  
578
579 int smb_mkstemp(char *template)
580 {
581 #if HAVE_SECURE_MKSTEMP
582         return mkstemp(template);
583 #else
584         /* have a reasonable go at emulating it. Hope that
585            the system mktemp() isn't completly hopeless */
586         char *p = mktemp(template);
587         if (!p)
588                 return -1;
589         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
590 #endif
591 }
592
593 /*****************************************************************
594  malloc that aborts with smb_panic on fail or zero size.
595  *****************************************************************/  
596
597 void *smb_xmalloc(size_t size)
598 {
599         void *p;
600         if (size == 0)
601                 smb_panic("smb_xmalloc: called with zero size.\n");
602         if ((p = malloc(size)) == NULL)
603                 smb_panic("smb_xmalloc: malloc fail.\n");
604         return p;
605 }
606
607 /**
608  Memdup with smb_panic on fail.
609 **/
610
611 void *smb_xmemdup(const void *p, size_t size)
612 {
613         void *p2;
614         p2 = smb_xmalloc(size);
615         memcpy(p2, p, size);
616         return p2;
617 }
618
619 /**
620  strdup that aborts on malloc fail.
621 **/
622
623 char *smb_xstrdup(const char *s)
624 {
625         char *s1 = strdup(s);
626         if (!s1)
627                 smb_panic("smb_xstrdup: malloc fail\n");
628         return s1;
629 }
630
631
632 /*****************************************************************
633  Like strdup but for memory.
634 *****************************************************************/  
635
636 void *memdup(const void *p, size_t size)
637 {
638         void *p2;
639         if (size == 0)
640                 return NULL;
641         p2 = malloc(size);
642         if (!p2)
643                 return NULL;
644         memcpy(p2, p, size);
645         return p2;
646 }
647
648 /*****************************************************************
649  Get local hostname and cache result.
650 *****************************************************************/  
651
652 char *myhostname(TALLOC_CTX *mem_ctx)
653 {
654         char *myname, *ret;
655         myname = get_myname();
656         ret = talloc_strdup(mem_ctx, myname);
657         free(myname);
658         return ret;
659
660 }
661
662 /**********************************************************************
663  Converts a name to a fully qalified domain name.
664 ***********************************************************************/
665
666 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
667 {
668         struct hostent *hp = sys_gethostbyname(name);
669         if ( hp && hp->h_name && *hp->h_name ) {
670                 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
671                 return talloc_strdup(mem_ctx, hp->h_name);
672         } else {
673                 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
674                 return talloc_strdup(mem_ctx, name);
675         }
676 }
677
678
679 /*****************************************************************
680  A useful function for returning a path in the Samba lock directory.
681 *****************************************************************/  
682 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
683 {
684         char *fname, *dname;
685
686         dname = talloc_strdup(mem_ctx, lp_lockdir());
687         trim_string(dname,"","/");
688         
689         if (!directory_exist(dname,NULL)) {
690                 mkdir(dname,0755);
691         }
692         
693         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
694
695         talloc_free(dname);
696
697         return fname;
698 }
699
700 /**
701  * @brief Returns an absolute path to a file in the Samba lib directory.
702  *
703  * @param name File to find, relative to LIBDIR.
704  *
705  * @retval Pointer to a talloc'ed string containing the full path.
706  **/
707
708 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
709 {
710         char *fname;
711         fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
712         return fname;
713 }
714
715 /*
716   return a path in the smbd.tmp directory, where all temporary file
717   for smbd go. If NULL is passed for name then return the directory 
718   path itself
719 */
720 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
721 {
722         char *fname, *dname;
723
724         dname = lock_path(mem_ctx, "smbd.tmp");
725         if (!directory_exist(dname,NULL)) {
726                 mkdir(dname,0755);
727         }
728
729         if (name == NULL) {
730                 return dname;
731         }
732
733         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
734         talloc_free(dname);
735
736         return fname;
737 }
738
739 /**
740  * @brief Returns the platform specific shared library extension.
741  *
742  * @retval Pointer to a static #fstring containing the extension.
743  **/
744
745 const char *shlib_ext(void)
746 {
747   return dyn_SHLIBEXT;
748 }
749
750
751 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
752 {
753 #ifdef DEBUG_PASSWORD
754         DEBUG(11, ("%s", msg));
755         if (data != NULL && len > 0)
756         {
757                 dump_data(11, data, len);
758         }
759 #endif
760 }
761
762
763 /* see if a range of memory is all zero. A NULL pointer is considered
764    to be all zero */
765 BOOL all_zero(const uint8_t *ptr, uint_t size)
766 {
767         int i;
768         if (!ptr) return True;
769         for (i=0;i<size;i++) {
770                 if (ptr[i]) return False;
771         }
772         return True;
773 }
774
775 /*
776   realloc an array, checking for integer overflow in the array size
777 */
778 void *realloc_array(void *ptr, size_t el_size, unsigned count)
779 {
780 #define MAX_MALLOC_SIZE 0x7fffffff
781         if (count == 0 ||
782             count >= MAX_MALLOC_SIZE/el_size) {
783                 return NULL;
784         }
785         if (!ptr) {
786                 return malloc(el_size * count);
787         }
788         return realloc(ptr, el_size * count);
789 }
790