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.
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)
34 if ((p = getenv("TMPDIR")))
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)
49 if (sys_stat(fname,sbuf) != 0)
52 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
55 /*******************************************************************
56 Check a files mod time.
57 ********************************************************************/
59 time_t file_modtime(const char *fname)
63 if (sys_stat(fname,&st) != 0)
69 /*******************************************************************
70 Check if a directory exists.
71 ********************************************************************/
73 BOOL directory_exist(const char *dname,SMB_STRUCT_STAT *st)
81 if (sys_stat(dname,st) != 0)
84 ret = S_ISDIR(st->st_mode);
90 /*******************************************************************
91 Returns the size in bytes of the named file.
92 ********************************************************************/
93 SMB_OFF_T get_file_size(char *file_name)
97 if(sys_stat(file_name,&buf) != 0)
102 /*******************************************************************
103 Close the low 3 fd's and open dev/null in their place.
104 ********************************************************************/
105 void close_low_fds(BOOL stderr_too)
117 /* try and use up these file descriptors, so silly
118 library routines writing to stdout etc won't cause havoc */
120 if (i == 2 && !stderr_too)
123 fd = sys_open("/dev/null",O_RDWR,0);
125 fd = sys_open("/dev/null",O_WRONLY,0);
127 DEBUG(0,("Can't open /dev/null\n"));
131 DEBUG(0,("Didn't get file descriptor %d\n",i));
138 /****************************************************************************
139 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
143 ****************************************************************************/
145 int set_blocking(int fd, BOOL set)
149 #define FLAG_TO_SET O_NONBLOCK
152 #define FLAG_TO_SET O_NDELAY
154 #define FLAG_TO_SET FNDELAY
158 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
160 if(set) /* Turn blocking on - ie. clear nonblock flag */
164 return sys_fcntl_long( fd, F_SETFL, val);
169 /*******************************************************************
170 Sleep for a specified number of milliseconds.
171 ********************************************************************/
173 void msleep(uint_t t)
177 tval.tv_sec = t/1000;
178 tval.tv_usec = 1000*(t%1000);
179 /* this should be the real select - do NOT replace
181 select(0,NULL,NULL,NULL,&tval);
184 /****************************************************************************
185 Become a daemon, discarding the controlling terminal.
186 ****************************************************************************/
188 void become_daemon(BOOL Fork)
196 /* detach from the terminal */
199 #elif defined(TIOCNOTTY)
201 int i = sys_open("/dev/tty", O_RDWR, 0);
203 ioctl(i, (int) TIOCNOTTY, (char *)0);
207 #endif /* HAVE_SETSID */
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 */
215 /****************************************************************************
216 Expand a pointer to be a particular size.
217 ****************************************************************************/
219 void *Realloc(void *p,size_t size)
225 DEBUG(5,("Realloc asked for 0 bytes\n"));
230 ret = (void *)malloc(size);
232 ret = (void *)realloc(p,size);
235 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
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 ****************************************************************************/
246 void safe_free(void *p)
253 see if a string matches either our primary or one of our secondary
254 netbios aliases. do a case insensitive match
256 BOOL is_myname(const char *name)
258 const char **aliases;
261 if (strcasecmp(name, lp_netbios_name()) == 0) {
265 aliases = lp_netbios_aliases();
266 for (i=0; aliases && aliases[i]; i++) {
267 if (strcasecmp(name, aliases[i]) == 0) {
276 /****************************************************************************
277 Get my own name, return in malloc'ed storage.
278 ****************************************************************************/
280 char* get_myname(void)
283 const int host_name_max = 255;
286 hostname = malloc(host_name_max+1);
289 /* get my host name */
290 if (gethostname(hostname, host_name_max+1) == -1) {
291 DEBUG(0,("gethostname failed\n"));
295 /* Ensure null termination. */
296 hostname[host_name_max] = '\0';
298 /* split off any parts after an initial . */
299 p = strchr_m(hostname,'.');
307 /****************************************************************************
308 Get my own name, including domain.
309 ****************************************************************************/
311 BOOL get_myfullname(char *my_name)
317 /* get my host name */
318 if (gethostname(hostname, sizeof(hostname)) == -1) {
319 DEBUG(0,("gethostname failed\n"));
323 /* Ensure null termination. */
324 hostname[sizeof(hostname)-1] = '\0';
327 fstrcpy(my_name, hostname);
331 /****************************************************************************
332 Get my own domain name.
333 ****************************************************************************/
335 BOOL get_mydomname(fstring my_domname)
341 /* get my host name */
342 if (gethostname(hostname, sizeof(hostname)) == -1) {
343 DEBUG(0,("gethostname failed\n"));
347 /* Ensure null termination. */
348 hostname[sizeof(hostname)-1] = '\0';
350 p = strchr_m(hostname, '.');
358 fstrcpy(my_domname, p);
363 /****************************************************************************
364 Interpret a protocol description string, with a default.
365 ****************************************************************************/
367 int interpret_protocol(char *str,int def)
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);
382 DEBUG(0,("Unrecognised protocol level %s\n",str));
387 /****************************************************************************
388 Return true if a string could be a pure IP address.
389 ****************************************************************************/
391 BOOL is_ipaddress(const char *str)
393 BOOL pure_address = True;
396 for (i=0; pure_address && str[i]; i++)
397 if (!(isdigit((int)str[i]) || str[i] == '.'))
398 pure_address = False;
400 /* Check that a pure number is not misinterpreted as an IP */
401 pure_address = pure_address && (strchr_m(str, '.') != NULL);
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)
415 strcmp(str,"0.0.0.0") == 0) {
418 if (strcmp(str,"255.255.255.255") == 0) {
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);
426 /* otherwise assume it's a network name of some sort and use
428 if ((hp = sys_gethostbyname(str)) == 0) {
429 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
433 if(hp->h_addr == NULL) {
434 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
437 putip((char *)&res,(char *)hp->h_addr);
440 if (res == (uint32_t)-1)
446 /*******************************************************************
447 A convenient addition to interpret_addr().
448 ******************************************************************/
449 struct in_addr interpret_addr2(const char *str)
452 uint32_t a = interpret_addr(str);
457 /*******************************************************************
458 Check if an IP is the 0.0.0.0.
459 ******************************************************************/
461 BOOL is_zero_ip(struct in_addr ip)
464 putip((char *)&a,(char *)&ip);
468 /*******************************************************************
469 Set an IP to 0.0.0.0.
470 ******************************************************************/
472 void zero_ip(struct in_addr *ip)
474 *ip = inet_makeaddr(0,0);
479 /*******************************************************************
480 Are two IPs on the same subnet?
481 ********************************************************************/
483 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
485 uint32_t net1,net2,nmask;
487 nmask = ntohl(mask.s_addr);
488 net1 = ntohl(ip1.s_addr);
489 net2 = ntohl(ip2.s_addr);
491 return((net1 & nmask) == (net2 & nmask));
495 /****************************************************************************
496 Check if a process exists. Does this work on all unixes?
497 ****************************************************************************/
499 BOOL process_exists(pid_t pid)
501 /* Doing kill with a non-positive pid causes messages to be
502 * sent to places we don't want. */
504 return(kill(pid,0) == 0 || errno != ESRCH);
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 ****************************************************************************/
512 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
514 SMB_STRUCT_FLOCK lock;
517 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
520 lock.l_whence = SEEK_SET;
521 lock.l_start = offset;
525 ret = sys_fcntl_ptr(fd,op,&lock);
527 if (ret == -1 && errno != 0)
528 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
531 if (op == SMB_F_GETLK) {
533 (lock.l_type != F_UNLCK) &&
535 (lock.l_pid != getpid())) {
536 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
540 /* it must be not locked or locked by me */
544 /* a lock set or unset */
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)));
551 /* everything went OK */
552 DEBUG(8,("fcntl_lock: Lock call successful\n"));
558 static void print_asc(int level, const uint8_t *buf,int len)
562 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
565 void dump_data(int level, const char *buf1,int len)
567 const uint8_t *buf = (const uint8_t *)buf1;
571 if (!DEBUGLVL(level)) return;
573 DEBUGADD(level,("[%03X] ",i));
575 DEBUGADD(level,("%02X ",(int)buf[i]));
577 if (i%8 == 0) DEBUGADD(level,(" "));
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));
587 DEBUGADD(level,(" "));
588 if (n>8) DEBUGADD(level,(" "));
589 while (n--) DEBUGADD(level,(" "));
591 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
593 if (n>0) print_asc(level,&buf[i-n],n);
594 DEBUGADD(level,("\n"));
598 /*****************************************************************
599 Possibly replace mkstemp if it is broken.
600 *****************************************************************/
602 int smb_mkstemp(char *template)
604 #if HAVE_SECURE_MKSTEMP
605 return mkstemp(template);
607 /* have a reasonable go at emulating it. Hope that
608 the system mktemp() isn't completly hopeless */
609 char *p = mktemp(template);
612 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
616 /*****************************************************************
617 malloc that aborts with smb_panic on fail or zero size.
618 *****************************************************************/
620 void *smb_xmalloc(size_t size)
624 smb_panic("smb_xmalloc: called with zero size.\n");
625 if ((p = malloc(size)) == NULL)
626 smb_panic("smb_xmalloc: malloc fail.\n");
631 Memdup with smb_panic on fail.
634 void *smb_xmemdup(const void *p, size_t size)
637 p2 = smb_xmalloc(size);
643 strdup that aborts on malloc fail.
646 char *smb_xstrdup(const char *s)
648 char *s1 = strdup(s);
650 smb_panic("smb_xstrdup: malloc fail\n");
655 /*****************************************************************
656 Like strdup but for memory.
657 *****************************************************************/
659 void *memdup(const void *p, size_t size)
671 /*****************************************************************
672 Get local hostname and cache result.
673 *****************************************************************/
675 char *myhostname(TALLOC_CTX *mem_ctx)
678 myname = get_myname();
679 ret = talloc_strdup(mem_ctx, myname);
685 /**********************************************************************
686 Converts a name to a fully qalified domain name.
687 ***********************************************************************/
689 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
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);
696 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
697 return talloc_strdup(mem_ctx, name);
702 /*****************************************************************
703 A useful function for returning a path in the Samba lock directory.
704 *****************************************************************/
706 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
710 fname = talloc_strdup(mem_ctx, lp_lockdir());
711 trim_string(fname,"","/");
713 if (!directory_exist(fname,NULL))
716 fname = talloc_asprintf(mem_ctx, "%s/%s", fname, name);
722 * @brief Returns an absolute path to a file in the Samba lib directory.
724 * @param name File to find, relative to LIBDIR.
726 * @retval Pointer to a talloc'ed string containing the full path.
729 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
732 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
737 * @brief Returns the platform specific shared library extension.
739 * @retval Pointer to a static #fstring containing the extension.
742 const char *shlib_ext(void)
748 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
750 #ifdef DEBUG_PASSWORD
751 DEBUG(11, ("%s", msg));
752 if (data != NULL && len > 0)
754 dump_data(11, data, len);
760 /* see if a range of memory is all zero. A NULL pointer is considered
762 BOOL all_zero(const char *ptr, uint_t size)
765 if (!ptr) return True;
766 for (i=0;i<size;i++) {
767 if (ptr[i]) return False;