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"
29 #include "system/filesys.h"
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)
38 if ((p = getenv("TMPDIR")))
44 /*******************************************************************
45 Check if a file exists - call vfs_file_exist for samba files.
46 ********************************************************************/
47 BOOL file_exist(const char *fname)
51 if (stat(fname, &st) != 0) {
55 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.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)
81 if (stat(dname,&st) != 0) {
85 ret = S_ISDIR(st.st_mode);
91 BOOL directory_create_or_exist(const char *dname, uid_t uid,
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 "
109 DEBUG(0, ("lstat failed on directory %s: %s\n",
110 dname, strerror(errno)));
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",
122 if ((st.st_uid != uid) ||
123 ((st.st_mode & 0777) != dir_perms)) {
124 DEBUG(0, ("invalid permissions on directory "
134 /*******************************************************************
135 Close the low 3 fd's and open dev/null in their place.
136 ********************************************************************/
137 static void close_low_fds(BOOL stderr_too)
149 /* try and use up these file descriptors, so silly
150 library routines writing to stdout etc won't cause havoc */
152 if (i == 2 && !stderr_too)
155 fd = open("/dev/null",O_RDWR,0);
157 fd = open("/dev/null",O_WRONLY,0);
159 DEBUG(0,("Can't open /dev/null\n"));
163 DEBUG(0,("Didn't get file descriptor %d\n",i));
170 /****************************************************************************
171 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
175 ****************************************************************************/
177 int set_blocking(int fd, BOOL set)
181 #define FLAG_TO_SET O_NONBLOCK
184 #define FLAG_TO_SET O_NDELAY
186 #define FLAG_TO_SET FNDELAY
190 if((val = fcntl(fd, F_GETFL, 0)) == -1)
192 if(set) /* Turn blocking on - ie. clear nonblock flag */
196 return fcntl( fd, F_SETFL, val);
201 /*******************************************************************
202 Sleep for a specified number of milliseconds.
203 ********************************************************************/
205 void msleep(uint_t t)
209 tval.tv_sec = t/1000;
210 tval.tv_usec = 1000*(t%1000);
211 /* this should be the real select - do NOT replace
213 select(0,NULL,NULL,NULL,&tval);
216 /****************************************************************************
217 Become a daemon, discarding the controlling terminal.
218 ****************************************************************************/
220 void become_daemon(BOOL Fork)
228 /* detach from the terminal */
231 #elif defined(TIOCNOTTY)
233 int i = open("/dev/tty", O_RDWR, 0);
235 ioctl(i, (int) TIOCNOTTY, (char *)0);
239 #endif /* HAVE_SETSID */
241 /* Close fd's 0,1,2. Needed if started by rsh */
242 close_low_fds(False); /* Don't close stderr, let the debug system
243 attach it to the logfile */
247 /****************************************************************************
248 Free memory, checks for NULL.
249 Use directly SAFE_FREE()
250 Exists only because we need to pass a function pointer somewhere --SSS
251 ****************************************************************************/
253 void safe_free(void *p)
260 see if a string matches either our primary or one of our secondary
261 netbios aliases. do a case insensitive match
263 BOOL is_myname(const char *name)
265 const char **aliases;
268 if (strcasecmp(name, lp_netbios_name()) == 0) {
272 aliases = lp_netbios_aliases();
273 for (i=0; aliases && aliases[i]; i++) {
274 if (strcasecmp(name, aliases[i]) == 0) {
283 /****************************************************************************
284 Get my own name, return in malloc'ed storage.
285 ****************************************************************************/
287 char* get_myname(void)
290 const int host_name_max = 255;
293 hostname = malloc(host_name_max+1);
296 /* get my host name */
297 if (gethostname(hostname, host_name_max+1) == -1) {
298 DEBUG(0,("gethostname failed\n"));
302 /* Ensure null termination. */
303 hostname[host_name_max] = '\0';
305 /* split off any parts after an initial . */
306 p = strchr_m(hostname,'.');
314 /****************************************************************************
315 Return true if a string could be a pure IP address.
316 ****************************************************************************/
318 BOOL is_ipaddress(const char *str)
320 BOOL pure_address = True;
323 for (i=0; pure_address && str[i]; i++)
324 if (!(isdigit((int)str[i]) || str[i] == '.'))
325 pure_address = False;
327 /* Check that a pure number is not misinterpreted as an IP */
328 pure_address = pure_address && (strchr_m(str, '.') != NULL);
333 /****************************************************************************
334 Interpret an internet address or name into an IP address in 4 byte form.
335 ****************************************************************************/
336 uint32_t interpret_addr(const char *str)
341 if (str == NULL || *str == 0 ||
342 strcmp(str,"0.0.0.0") == 0) {
345 if (strcmp(str,"255.255.255.255") == 0) {
348 /* recognise 'localhost' as a special name. This fixes problems with
349 some hosts that don't have localhost in /etc/hosts */
350 if (strcasecmp(str,"localhost") == 0) {
354 /* if it's in the form of an IP address then get the lib to interpret it */
355 if (is_ipaddress(str)) {
356 res = inet_addr(str);
358 /* otherwise assume it's a network name of some sort and use
360 if ((hp = sys_gethostbyname(str)) == 0) {
361 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
365 if(hp->h_addr == NULL) {
366 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
369 memcpy((char *)&res,(char *)hp->h_addr, 4);
372 if (res == (uint32_t)-1)
378 /*******************************************************************
379 A convenient addition to interpret_addr().
380 ******************************************************************/
381 struct ipv4_addr interpret_addr2(const char *str)
383 struct ipv4_addr ret;
384 uint32_t a = interpret_addr(str);
389 /*******************************************************************
390 Check if an IP is the 0.0.0.0.
391 ******************************************************************/
393 BOOL is_zero_ip(struct ipv4_addr ip)
398 /*******************************************************************
399 Are two IPs on the same subnet?
400 ********************************************************************/
402 BOOL same_net(struct ipv4_addr ip1,struct ipv4_addr ip2,struct ipv4_addr mask)
404 uint32_t net1,net2,nmask;
406 nmask = ntohl(mask.addr);
407 net1 = ntohl(ip1.addr);
408 net2 = ntohl(ip2.addr);
410 return((net1 & nmask) == (net2 & nmask));
414 /****************************************************************************
415 Check if a process exists. Does this work on all unixes?
416 ****************************************************************************/
418 BOOL process_exists(pid_t pid)
420 /* Doing kill with a non-positive pid causes messages to be
421 * sent to places we don't want. */
423 return(kill(pid,0) == 0 || errno != ESRCH);
426 /****************************************************************************
427 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
428 is dealt with in posix.c
429 ****************************************************************************/
431 BOOL fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
436 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
439 lock.l_whence = SEEK_SET;
440 lock.l_start = offset;
444 ret = fcntl(fd,op,&lock);
446 if (ret == -1 && errno != 0)
447 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
452 (lock.l_type != F_UNLCK) &&
454 (lock.l_pid != getpid())) {
455 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
459 /* it must be not locked or locked by me */
463 /* a lock set or unset */
465 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
466 (double)offset,(double)count,op,type,strerror(errno)));
470 /* everything went OK */
471 DEBUG(8,("fcntl_lock: Lock call successful\n"));
477 static void print_asc(int level, const uint8_t *buf,int len)
481 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
484 void dump_data(int level, const uint8_t *buf,int len)
489 if (!DEBUGLVL(level)) return;
491 DEBUGADD(level,("[%03X] ",i));
493 DEBUGADD(level,("%02X ",(int)buf[i]));
495 if (i%8 == 0) DEBUGADD(level,(" "));
497 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
498 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
499 if (i<len) DEBUGADD(level,("[%03X] ",i));
505 DEBUGADD(level,(" "));
506 if (n>8) DEBUGADD(level,(" "));
507 while (n--) DEBUGADD(level,(" "));
509 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
511 if (n>0) print_asc(level,&buf[i-n],n);
512 DEBUGADD(level,("\n"));
516 /*****************************************************************
517 malloc that aborts with smb_panic on fail or zero size.
518 *****************************************************************/
520 void *smb_xmalloc(size_t size)
524 smb_panic("smb_xmalloc: called with zero size.\n");
525 if ((p = malloc(size)) == NULL)
526 smb_panic("smb_xmalloc: malloc fail.\n");
531 Memdup with smb_panic on fail.
534 void *smb_xmemdup(const void *p, size_t size)
537 p2 = smb_xmalloc(size);
543 strdup that aborts on malloc fail.
546 char *smb_xstrdup(const char *s)
548 char *s1 = strdup(s);
550 smb_panic("smb_xstrdup: malloc fail\n");
555 /*****************************************************************
556 Like strdup but for memory.
557 *****************************************************************/
559 void *memdup(const void *p, size_t size)
571 /*****************************************************************
572 A useful function for returning a path in the Samba lock directory.
573 *****************************************************************/
574 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
580 if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
581 return talloc_strdup(mem_ctx, name);
584 dname = talloc_strdup(mem_ctx, lp_lockdir());
585 trim_string(dname,"","/");
587 if (!directory_exist(dname)) {
591 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
599 /*****************************************************************
600 A useful function for returning a path in the Samba piddir directory.
601 *****************************************************************/
602 static char *pid_path(TALLOC_CTX* mem_ctx, const char *name)
606 dname = talloc_strdup(mem_ctx, lp_piddir());
607 trim_string(dname,"","/");
609 if (!directory_exist(dname)) {
613 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
622 * @brief Returns an absolute path to a file in the Samba lib directory.
624 * @param name File to find, relative to LIBDIR.
626 * @retval Pointer to a talloc'ed string containing the full path.
629 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
632 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
637 * @brief Returns an absolute path to a file in the Samba private directory.
639 * @param name File to find, relative to PRIVATEDIR.
640 * if name is not relative, then use it as-is
642 * @retval Pointer to a talloc'ed string containing the full path.
644 char *private_path(TALLOC_CTX* mem_ctx, const char *name)
650 if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
651 return talloc_strdup(mem_ctx, name);
653 fname = talloc_asprintf(mem_ctx, "%s/%s", lp_private_dir(), name);
658 return a path in the smbd.tmp directory, where all temporary file
659 for smbd go. If NULL is passed for name then return the directory
662 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
666 dname = pid_path(mem_ctx, "smbd.tmp");
667 if (!directory_exist(dname)) {
675 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
681 static char *modules_path(TALLOC_CTX* mem_ctx, const char *name)
683 return talloc_asprintf(mem_ctx, "%s/%s", dyn_MODULESDIR, name);
686 init_module_fn *load_samba_modules(TALLOC_CTX *mem_ctx, const char *subsystem)
688 char *path = modules_path(mem_ctx, subsystem);
691 ret = load_modules(mem_ctx, path);
698 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
700 #ifdef DEBUG_PASSWORD
701 DEBUG(11, ("%s", msg));
702 if (data != NULL && len > 0)
704 dump_data(11, data, len);
710 /* see if a range of memory is all zero. A NULL pointer is considered
712 BOOL all_zero(const uint8_t *ptr, uint_t size)
715 if (!ptr) return True;
716 for (i=0;i<size;i++) {
717 if (ptr[i]) return False;
723 realloc an array, checking for integer overflow in the array size
725 void *realloc_array(void *ptr, size_t el_size, unsigned count)
727 #define MAX_MALLOC_SIZE 0x7fffffff
729 count >= MAX_MALLOC_SIZE/el_size) {
733 return malloc(el_size * count);
735 return realloc(ptr, el_size * count);