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