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) Anthony Liguori 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(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(unsigned int 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 Convert a gid into a group name.
530 ********************************************************************/
532 char *gidtoname(TALLOC_CTX *mem_ctx, gid_t gid)
539 return(grp->gr_name);
540 name = talloc_asprintf(mem_ctx, "%d",(int)gid);
545 /*******************************************************************
546 Convert a name to a gid_t if possible. Return -1 if not a group.
547 ********************************************************************/
549 gid_t nametogid(const char *name)
555 g = (gid_t)strtol(name, &p, 0);
556 if ((p != name) && (*p == '\0'))
559 grp = sys_getgrnam(name);
565 /*******************************************************************
566 Something really nasty happened - panic !
567 ********************************************************************/
569 void smb_panic(const char *why)
571 char *cmd = lp_panic_action();
575 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
576 result = system(cmd);
579 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
582 DEBUG(0, ("smb_panic(): action returned status %d\n",
583 WEXITSTATUS(result)));
585 DEBUG(0,("PANIC: %s\n", why));
589 /****************************************************************************
590 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
591 is dealt with in posix.c
592 ****************************************************************************/
594 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
596 SMB_STRUCT_FLOCK lock;
599 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
602 lock.l_whence = SEEK_SET;
603 lock.l_start = offset;
607 ret = sys_fcntl_ptr(fd,op,&lock);
609 if (ret == -1 && errno != 0)
610 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
613 if (op == SMB_F_GETLK) {
615 (lock.l_type != F_UNLCK) &&
617 (lock.l_pid != getpid())) {
618 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
622 /* it must be not locked or locked by me */
626 /* a lock set or unset */
628 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
629 (double)offset,(double)count,op,type,strerror(errno)));
633 /* everything went OK */
634 DEBUG(8,("fcntl_lock: Lock call successful\n"));
639 /*******************************************************************
640 Set the remote_arch string based on an enum. This is used in places
641 where we desperately need to distinguish client type.
642 ********************************************************************/
643 void set_remote_arch(struct server_context *smb, enum remote_arch_types type)
647 smb->negotiate.ra_type = type;
671 smb->negotiate.ra_type = RA_UNKNOWN;
676 sub_set_remote_arch(arch);
680 void print_asc(int level, const uint8_t *buf,int len)
684 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
687 void dump_data(int level, const char *buf1,int len)
689 const uint8_t *buf = (const uint8_t *)buf1;
693 if (!DEBUGLVL(level)) return;
695 DEBUGADD(level,("[%03X] ",i));
697 DEBUGADD(level,("%02X ",(int)buf[i]));
699 if (i%8 == 0) DEBUGADD(level,(" "));
701 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
702 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
703 if (i<len) DEBUGADD(level,("[%03X] ",i));
709 DEBUGADD(level,(" "));
710 if (n>8) DEBUGADD(level,(" "));
711 while (n--) DEBUGADD(level,(" "));
713 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
715 if (n>0) print_asc(level,&buf[i-n],n);
716 DEBUGADD(level,("\n"));
720 /*****************************************************************
721 Possibly replace mkstemp if it is broken.
722 *****************************************************************/
724 int smb_mkstemp(char *template)
726 #if HAVE_SECURE_MKSTEMP
727 return mkstemp(template);
729 /* have a reasonable go at emulating it. Hope that
730 the system mktemp() isn't completly hopeless */
731 char *p = mktemp(template);
734 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
738 /*****************************************************************
739 malloc that aborts with smb_panic on fail or zero size.
740 *****************************************************************/
742 void *smb_xmalloc(size_t size)
746 smb_panic("smb_xmalloc: called with zero size.\n");
747 if ((p = malloc(size)) == NULL)
748 smb_panic("smb_xmalloc: malloc fail.\n");
753 Memdup with smb_panic on fail.
756 void *smb_xmemdup(const void *p, size_t size)
759 p2 = smb_xmalloc(size);
765 strdup that aborts on malloc fail.
768 char *smb_xstrdup(const char *s)
770 char *s1 = strdup(s);
772 smb_panic("smb_xstrdup: malloc fail\n");
778 vasprintf that aborts on malloc fail
781 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
788 n = vasprintf(ptr, format, ap2);
789 if (n == -1 || ! *ptr)
790 smb_panic("smb_xvasprintf: out of memory");
794 /*****************************************************************
795 Like strdup but for memory.
796 *****************************************************************/
798 void *memdup(const void *p, size_t size)
810 /*****************************************************************
811 Get local hostname and cache result.
812 *****************************************************************/
814 char *myhostname(TALLOC_CTX *mem_ctx)
817 myname = get_myname();
818 ret = talloc_strdup(mem_ctx, myname);
824 /*****************************************************************
825 A useful function for returning a path in the Samba lock directory.
826 *****************************************************************/
828 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
832 fname = talloc_strdup(mem_ctx, lp_lockdir());
833 trim_string(fname,"","/");
835 if (!directory_exist(fname,NULL))
838 fname = talloc_asprintf(mem_ctx, "%s/%s", fname, name);
844 * @brief Returns an absolute path to a file in the Samba lib directory.
846 * @param name File to find, relative to LIBDIR.
848 * @retval Pointer to a talloc'ed string containing the full path.
851 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
854 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
859 * @brief Returns the platform specific shared library extension.
861 * @retval Pointer to a static #fstring containing the extension.
864 const char *shlib_ext(void)
870 /*********************************************************
871 Recursive routine that is called by unix_wild_match.
872 *********************************************************/
874 static BOOL unix_do_match(char *regexp, char *str)
878 for( p = regexp; *p && *str; ) {
889 * Look for a character matching
890 * the one after the '*'.
894 return True; /* Automatic match */
897 while(*str && (*p != *str))
901 * Patch from weidel@multichart.de. In the case of the regexp
902 * '*XX*' we want to ensure there are at least 2 'X' characters
903 * in the string after the '*' for a match to be made.
910 * Eat all the characters that match, but count how many there were.
913 while(*str && (*p == *str)) {
919 * Now check that if the regexp had n identical characters that
920 * matchcount had at least that many matches.
923 while ( *(p+1) && (*(p+1) == *p)) {
928 if ( matchcount <= 0 )
932 str--; /* We've eaten the match char after the '*' */
934 if(unix_do_match(p, str))
956 if (!*p && str[0] == '.' && str[1] == 0)
959 if (!*str && *p == '?') {
965 if(!*str && (*p == '*' && p[1] == '\0'))
971 void dump_data_pw(const char *msg, const uchar * data, size_t len)
973 #ifdef DEBUG_PASSWORD
974 DEBUG(11, ("%s", msg));
975 if (data != NULL && len > 0)
977 dump_data(11, data, len);
983 /* see if a range of memory is all zero. A NULL pointer is considered
985 BOOL all_zero(const char *ptr, unsigned size)
988 if (!ptr) return True;
989 for (i=0;i<size;i++) {
990 if (ptr[i]) return False;