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