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