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