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