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
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.
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.
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.
26 #include "system/network.h"
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)
35 if ((p = getenv("TMPDIR")))
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)
50 if (stat(fname,sbuf) != 0)
53 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
56 /*******************************************************************
57 Check a files mod time.
58 ********************************************************************/
60 time_t file_modtime(const char *fname)
64 if (stat(fname,&st) != 0)
70 /*******************************************************************
71 Check if a directory exists.
72 ********************************************************************/
74 BOOL directory_exist(const char *dname,struct stat *st)
82 if (stat(dname,st) != 0)
85 ret = S_ISDIR(st->st_mode);
91 /*******************************************************************
92 Returns the size in bytes of the named file.
93 ********************************************************************/
94 off_t get_file_size(char *file_name)
98 if(stat(file_name,&buf) != 0)
103 /*******************************************************************
104 Close the low 3 fd's and open dev/null in their place.
105 ********************************************************************/
106 void close_low_fds(BOOL stderr_too)
118 /* try and use up these file descriptors, so silly
119 library routines writing to stdout etc won't cause havoc */
121 if (i == 2 && !stderr_too)
124 fd = open("/dev/null",O_RDWR,0);
126 fd = open("/dev/null",O_WRONLY,0);
128 DEBUG(0,("Can't open /dev/null\n"));
132 DEBUG(0,("Didn't get file descriptor %d\n",i));
139 /****************************************************************************
140 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
144 ****************************************************************************/
146 int set_blocking(int fd, BOOL set)
150 #define FLAG_TO_SET O_NONBLOCK
153 #define FLAG_TO_SET O_NDELAY
155 #define FLAG_TO_SET FNDELAY
159 if((val = fcntl(fd, F_GETFL, 0)) == -1)
161 if(set) /* Turn blocking on - ie. clear nonblock flag */
165 return fcntl( fd, F_SETFL, val);
170 /*******************************************************************
171 Sleep for a specified number of milliseconds.
172 ********************************************************************/
174 void msleep(uint_t t)
178 tval.tv_sec = t/1000;
179 tval.tv_usec = 1000*(t%1000);
180 /* this should be the real select - do NOT replace
182 select(0,NULL,NULL,NULL,&tval);
185 /****************************************************************************
186 Become a daemon, discarding the controlling terminal.
187 ****************************************************************************/
189 void become_daemon(BOOL Fork)
197 /* detach from the terminal */
200 #elif defined(TIOCNOTTY)
202 int i = open("/dev/tty", O_RDWR, 0);
204 ioctl(i, (int) TIOCNOTTY, (char *)0);
208 #endif /* HAVE_SETSID */
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 */
216 /****************************************************************************
217 Expand a pointer to be a particular size.
218 ****************************************************************************/
220 void *Realloc(void *p,size_t size)
226 DEBUG(5,("Realloc asked for 0 bytes\n"));
231 ret = (void *)malloc(size);
233 ret = (void *)realloc(p,size);
236 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
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 ****************************************************************************/
247 void safe_free(void *p)
254 see if a string matches either our primary or one of our secondary
255 netbios aliases. do a case insensitive match
257 BOOL is_myname(const char *name)
259 const char **aliases;
262 if (strcasecmp(name, lp_netbios_name()) == 0) {
266 aliases = lp_netbios_aliases();
267 for (i=0; aliases && aliases[i]; i++) {
268 if (strcasecmp(name, aliases[i]) == 0) {
277 /****************************************************************************
278 Get my own name, return in malloc'ed storage.
279 ****************************************************************************/
281 char* get_myname(void)
284 const int host_name_max = 255;
287 hostname = malloc(host_name_max+1);
290 /* get my host name */
291 if (gethostname(hostname, host_name_max+1) == -1) {
292 DEBUG(0,("gethostname failed\n"));
296 /* Ensure null termination. */
297 hostname[host_name_max] = '\0';
299 /* split off any parts after an initial . */
300 p = strchr_m(hostname,'.');
308 /****************************************************************************
309 Get my own name, including domain.
310 ****************************************************************************/
312 BOOL get_myfullname(char *my_name)
318 /* get my host name */
319 if (gethostname(hostname, sizeof(hostname)) == -1) {
320 DEBUG(0,("gethostname failed\n"));
324 /* Ensure null termination. */
325 hostname[sizeof(hostname)-1] = '\0';
328 fstrcpy(my_name, hostname);
332 /****************************************************************************
333 Get my own domain name.
334 ****************************************************************************/
336 BOOL get_mydomname(fstring my_domname)
342 /* get my host name */
343 if (gethostname(hostname, sizeof(hostname)) == -1) {
344 DEBUG(0,("gethostname failed\n"));
348 /* Ensure null termination. */
349 hostname[sizeof(hostname)-1] = '\0';
351 p = strchr_m(hostname, '.');
359 fstrcpy(my_domname, p);
364 /****************************************************************************
365 Interpret a protocol description string, with a default.
366 ****************************************************************************/
368 int interpret_protocol(char *str,int def)
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);
383 DEBUG(0,("Unrecognised protocol level %s\n",str));
388 /****************************************************************************
389 Return true if a string could be a pure IP address.
390 ****************************************************************************/
392 BOOL is_ipaddress(const char *str)
394 BOOL pure_address = True;
397 for (i=0; pure_address && str[i]; i++)
398 if (!(isdigit((int)str[i]) || str[i] == '.'))
399 pure_address = False;
401 /* Check that a pure number is not misinterpreted as an IP */
402 pure_address = pure_address && (strchr_m(str, '.') != NULL);
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)
416 strcmp(str,"0.0.0.0") == 0) {
419 if (strcmp(str,"255.255.255.255") == 0) {
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);
427 /* otherwise assume it's a network name of some sort and use
429 if ((hp = sys_gethostbyname(str)) == 0) {
430 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
434 if(hp->h_addr == NULL) {
435 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
438 putip((char *)&res,(char *)hp->h_addr);
441 if (res == (uint32_t)-1)
447 /*******************************************************************
448 A convenient addition to interpret_addr().
449 ******************************************************************/
450 struct ipv4_addr interpret_addr2(const char *str)
452 struct ipv4_addr ret;
453 uint32_t a = interpret_addr(str);
458 /*******************************************************************
459 Check if an IP is the 0.0.0.0.
460 ******************************************************************/
462 BOOL is_zero_ip(struct ipv4_addr ip)
465 putip((char *)&a,(char *)&ip);
469 /*******************************************************************
470 Set an IP to 0.0.0.0.
471 ******************************************************************/
473 void zero_ip(struct ipv4_addr *ip)
475 *ip = sys_inet_makeaddr(0,0);
480 /*******************************************************************
481 Are two IPs on the same subnet?
482 ********************************************************************/
484 BOOL same_net(struct ipv4_addr ip1,struct ipv4_addr ip2,struct ipv4_addr mask)
486 uint32_t net1,net2,nmask;
488 nmask = ntohl(mask.s_addr);
489 net1 = ntohl(ip1.s_addr);
490 net2 = ntohl(ip2.s_addr);
492 return((net1 & nmask) == (net2 & nmask));
496 /****************************************************************************
497 Check if a process exists. Does this work on all unixes?
498 ****************************************************************************/
500 BOOL process_exists(pid_t pid)
502 /* Doing kill with a non-positive pid causes messages to be
503 * sent to places we don't want. */
505 return(kill(pid,0) == 0 || errno != ESRCH);
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 ****************************************************************************/
513 BOOL fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
518 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
521 lock.l_whence = SEEK_SET;
522 lock.l_start = offset;
526 ret = fcntl(fd,op,&lock);
528 if (ret == -1 && errno != 0)
529 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
534 (lock.l_type != F_UNLCK) &&
536 (lock.l_pid != getpid())) {
537 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
541 /* it must be not locked or locked by me */
545 /* a lock set or unset */
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)));
552 /* everything went OK */
553 DEBUG(8,("fcntl_lock: Lock call successful\n"));
559 static void print_asc(int level, const uint8_t *buf,int len)
563 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
566 void dump_data(int level, const char *buf1,int len)
568 const uint8_t *buf = (const uint8_t *)buf1;
572 if (!DEBUGLVL(level)) return;
574 DEBUGADD(level,("[%03X] ",i));
576 DEBUGADD(level,("%02X ",(int)buf[i]));
578 if (i%8 == 0) DEBUGADD(level,(" "));
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));
588 DEBUGADD(level,(" "));
589 if (n>8) DEBUGADD(level,(" "));
590 while (n--) DEBUGADD(level,(" "));
592 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
594 if (n>0) print_asc(level,&buf[i-n],n);
595 DEBUGADD(level,("\n"));
599 /*****************************************************************
600 Possibly replace mkstemp if it is broken.
601 *****************************************************************/
603 int smb_mkstemp(char *template)
605 #if HAVE_SECURE_MKSTEMP
606 return mkstemp(template);
608 /* have a reasonable go at emulating it. Hope that
609 the system mktemp() isn't completly hopeless */
610 char *p = mktemp(template);
613 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
617 /*****************************************************************
618 malloc that aborts with smb_panic on fail or zero size.
619 *****************************************************************/
621 void *smb_xmalloc(size_t size)
625 smb_panic("smb_xmalloc: called with zero size.\n");
626 if ((p = malloc(size)) == NULL)
627 smb_panic("smb_xmalloc: malloc fail.\n");
632 Memdup with smb_panic on fail.
635 void *smb_xmemdup(const void *p, size_t size)
638 p2 = smb_xmalloc(size);
644 strdup that aborts on malloc fail.
647 char *smb_xstrdup(const char *s)
649 char *s1 = strdup(s);
651 smb_panic("smb_xstrdup: malloc fail\n");
656 /*****************************************************************
657 Like strdup but for memory.
658 *****************************************************************/
660 void *memdup(const void *p, size_t size)
672 /*****************************************************************
673 Get local hostname and cache result.
674 *****************************************************************/
676 char *myhostname(TALLOC_CTX *mem_ctx)
679 myname = get_myname();
680 ret = talloc_strdup(mem_ctx, myname);
686 /**********************************************************************
687 Converts a name to a fully qalified domain name.
688 ***********************************************************************/
690 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
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);
697 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
698 return talloc_strdup(mem_ctx, name);
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)
710 dname = talloc_strdup(mem_ctx, lp_lockdir());
711 trim_string(dname,"","/");
713 if (!directory_exist(dname,NULL)) {
717 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
725 * @brief Returns an absolute path to a file in the Samba lib directory.
727 * @param name File to find, relative to LIBDIR.
729 * @retval Pointer to a talloc'ed string containing the full path.
732 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
735 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
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
744 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
748 dname = lock_path(mem_ctx, "smbd.tmp");
749 if (!directory_exist(dname,NULL)) {
757 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
764 * @brief Returns the platform specific shared library extension.
766 * @retval Pointer to a static #fstring containing the extension.
769 const char *shlib_ext(void)
775 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
777 #ifdef DEBUG_PASSWORD
778 DEBUG(11, ("%s", msg));
779 if (data != NULL && len > 0)
781 dump_data(11, data, len);
787 /* see if a range of memory is all zero. A NULL pointer is considered
789 BOOL all_zero(const char *ptr, uint_t size)
792 if (!ptr) return True;
793 for (i=0;i<size;i++) {
794 if (ptr[i]) return False;