r9702: r9680@blu: tridge | 2005-08-27 18:45:08 +1000
[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/dir.h"
30 #include "system/filesys.h"
31
32 /***************************************************************************
33  Find a suitable temporary directory. The result should be copied immediately
34  as it may be overwritten by a subsequent call.
35 ****************************************************************************/
36 const char *tmpdir(void)
37 {
38         char *p;
39         if ((p = getenv("TMPDIR")))
40                 return p;
41         return "/tmp";
42 }
43
44
45 /*******************************************************************
46  Check if a file exists - call vfs_file_exist for samba files.
47 ********************************************************************/
48 BOOL file_exist(const char *fname)
49 {
50         struct stat st;
51
52         if (stat(fname, &st) != 0) {
53                 return False;
54         }
55
56         return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
57 }
58
59 /*******************************************************************
60  Check a files mod time.
61 ********************************************************************/
62
63 time_t file_modtime(const char *fname)
64 {
65         struct stat st;
66   
67         if (stat(fname,&st) != 0) 
68                 return(0);
69
70         return(st.st_mtime);
71 }
72
73 /*******************************************************************
74  Check if a directory exists.
75 ********************************************************************/
76
77 BOOL directory_exist(const char *dname)
78 {
79         struct stat st;
80         BOOL ret;
81
82         if (stat(dname,&st) != 0) {
83                 return False;
84         }
85
86         ret = S_ISDIR(st.st_mode);
87         if(!ret)
88                 errno = ENOTDIR;
89         return ret;
90 }
91
92 /*******************************************************************
93  Returns the size in bytes of the named file.
94 ********************************************************************/
95 off_t get_file_size(char *file_name)
96 {
97         struct stat buf;
98         buf.st_size = 0;
99         if(stat(file_name,&buf) != 0)
100                 return (off_t)-1;
101         return(buf.st_size);
102 }
103
104 /*******************************************************************
105  Close the low 3 fd's and open dev/null in their place.
106 ********************************************************************/
107 void close_low_fds(BOOL stderr_too)
108 {
109 #ifndef VALGRIND
110         int fd;
111         int i;
112
113         close(0);
114         close(1); 
115
116         if (stderr_too)
117                 close(2);
118
119         /* try and use up these file descriptors, so silly
120                 library routines writing to stdout etc won't cause havoc */
121         for (i=0;i<3;i++) {
122                 if (i == 2 && !stderr_too)
123                         continue;
124
125                 fd = open("/dev/null",O_RDWR,0);
126                 if (fd < 0)
127                         fd = open("/dev/null",O_WRONLY,0);
128                 if (fd < 0) {
129                         DEBUG(0,("Can't open /dev/null\n"));
130                         return;
131                 }
132                 if (fd != i) {
133                         DEBUG(0,("Didn't get file descriptor %d\n",i));
134                         return;
135                 }
136         }
137 #endif
138 }
139
140 /****************************************************************************
141  Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
142  else
143   if SYSV use O_NDELAY
144   if BSD use FNDELAY
145 ****************************************************************************/
146
147 int set_blocking(int fd, BOOL set)
148 {
149         int val;
150 #ifdef O_NONBLOCK
151 #define FLAG_TO_SET O_NONBLOCK
152 #else
153 #ifdef SYSV
154 #define FLAG_TO_SET O_NDELAY
155 #else /* BSD */
156 #define FLAG_TO_SET FNDELAY
157 #endif
158 #endif
159
160         if((val = fcntl(fd, F_GETFL, 0)) == -1)
161                 return -1;
162         if(set) /* Turn blocking on - ie. clear nonblock flag */
163                 val &= ~FLAG_TO_SET;
164         else
165                 val |= FLAG_TO_SET;
166         return fcntl( fd, F_SETFL, val);
167 #undef FLAG_TO_SET
168 }
169
170
171 /*******************************************************************
172  Sleep for a specified number of milliseconds.
173 ********************************************************************/
174
175 void msleep(uint_t t)
176 {
177         struct timeval tval;  
178
179         tval.tv_sec = t/1000;
180         tval.tv_usec = 1000*(t%1000);
181         /* this should be the real select - do NOT replace
182            with sys_select() */
183         select(0,NULL,NULL,NULL,&tval);
184 }
185
186 /****************************************************************************
187  Become a daemon, discarding the controlling terminal.
188 ****************************************************************************/
189
190 void become_daemon(BOOL Fork)
191 {
192         if (Fork) {
193                 if (fork()) {
194                         _exit(0);
195                 }
196         }
197
198   /* detach from the terminal */
199 #ifdef HAVE_SETSID
200         setsid();
201 #elif defined(TIOCNOTTY)
202         {
203                 int i = open("/dev/tty", O_RDWR, 0);
204                 if (i != -1) {
205                         ioctl(i, (int) TIOCNOTTY, (char *)0);      
206                         close(i);
207                 }
208         }
209 #endif /* HAVE_SETSID */
210
211         /* Close fd's 0,1,2. Needed if started by rsh */
212         close_low_fds(False);  /* Don't close stderr, let the debug system
213                                   attach it to the logfile */
214 }
215
216
217 /****************************************************************************
218  Free memory, checks for NULL.
219  Use directly SAFE_FREE()
220  Exists only because we need to pass a function pointer somewhere --SSS
221 ****************************************************************************/
222
223 void safe_free(void *p)
224 {
225         SAFE_FREE(p);
226 }
227
228
229 /*
230   see if a string matches either our primary or one of our secondary 
231   netbios aliases. do a case insensitive match
232 */
233 BOOL is_myname(const char *name)
234 {
235         const char **aliases;
236         int i;
237
238         if (strcasecmp(name, lp_netbios_name()) == 0) {
239                 return True;
240         }
241
242         aliases = lp_netbios_aliases();
243         for (i=0; aliases && aliases[i]; i++) {
244                 if (strcasecmp(name, aliases[i]) == 0) {
245                         return True;
246                 }
247         }
248
249         return False;
250 }
251
252
253 /****************************************************************************
254  Get my own name, return in malloc'ed storage.
255 ****************************************************************************/
256
257 char* get_myname(void)
258 {
259         char *hostname;
260         const int host_name_max = 255;
261         char *p;
262
263         hostname = malloc(host_name_max+1);
264         *hostname = 0;
265
266         /* get my host name */
267         if (gethostname(hostname, host_name_max+1) == -1) {
268                 DEBUG(0,("gethostname failed\n"));
269                 return NULL;
270         } 
271
272         /* Ensure null termination. */
273         hostname[host_name_max] = '\0';
274
275         /* split off any parts after an initial . */
276         p = strchr_m(hostname,'.');
277
278         if (p)
279                 *p = 0;
280         
281         return hostname;
282 }
283
284 /****************************************************************************
285  Interpret a protocol description string, with a default.
286 ****************************************************************************/
287
288 int interpret_protocol(char *str,int def)
289 {
290         if (strequal(str,"NT1"))
291                 return(PROTOCOL_NT1);
292         if (strequal(str,"LANMAN2"))
293                 return(PROTOCOL_LANMAN2);
294         if (strequal(str,"LANMAN1"))
295                 return(PROTOCOL_LANMAN1);
296         if (strequal(str,"CORE"))
297                 return(PROTOCOL_CORE);
298         if (strequal(str,"COREPLUS"))
299                 return(PROTOCOL_COREPLUS);
300         if (strequal(str,"CORE+"))
301                 return(PROTOCOL_COREPLUS);
302   
303         DEBUG(0,("Unrecognised protocol level %s\n",str));
304   
305         return(def);
306 }
307
308 /****************************************************************************
309  Return true if a string could be a pure IP address.
310 ****************************************************************************/
311
312 BOOL is_ipaddress(const char *str)
313 {
314         BOOL pure_address = True;
315         int i;
316   
317         for (i=0; pure_address && str[i]; i++)
318                 if (!(isdigit((int)str[i]) || str[i] == '.'))
319                         pure_address = False;
320
321         /* Check that a pure number is not misinterpreted as an IP */
322         pure_address = pure_address && (strchr_m(str, '.') != NULL);
323
324         return pure_address;
325 }
326
327 /****************************************************************************
328  Interpret an internet address or name into an IP address in 4 byte form.
329 ****************************************************************************/
330 uint32_t interpret_addr(const char *str)
331 {
332         struct hostent *hp;
333         uint32_t res;
334
335         if (str == NULL || *str == 0 ||
336             strcmp(str,"0.0.0.0") == 0) {
337                 return 0;
338         }
339         if (strcmp(str,"255.255.255.255") == 0) {
340                 return 0xFFFFFFFF;
341         }
342         /* recognise 'localhost' as a special name. This fixes problems with
343            some hosts that don't have localhost in /etc/hosts */
344         if (strcmp(str,"localhost") == 0) {
345                 str = "127.0.0.1";
346         }
347
348         /* if it's in the form of an IP address then get the lib to interpret it */
349         if (is_ipaddress(str)) {
350                 res = sys_inet_addr(str);
351         } else {
352                 /* otherwise assume it's a network name of some sort and use 
353                         sys_gethostbyname */
354                 if ((hp = sys_gethostbyname(str)) == 0) {
355                         DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
356                         return 0;
357                 }
358
359                 if(hp->h_addr == NULL) {
360                         DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
361                         return 0;
362                 }
363                 memcpy((char *)&res,(char *)hp->h_addr, 4);
364         }
365
366         if (res == (uint32_t)-1)
367                 return(0);
368
369         return(res);
370 }
371
372 /*******************************************************************
373  A convenient addition to interpret_addr().
374 ******************************************************************/
375 struct ipv4_addr interpret_addr2(const char *str)
376 {
377         struct ipv4_addr ret;
378         uint32_t a = interpret_addr(str);
379         ret.addr = a;
380         return ret;
381 }
382
383 /*******************************************************************
384  Check if an IP is the 0.0.0.0.
385 ******************************************************************/
386
387 BOOL is_zero_ip(struct ipv4_addr ip)
388 {
389         return ip.addr == 0;
390 }
391
392 /*******************************************************************
393  Set an IP to 0.0.0.0.
394 ******************************************************************/
395
396 void zero_ip(struct ipv4_addr *ip)
397 {
398         *ip = sys_inet_makeaddr(0,0);
399         return;
400 }
401
402
403 /*******************************************************************
404  Are two IPs on the same subnet?
405 ********************************************************************/
406
407 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 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 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 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  Possibly replace mkstemp if it is broken.
523 *****************************************************************/  
524
525 int smb_mkstemp(char *template)
526 {
527 #if HAVE_SECURE_MKSTEMP
528         return mkstemp(template);
529 #else
530         /* have a reasonable go at emulating it. Hope that
531            the system mktemp() isn't completly hopeless */
532         char *p = mktemp(template);
533         if (!p)
534                 return -1;
535         return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
536 #endif
537 }
538
539 /*****************************************************************
540  malloc that aborts with smb_panic on fail or zero size.
541  *****************************************************************/  
542
543 void *smb_xmalloc(size_t size)
544 {
545         void *p;
546         if (size == 0)
547                 smb_panic("smb_xmalloc: called with zero size.\n");
548         if ((p = malloc(size)) == NULL)
549                 smb_panic("smb_xmalloc: malloc fail.\n");
550         return p;
551 }
552
553 /**
554  Memdup with smb_panic on fail.
555 **/
556
557 void *smb_xmemdup(const void *p, size_t size)
558 {
559         void *p2;
560         p2 = smb_xmalloc(size);
561         memcpy(p2, p, size);
562         return p2;
563 }
564
565 /**
566  strdup that aborts on malloc fail.
567 **/
568
569 char *smb_xstrdup(const char *s)
570 {
571         char *s1 = strdup(s);
572         if (!s1)
573                 smb_panic("smb_xstrdup: malloc fail\n");
574         return s1;
575 }
576
577
578 /*****************************************************************
579  Like strdup but for memory.
580 *****************************************************************/  
581
582 void *memdup(const void *p, size_t size)
583 {
584         void *p2;
585         if (size == 0)
586                 return NULL;
587         p2 = malloc(size);
588         if (!p2)
589                 return NULL;
590         memcpy(p2, p, size);
591         return p2;
592 }
593
594 /*****************************************************************
595  Get local hostname and cache result.
596 *****************************************************************/  
597
598 char *myhostname(TALLOC_CTX *mem_ctx)
599 {
600         char *myname, *ret;
601         myname = get_myname();
602         ret = talloc_strdup(mem_ctx, myname);
603         free(myname);
604         return ret;
605
606 }
607
608 /**********************************************************************
609  Converts a name to a fully qalified domain name.
610 ***********************************************************************/
611
612 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
613 {
614         struct hostent *hp = sys_gethostbyname(name);
615         if ( hp && hp->h_name && *hp->h_name ) {
616                 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
617                 return talloc_strdup(mem_ctx, hp->h_name);
618         } else {
619                 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
620                 return talloc_strdup(mem_ctx, name);
621         }
622 }
623
624
625 /*****************************************************************
626  A useful function for returning a path in the Samba lock directory.
627 *****************************************************************/  
628 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
629 {
630         char *fname, *dname;
631
632         dname = talloc_strdup(mem_ctx, lp_lockdir());
633         trim_string(dname,"","/");
634         
635         if (!directory_exist(dname)) {
636                 mkdir(dname,0755);
637         }
638         
639         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
640
641         talloc_free(dname);
642
643         return fname;
644 }
645
646 /**
647  * @brief Returns an absolute path to a file in the Samba lib directory.
648  *
649  * @param name File to find, relative to LIBDIR.
650  *
651  * @retval Pointer to a talloc'ed string containing the full path.
652  **/
653
654 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
655 {
656         char *fname;
657         fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
658         return fname;
659 }
660
661 /**
662  * @brief Returns an absolute path to a file in the Samba private directory.
663  *
664  * @param name File to find, relative to PRIVATEDIR.
665  * if name is not relative, then use it as-is
666  *
667  * @retval Pointer to a talloc'ed string containing the full path.
668  **/
669 char *private_path(TALLOC_CTX* mem_ctx, const char *name)
670 {
671         char *fname;
672         if (name == NULL) {
673                 return NULL;
674         }
675         if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
676                 return talloc_strdup(mem_ctx, name);
677         }
678         fname = talloc_asprintf(mem_ctx, "%s/%s", lp_private_dir(), name);
679         return fname;
680 }
681
682 /*
683   return a path in the smbd.tmp directory, where all temporary file
684   for smbd go. If NULL is passed for name then return the directory 
685   path itself
686 */
687 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
688 {
689         char *fname, *dname;
690
691         dname = lock_path(mem_ctx, "smbd.tmp");
692         if (!directory_exist(dname)) {
693                 mkdir(dname,0755);
694         }
695
696         if (name == NULL) {
697                 return dname;
698         }
699
700         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
701         talloc_free(dname);
702
703         return fname;
704 }
705
706 /**
707  * @brief Returns the platform specific shared library extension.
708  *
709  * @retval Pointer to a static #fstring containing the extension.
710  **/
711
712 const char *shlib_ext(void)
713 {
714   return dyn_SHLIBEXT;
715 }
716
717
718 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
719 {
720 #ifdef DEBUG_PASSWORD
721         DEBUG(11, ("%s", msg));
722         if (data != NULL && len > 0)
723         {
724                 dump_data(11, data, len);
725         }
726 #endif
727 }
728
729
730 /* see if a range of memory is all zero. A NULL pointer is considered
731    to be all zero */
732 BOOL all_zero(const uint8_t *ptr, uint_t size)
733 {
734         int i;
735         if (!ptr) return True;
736         for (i=0;i<size;i++) {
737                 if (ptr[i]) return False;
738         }
739         return True;
740 }
741
742 /*
743   realloc an array, checking for integer overflow in the array size
744 */
745 void *realloc_array(void *ptr, size_t el_size, unsigned count)
746 {
747 #define MAX_MALLOC_SIZE 0x7fffffff
748         if (count == 0 ||
749             count >= MAX_MALLOC_SIZE/el_size) {
750                 return NULL;
751         }
752         if (!ptr) {
753                 return malloc(el_size * count);
754         }
755         return realloc(ptr, el_size * count);
756 }
757