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 ****************************************************************************/
32 const char *tmpdir(void)
35 if ((p = getenv("TMPDIR")))
40 /****************************************************************************
41 Determine whether we are in the specified group.
42 ****************************************************************************/
44 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
48 if (group == current_gid)
51 for (i=0;i<ngroups;i++)
52 if (group == groups[i])
58 /*******************************************************************
59 Check if a file exists - call vfs_file_exist for samba files.
60 ********************************************************************/
62 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
68 if (sys_stat(fname,sbuf) != 0)
71 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
74 /*******************************************************************
75 Check a files mod time.
76 ********************************************************************/
78 time_t file_modtime(const char *fname)
82 if (sys_stat(fname,&st) != 0)
88 /*******************************************************************
89 Check if a directory exists.
90 ********************************************************************/
92 BOOL directory_exist(const char *dname,SMB_STRUCT_STAT *st)
100 if (sys_stat(dname,st) != 0)
103 ret = S_ISDIR(st->st_mode);
109 /*******************************************************************
110 Returns the size in bytes of the named file.
111 ********************************************************************/
112 SMB_OFF_T get_file_size(char *file_name)
116 if(sys_stat(file_name,&buf) != 0)
117 return (SMB_OFF_T)-1;
121 /*******************************************************************
122 Close the low 3 fd's and open dev/null in their place.
123 ********************************************************************/
124 void close_low_fds(BOOL stderr_too)
136 /* try and use up these file descriptors, so silly
137 library routines writing to stdout etc won't cause havoc */
139 if (i == 2 && !stderr_too)
142 fd = sys_open("/dev/null",O_RDWR,0);
144 fd = sys_open("/dev/null",O_WRONLY,0);
146 DEBUG(0,("Can't open /dev/null\n"));
150 DEBUG(0,("Didn't get file descriptor %d\n",i));
157 /****************************************************************************
158 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
162 ****************************************************************************/
164 int set_blocking(int fd, BOOL set)
168 #define FLAG_TO_SET O_NONBLOCK
171 #define FLAG_TO_SET O_NDELAY
173 #define FLAG_TO_SET FNDELAY
177 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
179 if(set) /* Turn blocking on - ie. clear nonblock flag */
183 return sys_fcntl_long( fd, F_SETFL, val);
188 /*******************************************************************
189 Sleep for a specified number of milliseconds.
190 ********************************************************************/
192 void msleep(uint_t t)
196 tval.tv_sec = t/1000;
197 tval.tv_usec = 1000*(t%1000);
198 /* this should be the real select - do NOT replace
200 select(0,NULL,NULL,NULL,&tval);
203 /****************************************************************************
204 Become a daemon, discarding the controlling terminal.
205 ****************************************************************************/
207 void become_daemon(BOOL Fork)
215 /* detach from the terminal */
218 #elif defined(TIOCNOTTY)
220 int i = sys_open("/dev/tty", O_RDWR, 0);
222 ioctl(i, (int) TIOCNOTTY, (char *)0);
226 #endif /* HAVE_SETSID */
228 /* Close fd's 0,1,2. Needed if started by rsh */
229 close_low_fds(False); /* Don't close stderr, let the debug system
230 attach it to the logfile */
234 /****************************************************************************
235 Expand a pointer to be a particular size.
236 ****************************************************************************/
238 void *Realloc(void *p,size_t size)
244 DEBUG(5,("Realloc asked for 0 bytes\n"));
249 ret = (void *)malloc(size);
251 ret = (void *)realloc(p,size);
254 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
259 /****************************************************************************
260 Free memory, checks for NULL.
261 Use directly SAFE_FREE()
262 Exists only because we need to pass a function pointer somewhere --SSS
263 ****************************************************************************/
265 void safe_free(void *p)
272 see if a string matches either our primary or one of our secondary
273 netbios aliases. do a case insensitive match
275 BOOL is_myname(const char *name)
277 const char **aliases;
280 if (strcasecmp(name, lp_netbios_name()) == 0) {
284 aliases = lp_netbios_aliases();
285 for (i=0; aliases && aliases[i]; i++) {
286 if (strcasecmp(name, aliases[i]) == 0) {
295 /****************************************************************************
296 Get my own name, return in malloc'ed storage.
297 ****************************************************************************/
299 char* get_myname(void)
302 const int host_name_max = 255;
305 hostname = malloc(host_name_max+1);
308 /* get my host name */
309 if (gethostname(hostname, host_name_max+1) == -1) {
310 DEBUG(0,("gethostname failed\n"));
314 /* Ensure null termination. */
315 hostname[host_name_max] = '\0';
317 /* split off any parts after an initial . */
318 p = strchr_m(hostname,'.');
326 /****************************************************************************
327 Get my own name, including domain.
328 ****************************************************************************/
330 BOOL get_myfullname(char *my_name)
336 /* get my host name */
337 if (gethostname(hostname, sizeof(hostname)) == -1) {
338 DEBUG(0,("gethostname failed\n"));
342 /* Ensure null termination. */
343 hostname[sizeof(hostname)-1] = '\0';
346 fstrcpy(my_name, hostname);
350 /****************************************************************************
351 Get my own domain name.
352 ****************************************************************************/
354 BOOL get_mydomname(fstring my_domname)
360 /* get my host name */
361 if (gethostname(hostname, sizeof(hostname)) == -1) {
362 DEBUG(0,("gethostname failed\n"));
366 /* Ensure null termination. */
367 hostname[sizeof(hostname)-1] = '\0';
369 p = strchr_m(hostname, '.');
377 fstrcpy(my_domname, p);
382 /****************************************************************************
383 Interpret a protocol description string, with a default.
384 ****************************************************************************/
386 int interpret_protocol(char *str,int def)
388 if (strequal(str,"NT1"))
389 return(PROTOCOL_NT1);
390 if (strequal(str,"LANMAN2"))
391 return(PROTOCOL_LANMAN2);
392 if (strequal(str,"LANMAN1"))
393 return(PROTOCOL_LANMAN1);
394 if (strequal(str,"CORE"))
395 return(PROTOCOL_CORE);
396 if (strequal(str,"COREPLUS"))
397 return(PROTOCOL_COREPLUS);
398 if (strequal(str,"CORE+"))
399 return(PROTOCOL_COREPLUS);
401 DEBUG(0,("Unrecognised protocol level %s\n",str));
406 /****************************************************************************
407 Return true if a string could be a pure IP address.
408 ****************************************************************************/
410 BOOL is_ipaddress(const char *str)
412 BOOL pure_address = True;
415 for (i=0; pure_address && str[i]; i++)
416 if (!(isdigit((int)str[i]) || str[i] == '.'))
417 pure_address = False;
419 /* Check that a pure number is not misinterpreted as an IP */
420 pure_address = pure_address && (strchr_m(str, '.') != NULL);
425 /****************************************************************************
426 Interpret an internet address or name into an IP address in 4 byte form.
427 ****************************************************************************/
429 uint32_t interpret_addr(const char *str)
434 if (strcmp(str,"0.0.0.0") == 0)
436 if (strcmp(str,"255.255.255.255") == 0)
439 /* if it's in the form of an IP address then get the lib to interpret it */
440 if (is_ipaddress(str)) {
441 res = inet_addr(str);
443 /* otherwise assume it's a network name of some sort and use
445 if ((hp = sys_gethostbyname(str)) == 0) {
446 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
450 if(hp->h_addr == NULL) {
451 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
454 putip((char *)&res,(char *)hp->h_addr);
457 if (res == (uint32_t)-1)
463 /*******************************************************************
464 A convenient addition to interpret_addr().
465 ******************************************************************/
467 struct in_addr *interpret_addr2(TALLOC_CTX *mem_ctx, const char *str)
470 uint32_t a = interpret_addr(str);
472 ret = talloc(mem_ctx, sizeof(struct in_addr));
473 if (!ret) return NULL;
478 /*******************************************************************
479 Check if an IP is the 0.0.0.0.
480 ******************************************************************/
482 BOOL is_zero_ip(struct in_addr ip)
485 putip((char *)&a,(char *)&ip);
489 /*******************************************************************
490 Set an IP to 0.0.0.0.
491 ******************************************************************/
493 void zero_ip(struct in_addr *ip)
495 *ip = inet_makeaddr(0,0);
500 /*******************************************************************
501 Are two IPs on the same subnet?
502 ********************************************************************/
504 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
506 uint32_t net1,net2,nmask;
508 nmask = ntohl(mask.s_addr);
509 net1 = ntohl(ip1.s_addr);
510 net2 = ntohl(ip2.s_addr);
512 return((net1 & nmask) == (net2 & nmask));
516 /****************************************************************************
517 Check if a process exists. Does this work on all unixes?
518 ****************************************************************************/
520 BOOL process_exists(pid_t pid)
522 /* Doing kill with a non-positive pid causes messages to be
523 * sent to places we don't want. */
525 return(kill(pid,0) == 0 || errno != ESRCH);
528 /****************************************************************************
529 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
530 is dealt with in posix.c
531 ****************************************************************************/
533 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
535 SMB_STRUCT_FLOCK lock;
538 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
541 lock.l_whence = SEEK_SET;
542 lock.l_start = offset;
546 ret = sys_fcntl_ptr(fd,op,&lock);
548 if (ret == -1 && errno != 0)
549 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
552 if (op == SMB_F_GETLK) {
554 (lock.l_type != F_UNLCK) &&
556 (lock.l_pid != getpid())) {
557 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
561 /* it must be not locked or locked by me */
565 /* a lock set or unset */
567 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
568 (double)offset,(double)count,op,type,strerror(errno)));
572 /* everything went OK */
573 DEBUG(8,("fcntl_lock: Lock call successful\n"));
579 static void print_asc(int level, const uint8_t *buf,int len)
583 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
586 void dump_data(int level, const char *buf1,int len)
588 const uint8_t *buf = (const uint8_t *)buf1;
592 if (!DEBUGLVL(level)) return;
594 DEBUGADD(level,("[%03X] ",i));
596 DEBUGADD(level,("%02X ",(int)buf[i]));
598 if (i%8 == 0) DEBUGADD(level,(" "));
600 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
601 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
602 if (i<len) DEBUGADD(level,("[%03X] ",i));
608 DEBUGADD(level,(" "));
609 if (n>8) DEBUGADD(level,(" "));
610 while (n--) DEBUGADD(level,(" "));
612 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
614 if (n>0) print_asc(level,&buf[i-n],n);
615 DEBUGADD(level,("\n"));
619 /*****************************************************************
620 Possibly replace mkstemp if it is broken.
621 *****************************************************************/
623 int smb_mkstemp(char *template)
625 #if HAVE_SECURE_MKSTEMP
626 return mkstemp(template);
628 /* have a reasonable go at emulating it. Hope that
629 the system mktemp() isn't completly hopeless */
630 char *p = mktemp(template);
633 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
637 /*****************************************************************
638 malloc that aborts with smb_panic on fail or zero size.
639 *****************************************************************/
641 void *smb_xmalloc(size_t size)
645 smb_panic("smb_xmalloc: called with zero size.\n");
646 if ((p = malloc(size)) == NULL)
647 smb_panic("smb_xmalloc: malloc fail.\n");
652 Memdup with smb_panic on fail.
655 void *smb_xmemdup(const void *p, size_t size)
658 p2 = smb_xmalloc(size);
664 strdup that aborts on malloc fail.
667 char *smb_xstrdup(const char *s)
669 char *s1 = strdup(s);
671 smb_panic("smb_xstrdup: malloc fail\n");
676 /*****************************************************************
677 Like strdup but for memory.
678 *****************************************************************/
680 void *memdup(const void *p, size_t size)
692 /*****************************************************************
693 Get local hostname and cache result.
694 *****************************************************************/
696 char *myhostname(TALLOC_CTX *mem_ctx)
699 myname = get_myname();
700 ret = talloc_strdup(mem_ctx, myname);
706 /**********************************************************************
707 Converts a name to a fully qalified domain name.
708 ***********************************************************************/
710 char *name_to_fqdn(TALLOC_CTX *mem_ctx, const char *name)
712 struct hostent *hp = sys_gethostbyname(name);
713 if ( hp && hp->h_name && *hp->h_name ) {
714 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
715 return talloc_strdup(mem_ctx, hp->h_name);
717 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
718 return talloc_strdup(mem_ctx, name);
723 /*****************************************************************
724 A useful function for returning a path in the Samba lock directory.
725 *****************************************************************/
727 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
731 fname = talloc_strdup(mem_ctx, lp_lockdir());
732 trim_string(fname,"","/");
734 if (!directory_exist(fname,NULL))
737 fname = talloc_asprintf(mem_ctx, "%s/%s", fname, name);
743 * @brief Returns an absolute path to a file in the Samba lib directory.
745 * @param name File to find, relative to LIBDIR.
747 * @retval Pointer to a talloc'ed string containing the full path.
750 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
753 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
758 * @brief Returns the platform specific shared library extension.
760 * @retval Pointer to a static #fstring containing the extension.
763 const char *shlib_ext(void)
769 /*********************************************************
770 Recursive routine that is called by unix_wild_match.
771 *********************************************************/
773 static BOOL unix_do_match(char *regexp, char *str)
777 for( p = regexp; *p && *str; ) {
788 * Look for a character matching
789 * the one after the '*'.
793 return True; /* Automatic match */
796 while(*str && (*p != *str))
800 * Patch from weidel@multichart.de. In the case of the regexp
801 * '*XX*' we want to ensure there are at least 2 'X' characters
802 * in the string after the '*' for a match to be made.
809 * Eat all the characters that match, but count how many there were.
812 while(*str && (*p == *str)) {
818 * Now check that if the regexp had n identical characters that
819 * matchcount had at least that many matches.
822 while ( *(p+1) && (*(p+1) == *p)) {
827 if ( matchcount <= 0 )
831 str--; /* We've eaten the match char after the '*' */
833 if(unix_do_match(p, str))
855 if (!*p && str[0] == '.' && str[1] == 0)
858 if (!*str && *p == '?') {
864 if(!*str && (*p == '*' && p[1] == '\0'))
870 void dump_data_pw(const char *msg, const uint8_t * data, size_t len)
872 #ifdef DEBUG_PASSWORD
873 DEBUG(11, ("%s", msg));
874 if (data != NULL && len > 0)
876 dump_data(11, data, len);
882 /* see if a range of memory is all zero. A NULL pointer is considered
884 BOOL all_zero(const char *ptr, uint_t size)
887 if (!ptr) return True;
888 for (i=0;i<size;i++) {
889 if (ptr[i]) return False;
896 this is a warning hack. The idea is to use this everywhere that we
897 get the "discarding const" warning from gcc, effectively moving all
898 the warnings to this one place. That doesn't actually fix the
899 problem of course, but it means that when we do get to cleaning them
900 up we can do it by searching the code for discard_const.
902 It also means that other error types aren't as swamped by the noise
903 of hundreds of const warnings, so we are more likely to notice when
906 Please only add more calls to this function when you find it
907 _really_ hard to fix const warnings. Our aim is to eventually use
908 this function in only a very few places.
910 Also, please call this via the discard_const_p() macro interface, as that
911 makes the return type safe.
913 void *discard_const(const void *ptr)