r12286: handle absolute path and url in lock_path() as in private_path()
[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 (strcasecmp(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 = 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  malloc that aborts with smb_panic on fail or zero size.
523  *****************************************************************/  
524
525 void *smb_xmalloc(size_t size)
526 {
527         void *p;
528         if (size == 0)
529                 smb_panic("smb_xmalloc: called with zero size.\n");
530         if ((p = malloc(size)) == NULL)
531                 smb_panic("smb_xmalloc: malloc fail.\n");
532         return p;
533 }
534
535 /**
536  Memdup with smb_panic on fail.
537 **/
538
539 void *smb_xmemdup(const void *p, size_t size)
540 {
541         void *p2;
542         p2 = smb_xmalloc(size);
543         memcpy(p2, p, size);
544         return p2;
545 }
546
547 /**
548  strdup that aborts on malloc fail.
549 **/
550
551 char *smb_xstrdup(const char *s)
552 {
553         char *s1 = strdup(s);
554         if (!s1)
555                 smb_panic("smb_xstrdup: malloc fail\n");
556         return s1;
557 }
558
559
560 /*****************************************************************
561  Like strdup but for memory.
562 *****************************************************************/  
563
564 void *memdup(const void *p, size_t size)
565 {
566         void *p2;
567         if (size == 0)
568                 return NULL;
569         p2 = malloc(size);
570         if (!p2)
571                 return NULL;
572         memcpy(p2, p, size);
573         return p2;
574 }
575
576 /*****************************************************************
577  Get local hostname and cache result.
578 *****************************************************************/  
579
580 char *myhostname(TALLOC_CTX *mem_ctx)
581 {
582         char *myname, *ret;
583         myname = get_myname();
584         ret = talloc_strdup(mem_ctx, myname);
585         free(myname);
586         return ret;
587
588 }
589
590 /**********************************************************************
591  Converts a name to a fully qalified domain name.
592 ***********************************************************************/
593
594 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
595 {
596         struct hostent *hp = sys_gethostbyname(name);
597         if ( hp && hp->h_name && *hp->h_name ) {
598                 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
599                 return talloc_strdup(mem_ctx, hp->h_name);
600         } else {
601                 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
602                 return talloc_strdup(mem_ctx, name);
603         }
604 }
605
606
607 /*****************************************************************
608  A useful function for returning a path in the Samba lock directory.
609 *****************************************************************/  
610 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
611 {
612         char *fname, *dname;
613         if (name == NULL) {
614                 return NULL;
615         }
616         if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
617                 return talloc_strdup(mem_ctx, name);
618         }
619
620         dname = talloc_strdup(mem_ctx, lp_lockdir());
621         trim_string(dname,"","/");
622         
623         if (!directory_exist(dname)) {
624                 mkdir(dname,0755);
625         }
626         
627         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
628
629         talloc_free(dname);
630
631         return fname;
632 }
633
634
635 /*****************************************************************
636  A useful function for returning a path in the Samba piddir directory.
637 *****************************************************************/  
638 char *pid_path(TALLOC_CTX* mem_ctx, const char *name)
639 {
640         char *fname, *dname;
641
642         dname = talloc_strdup(mem_ctx, lp_piddir());
643         trim_string(dname,"","/");
644         
645         if (!directory_exist(dname)) {
646                 mkdir(dname,0755);
647         }
648         
649         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
650
651         talloc_free(dname);
652
653         return fname;
654 }
655
656
657 /**
658  * @brief Returns an absolute path to a file in the Samba lib directory.
659  *
660  * @param name File to find, relative to LIBDIR.
661  *
662  * @retval Pointer to a talloc'ed string containing the full path.
663  **/
664
665 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
666 {
667         char *fname;
668         fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
669         return fname;
670 }
671
672 /**
673  * @brief Returns an absolute path to a file in the Samba private directory.
674  *
675  * @param name File to find, relative to PRIVATEDIR.
676  * if name is not relative, then use it as-is
677  *
678  * @retval Pointer to a talloc'ed string containing the full path.
679  **/
680 char *private_path(TALLOC_CTX* mem_ctx, const char *name)
681 {
682         char *fname;
683         if (name == NULL) {
684                 return NULL;
685         }
686         if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
687                 return talloc_strdup(mem_ctx, name);
688         }
689         fname = talloc_asprintf(mem_ctx, "%s/%s", lp_private_dir(), name);
690         return fname;
691 }
692
693 /*
694   return a path in the smbd.tmp directory, where all temporary file
695   for smbd go. If NULL is passed for name then return the directory 
696   path itself
697 */
698 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
699 {
700         char *fname, *dname;
701
702         dname = pid_path(mem_ctx, "smbd.tmp");
703         if (!directory_exist(dname)) {
704                 mkdir(dname,0755);
705         }
706
707         if (name == NULL) {
708                 return dname;
709         }
710
711         fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
712         talloc_free(dname);
713
714         return fname;
715 }
716
717 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
718 {
719 #ifdef DEBUG_PASSWORD
720         DEBUG(11, ("%s", msg));
721         if (data != NULL && len > 0)
722         {
723                 dump_data(11, data, len);
724         }
725 #endif
726 }
727
728
729 /* see if a range of memory is all zero. A NULL pointer is considered
730    to be all zero */
731 BOOL all_zero(const uint8_t *ptr, uint_t size)
732 {
733         int i;
734         if (!ptr) return True;
735         for (i=0;i<size;i++) {
736                 if (ptr[i]) return False;
737         }
738         return True;
739 }
740
741 /*
742   realloc an array, checking for integer overflow in the array size
743 */
744 void *realloc_array(void *ptr, size_t el_size, unsigned count)
745 {
746 #define MAX_MALLOC_SIZE 0x7fffffff
747         if (count == 0 ||
748             count >= MAX_MALLOC_SIZE/el_size) {
749                 return NULL;
750         }
751         if (!ptr) {
752                 return malloc(el_size * count);
753         }
754         return realloc(ptr, el_size * count);
755 }
756