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