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