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