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/dir.h"
30 #include "system/filesys.h"
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)
39 if ((p = getenv("TMPDIR")))
45 /*******************************************************************
46 Check if a file exists - call vfs_file_exist for samba files.
47 ********************************************************************/
48 BOOL file_exist(const char *fname)
52 if (stat(fname, &st) != 0) {
56 return ((S_ISREG(st.st_mode)) || (S_ISFIFO(st.st_mode)));
59 /*******************************************************************
60 Check a files mod time.
61 ********************************************************************/
63 time_t file_modtime(const char *fname)
67 if (stat(fname,&st) != 0)
73 /*******************************************************************
74 Check if a directory exists.
75 ********************************************************************/
77 BOOL directory_exist(const char *dname)
82 if (stat(dname,&st) != 0) {
86 ret = S_ISDIR(st.st_mode);
92 /*******************************************************************
93 Returns the size in bytes of the named file.
94 ********************************************************************/
95 off_t get_file_size(char *file_name)
99 if(stat(file_name,&buf) != 0)
104 /*******************************************************************
105 Close the low 3 fd's and open dev/null in their place.
106 ********************************************************************/
107 void close_low_fds(BOOL stderr_too)
119 /* try and use up these file descriptors, so silly
120 library routines writing to stdout etc won't cause havoc */
122 if (i == 2 && !stderr_too)
125 fd = open("/dev/null",O_RDWR,0);
127 fd = open("/dev/null",O_WRONLY,0);
129 DEBUG(0,("Can't open /dev/null\n"));
133 DEBUG(0,("Didn't get file descriptor %d\n",i));
140 /****************************************************************************
141 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
145 ****************************************************************************/
147 int set_blocking(int fd, BOOL set)
151 #define FLAG_TO_SET O_NONBLOCK
154 #define FLAG_TO_SET O_NDELAY
156 #define FLAG_TO_SET FNDELAY
160 if((val = fcntl(fd, F_GETFL, 0)) == -1)
162 if(set) /* Turn blocking on - ie. clear nonblock flag */
166 return fcntl( fd, F_SETFL, val);
171 /*******************************************************************
172 Sleep for a specified number of milliseconds.
173 ********************************************************************/
175 void msleep(uint_t t)
179 tval.tv_sec = t/1000;
180 tval.tv_usec = 1000*(t%1000);
181 /* this should be the real select - do NOT replace
183 select(0,NULL,NULL,NULL,&tval);
186 /****************************************************************************
187 Become a daemon, discarding the controlling terminal.
188 ****************************************************************************/
190 void become_daemon(BOOL Fork)
198 /* detach from the terminal */
201 #elif defined(TIOCNOTTY)
203 int i = open("/dev/tty", O_RDWR, 0);
205 ioctl(i, (int) TIOCNOTTY, (char *)0);
209 #endif /* HAVE_SETSID */
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 */
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 ****************************************************************************/
223 void safe_free(void *p)
230 see if a string matches either our primary or one of our secondary
231 netbios aliases. do a case insensitive match
233 BOOL is_myname(const char *name)
235 const char **aliases;
238 if (strcasecmp(name, lp_netbios_name()) == 0) {
242 aliases = lp_netbios_aliases();
243 for (i=0; aliases && aliases[i]; i++) {
244 if (strcasecmp(name, aliases[i]) == 0) {
253 /****************************************************************************
254 Get my own name, return in malloc'ed storage.
255 ****************************************************************************/
257 char* get_myname(void)
260 const int host_name_max = 255;
263 hostname = malloc(host_name_max+1);
266 /* get my host name */
267 if (gethostname(hostname, host_name_max+1) == -1) {
268 DEBUG(0,("gethostname failed\n"));
272 /* Ensure null termination. */
273 hostname[host_name_max] = '\0';
275 /* split off any parts after an initial . */
276 p = strchr_m(hostname,'.');
284 /****************************************************************************
285 Interpret a protocol description string, with a default.
286 ****************************************************************************/
288 int interpret_protocol(char *str,int def)
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);
303 DEBUG(0,("Unrecognised protocol level %s\n",str));
308 /****************************************************************************
309 Return true if a string could be a pure IP address.
310 ****************************************************************************/
312 BOOL is_ipaddress(const char *str)
314 BOOL pure_address = True;
317 for (i=0; pure_address && str[i]; i++)
318 if (!(isdigit((int)str[i]) || str[i] == '.'))
319 pure_address = False;
321 /* Check that a pure number is not misinterpreted as an IP */
322 pure_address = pure_address && (strchr_m(str, '.') != NULL);
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)
335 if (str == NULL || *str == 0 ||
336 strcmp(str,"0.0.0.0") == 0) {
339 if (strcmp(str,"255.255.255.255") == 0) {
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) {
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);
352 /* otherwise assume it's a network name of some sort and use
354 if ((hp = sys_gethostbyname(str)) == 0) {
355 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
359 if(hp->h_addr == NULL) {
360 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
363 memcpy((char *)&res,(char *)hp->h_addr, 4);
366 if (res == (uint32_t)-1)
372 /*******************************************************************
373 A convenient addition to interpret_addr().
374 ******************************************************************/
375 struct ipv4_addr interpret_addr2(const char *str)
377 struct ipv4_addr ret;
378 uint32_t a = interpret_addr(str);
383 /*******************************************************************
384 Check if an IP is the 0.0.0.0.
385 ******************************************************************/
387 BOOL is_zero_ip(struct ipv4_addr ip)
392 /*******************************************************************
393 Set an IP to 0.0.0.0.
394 ******************************************************************/
396 void zero_ip(struct ipv4_addr *ip)
398 *ip = sys_inet_makeaddr(0,0);
403 /*******************************************************************
404 Are two IPs on the same subnet?
405 ********************************************************************/
407 BOOL same_net(struct ipv4_addr ip1,struct ipv4_addr ip2,struct ipv4_addr mask)
409 uint32_t net1,net2,nmask;
411 nmask = ntohl(mask.addr);
412 net1 = ntohl(ip1.addr);
413 net2 = ntohl(ip2.addr);
415 return((net1 & nmask) == (net2 & nmask));
419 /****************************************************************************
420 Check if a process exists. Does this work on all unixes?
421 ****************************************************************************/
423 BOOL process_exists(pid_t pid)
425 /* Doing kill with a non-positive pid causes messages to be
426 * sent to places we don't want. */
428 return(kill(pid,0) == 0 || errno != ESRCH);
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 ****************************************************************************/
436 BOOL fcntl_lock(int fd, int op, off_t offset, off_t count, int type)
441 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
444 lock.l_whence = SEEK_SET;
445 lock.l_start = offset;
449 ret = fcntl(fd,op,&lock);
451 if (ret == -1 && errno != 0)
452 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
457 (lock.l_type != F_UNLCK) &&
459 (lock.l_pid != getpid())) {
460 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
464 /* it must be not locked or locked by me */
468 /* a lock set or unset */
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)));
475 /* everything went OK */
476 DEBUG(8,("fcntl_lock: Lock call successful\n"));
482 static void print_asc(int level, const uint8_t *buf,int len)
486 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
489 void dump_data(int level, const uint8_t *buf,int len)
494 if (!DEBUGLVL(level)) return;
496 DEBUGADD(level,("[%03X] ",i));
498 DEBUGADD(level,("%02X ",(int)buf[i]));
500 if (i%8 == 0) DEBUGADD(level,(" "));
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));
510 DEBUGADD(level,(" "));
511 if (n>8) DEBUGADD(level,(" "));
512 while (n--) DEBUGADD(level,(" "));
514 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
516 if (n>0) print_asc(level,&buf[i-n],n);
517 DEBUGADD(level,("\n"));
521 /*****************************************************************
522 malloc that aborts with smb_panic on fail or zero size.
523 *****************************************************************/
525 void *smb_xmalloc(size_t size)
529 smb_panic("smb_xmalloc: called with zero size.\n");
530 if ((p = malloc(size)) == NULL)
531 smb_panic("smb_xmalloc: malloc fail.\n");
536 Memdup with smb_panic on fail.
539 void *smb_xmemdup(const void *p, size_t size)
542 p2 = smb_xmalloc(size);
548 strdup that aborts on malloc fail.
551 char *smb_xstrdup(const char *s)
553 char *s1 = strdup(s);
555 smb_panic("smb_xstrdup: malloc fail\n");
560 /*****************************************************************
561 Like strdup but for memory.
562 *****************************************************************/
564 void *memdup(const void *p, size_t size)
576 /*****************************************************************
577 Get local hostname and cache result.
578 *****************************************************************/
580 char *myhostname(TALLOC_CTX *mem_ctx)
583 myname = get_myname();
584 ret = talloc_strdup(mem_ctx, myname);
590 /**********************************************************************
591 Converts a name to a fully qalified domain name.
592 ***********************************************************************/
594 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
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);
601 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
602 return talloc_strdup(mem_ctx, name);
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)
614 dname = talloc_strdup(mem_ctx, lp_lockdir());
615 trim_string(dname,"","/");
617 if (!directory_exist(dname)) {
621 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
629 * @brief Returns an absolute path to a file in the Samba lib directory.
631 * @param name File to find, relative to LIBDIR.
633 * @retval Pointer to a talloc'ed string containing the full path.
636 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
639 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
644 * @brief Returns an absolute path to a file in the Samba private directory.
646 * @param name File to find, relative to PRIVATEDIR.
647 * if name is not relative, then use it as-is
649 * @retval Pointer to a talloc'ed string containing the full path.
651 char *private_path(TALLOC_CTX* mem_ctx, const char *name)
657 if (name[0] == 0 || name[0] == '/' || strstr(name, ":/")) {
658 return talloc_strdup(mem_ctx, name);
660 fname = talloc_asprintf(mem_ctx, "%s/%s", lp_private_dir(), name);
665 return a path in the smbd.tmp directory, where all temporary file
666 for smbd go. If NULL is passed for name then return the directory
669 char *smbd_tmp_path(TALLOC_CTX *mem_ctx, const char *name)
673 dname = lock_path(mem_ctx, "smbd.tmp");
674 if (!directory_exist(dname)) {
682 fname = talloc_asprintf(mem_ctx, "%s/%s", dname, name);
688 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
690 #ifdef DEBUG_PASSWORD
691 DEBUG(11, ("%s", msg));
692 if (data != NULL && len > 0)
694 dump_data(11, data, len);
700 /* see if a range of memory is all zero. A NULL pointer is considered
702 BOOL all_zero(const uint8_t *ptr, uint_t size)
705 if (!ptr) return True;
706 for (i=0;i<size;i++) {
707 if (ptr[i]) return False;
713 realloc an array, checking for integer overflow in the array size
715 void *realloc_array(void *ptr, size_t el_size, unsigned count)
717 #define MAX_MALLOC_SIZE 0x7fffffff
719 count >= MAX_MALLOC_SIZE/el_size) {
723 return malloc(el_size * count);
725 return realloc(ptr, el_size * count);