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 "dynconfig.h"
27 #include "system/network.h"
28 #include "system/iconv.h"
30 /**************************************************************************n
31 Find a suitable temporary directory. The result should be copied immediately
32 as it may be overwritten by a subsequent call.
33 ****************************************************************************/
34 const char *tmpdir(void)
37 if ((p = getenv("TMPDIR")))
43 /*******************************************************************
44 Check if a file exists - call vfs_file_exist for samba files.
45 ********************************************************************/
46 BOOL file_exist(const char *fname, struct stat *sbuf)
52 if (stat(fname,sbuf) != 0)
55 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
58 /*******************************************************************
59 Check a files mod time.
60 ********************************************************************/
62 time_t file_modtime(const char *fname)
66 if (stat(fname,&st) != 0)
72 /*******************************************************************
73 Check if a directory exists.
74 ********************************************************************/
76 BOOL directory_exist(const char *dname,struct stat *st)
84 if (stat(dname,st) != 0)
87 ret = S_ISDIR(st->st_mode);
93 /*******************************************************************
94 Returns the size in bytes of the named file.
95 ********************************************************************/
96 off_t get_file_size(char *file_name)
100 if(stat(file_name,&buf) != 0)
105 /*******************************************************************
106 Close the low 3 fd's and open dev/null in their place.
107 ********************************************************************/
108 void close_low_fds(BOOL stderr_too)
120 /* try and use up these file descriptors, so silly
121 library routines writing to stdout etc won't cause havoc */
123 if (i == 2 && !stderr_too)
126 fd = open("/dev/null",O_RDWR,0);
128 fd = open("/dev/null",O_WRONLY,0);
130 DEBUG(0,("Can't open /dev/null\n"));
134 DEBUG(0,("Didn't get file descriptor %d\n",i));
141 /****************************************************************************
142 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
146 ****************************************************************************/
148 int set_blocking(int fd, BOOL set)
152 #define FLAG_TO_SET O_NONBLOCK
155 #define FLAG_TO_SET O_NDELAY
157 #define FLAG_TO_SET FNDELAY
161 if((val = fcntl(fd, F_GETFL, 0)) == -1)
163 if(set) /* Turn blocking on - ie. clear nonblock flag */
167 return fcntl( fd, F_SETFL, val);
172 /*******************************************************************
173 Sleep for a specified number of milliseconds.
174 ********************************************************************/
176 void msleep(uint_t t)
180 tval.tv_sec = t/1000;
181 tval.tv_usec = 1000*(t%1000);
182 /* this should be the real select - do NOT replace
184 select(0,NULL,NULL,NULL,&tval);
187 /****************************************************************************
188 Become a daemon, discarding the controlling terminal.
189 ****************************************************************************/
191 void become_daemon(BOOL Fork)
199 /* detach from the terminal */
202 #elif defined(TIOCNOTTY)
204 int i = open("/dev/tty", O_RDWR, 0);
206 ioctl(i, (int) TIOCNOTTY, (char *)0);
210 #endif /* HAVE_SETSID */
212 /* Close fd's 0,1,2. Needed if started by rsh */
213 close_low_fds(False); /* Don't close stderr, let the debug system
214 attach it to the logfile */
218 /****************************************************************************
219 Free memory, checks for NULL.
220 Use directly SAFE_FREE()
221 Exists only because we need to pass a function pointer somewhere --SSS
222 ****************************************************************************/
224 void safe_free(void *p)
231 see if a string matches either our primary or one of our secondary
232 netbios aliases. do a case insensitive match
234 BOOL is_myname(const char *name)
236 const char **aliases;
239 if (strcasecmp(name, lp_netbios_name()) == 0) {
243 aliases = lp_netbios_aliases();
244 for (i=0; aliases && aliases[i]; i++) {
245 if (strcasecmp(name, aliases[i]) == 0) {
254 /****************************************************************************
255 Get my own name, return in malloc'ed storage.
256 ****************************************************************************/
258 char* get_myname(void)
261 const int host_name_max = 255;
264 hostname = malloc(host_name_max+1);
267 /* get my host name */
268 if (gethostname(hostname, host_name_max+1) == -1) {
269 DEBUG(0,("gethostname failed\n"));
273 /* Ensure null termination. */
274 hostname[host_name_max] = '\0';
276 /* split off any parts after an initial . */
277 p = strchr_m(hostname,'.');
285 /****************************************************************************
286 Get my own name, including domain.
287 ****************************************************************************/
289 BOOL get_myfullname(char *my_name)
295 /* get my host name */
296 if (gethostname(hostname, sizeof(hostname)) == -1) {
297 DEBUG(0,("gethostname failed\n"));
301 /* Ensure null termination. */
302 hostname[sizeof(hostname)-1] = '\0';
305 fstrcpy(my_name, hostname);
309 /****************************************************************************
310 Get my own domain name.
311 ****************************************************************************/
313 BOOL get_mydomname(fstring my_domname)
319 /* get my host name */
320 if (gethostname(hostname, sizeof(hostname)) == -1) {
321 DEBUG(0,("gethostname failed\n"));
325 /* Ensure null termination. */
326 hostname[sizeof(hostname)-1] = '\0';
328 p = strchr_m(hostname, '.');
336 fstrcpy(my_domname, p);
341 /****************************************************************************
342 Interpret a protocol description string, with a default.
343 ****************************************************************************/
345 int interpret_protocol(char *str,int def)
347 if (strequal(str,"NT1"))
348 return(PROTOCOL_NT1);
349 if (strequal(str,"LANMAN2"))
350 return(PROTOCOL_LANMAN2);
351 if (strequal(str,"LANMAN1"))
352 return(PROTOCOL_LANMAN1);
353 if (strequal(str,"CORE"))
354 return(PROTOCOL_CORE);
355 if (strequal(str,"COREPLUS"))
356 return(PROTOCOL_COREPLUS);
357 if (strequal(str,"CORE+"))
358 return(PROTOCOL_COREPLUS);
360 DEBUG(0,("Unrecognised protocol level %s\n",str));
365 /****************************************************************************
366 Return true if a string could be a pure IP address.
367 ****************************************************************************/
369 BOOL is_ipaddress(const char *str)
371 BOOL pure_address = True;
374 for (i=0; pure_address && str[i]; i++)
375 if (!(isdigit((int)str[i]) || str[i] == '.'))
376 pure_address = False;
378 /* Check that a pure number is not misinterpreted as an IP */
379 pure_address = pure_address && (strchr_m(str, '.') != NULL);
384 /****************************************************************************
385 Interpret an internet address or name into an IP address in 4 byte form.
386 ****************************************************************************/
387 uint32_t interpret_addr(const char *str)
393 strcmp(str,"0.0.0.0") == 0) {
396 if (strcmp(str,"255.255.255.255") == 0) {
400 /* if it's in the form of an IP address then get the lib to interpret it */
401 if (is_ipaddress(str)) {
402 res = sys_inet_addr(str);
404 /* otherwise assume it's a network name of some sort and use
406 if ((hp = sys_gethostbyname(str)) == 0) {
407 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
411 if(hp->h_addr == NULL) {
412 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
415 putip((char *)&res,(char *)hp->h_addr);
418 if (res == (uint32_t)-1)
424 /*******************************************************************
425 A convenient addition to interpret_addr().
426 ******************************************************************/
427 struct ipv4_addr interpret_addr2(const char *str)
429 struct ipv4_addr ret;
430 uint32_t a = interpret_addr(str);
435 /*******************************************************************
436 Check if an IP is the 0.0.0.0.
437 ******************************************************************/
439 BOOL is_zero_ip(struct ipv4_addr ip)
442 putip((char *)&a,(char *)&ip);
446 /*******************************************************************
447 Set an IP to 0.0.0.0.
448 ******************************************************************/
450 void zero_ip(struct ipv4_addr *ip)
452 *ip = sys_inet_makeaddr(0,0);
457 /*******************************************************************
458 Are two IPs on the same subnet?
459 ********************************************************************/
461 BOOL same_net(struct ipv4_addr ip1,struct ipv4_addr ip2,struct ipv4_addr mask)
463 uint32_t net1,net2,nmask;
465 nmask = ntohl(mask.addr);
466 net1 = ntohl(ip1.addr);
467 net2 = ntohl(ip2.addr);
469 return((net1 & nmask) == (net2 & nmask));
473 /****************************************************************************
474 Check if a process exists. Does this work on all unixes?
475 ****************************************************************************/
477 BOOL process_exists(pid_t pid)
479 /* Doing kill with a non-positive pid causes messages to be
480 * sent to places we don't want. */
482 return(kill(pid,0) == 0 || errno != ESRCH);
485 /****************************************************************************
486 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
487 is dealt with in posix.c
488 ****************************************************************************/
490 BOOL fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
495 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
498 lock.l_whence = SEEK_SET;
499 lock.l_start = offset;
503 ret = fcntl(fd,op,&lock);
505 if (ret == -1 && errno != 0)
506 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
511 (lock.l_type != F_UNLCK) &&
513 (lock.l_pid != getpid())) {
514 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
518 /* it must be not locked or locked by me */
522 /* a lock set or unset */
524 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
525 (double)offset,(double)count,op,type,strerror(errno)));
529 /* everything went OK */
530 DEBUG(8,("fcntl_lock: Lock call successful\n"));
536 static void print_asc(int level, const uint8_t *buf,int len)
540 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
543 void dump_data(int level, const uint8_t *buf,int len)
548 if (!DEBUGLVL(level)) return;
550 DEBUGADD(level,("[%03X] ",i));
552 DEBUGADD(level,("%02X ",(int)buf[i]));
554 if (i%8 == 0) DEBUGADD(level,(" "));
556 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
557 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
558 if (i<len) DEBUGADD(level,("[%03X] ",i));
564 DEBUGADD(level,(" "));
565 if (n>8) DEBUGADD(level,(" "));
566 while (n--) DEBUGADD(level,(" "));
568 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
570 if (n>0) print_asc(level,&buf[i-n],n);
571 DEBUGADD(level,("\n"));
575 /*****************************************************************
576 Possibly replace mkstemp if it is broken.
577 *****************************************************************/
579 int smb_mkstemp(char *template)
581 #if HAVE_SECURE_MKSTEMP
582 return mkstemp(template);
584 /* have a reasonable go at emulating it. Hope that
585 the system mktemp() isn't completly hopeless */
586 char *p = mktemp(template);
589 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
593 /*****************************************************************
594 malloc that aborts with smb_panic on fail or zero size.
595 *****************************************************************/
597 void *smb_xmalloc(size_t size)
601 smb_panic("smb_xmalloc: called with zero size.\n");
602 if ((p = malloc(size)) == NULL)
603 smb_panic("smb_xmalloc: malloc fail.\n");
608 Memdup with smb_panic on fail.
611 void *smb_xmemdup(const void *p, size_t size)
614 p2 = smb_xmalloc(size);
620 strdup that aborts on malloc fail.
623 char *smb_xstrdup(const char *s)
625 char *s1 = strdup(s);
627 smb_panic("smb_xstrdup: malloc fail\n");
632 /*****************************************************************
633 Like strdup but for memory.
634 *****************************************************************/
636 void *memdup(const void *p, size_t size)
648 /*****************************************************************
649 Get local hostname and cache result.
650 *****************************************************************/
652 char *myhostname(TALLOC_CTX *mem_ctx)
655 myname = get_myname();
656 ret = talloc_strdup(mem_ctx, myname);
662 /**********************************************************************
663 Converts a name to a fully qalified domain name.
664 ***********************************************************************/
666 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
668 struct hostent *hp = sys_gethostbyname(name);
669 if ( hp && hp->h_name && *hp->h_name ) {
670 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
671 return talloc_strdup(mem_ctx, hp->h_name);
673 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
674 return talloc_strdup(mem_ctx, name);
679 /*****************************************************************
680 A useful function for returning a path in the Samba lock directory.
681 *****************************************************************/
682 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
686 dname = talloc_strdup(mem_ctx, lp_lockdir());
687 trim_string(dname,"","/");
689 if (!directory_exist(dname,NULL)) {
693 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
701 * @brief Returns an absolute path to a file in the Samba lib directory.
703 * @param name File to find, relative to LIBDIR.
705 * @retval Pointer to a talloc'ed string containing the full path.
708 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
711 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
716 return a path in the smbd.tmp directory, where all temporary file
717 for smbd go. If NULL is passed for name then return the directory
720 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
724 dname = lock_path(mem_ctx, "smbd.tmp");
725 if (!directory_exist(dname,NULL)) {
733 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
740 * @brief Returns the platform specific shared library extension.
742 * @retval Pointer to a static #fstring containing the extension.
745 const char *shlib_ext(void)
751 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
753 #ifdef DEBUG_PASSWORD
754 DEBUG(11, ("%s", msg));
755 if (data != NULL && len > 0)
757 dump_data(11, data, len);
763 /* see if a range of memory is all zero. A NULL pointer is considered
765 BOOL all_zero(const uint8_t *ptr, uint_t size)
768 if (!ptr) return True;
769 for (i=0;i<size;i++) {
770 if (ptr[i]) return False;
776 realloc an array, checking for integer overflow in the array size
778 void *realloc_array(void *ptr, size_t el_size, unsigned count)
780 #define MAX_MALLOC_SIZE 0x7fffffff
782 count >= MAX_MALLOC_SIZE/el_size) {
786 return malloc(el_size * count);
788 return realloc(ptr, el_size * count);