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 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
28 #ifdef WITH_NISPLUS_HOME
29 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
31 * The following lines are needed due to buggy include files
32 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
33 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
34 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
35 * an enum in /usr/include/rpcsvc/nis.h.
42 #if defined(GROUP_OBJ)
46 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
48 #include <rpcsvc/nis.h>
50 #else /* !WITH_NISPLUS_HOME */
52 #include "rpcsvc/ypclnt.h"
54 #endif /* WITH_NISPLUS_HOME */
55 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
58 /**************************************************************************n
59 Find a suitable temporary directory. The result should be copied immediately
60 as it may be overwritten by a subsequent call.
61 ****************************************************************************/
63 const char *tmpdir(void)
66 if ((p = getenv("TMPDIR")))
71 /****************************************************************************
72 Determine whether we are in the specified group.
73 ****************************************************************************/
75 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
79 if (group == current_gid)
82 for (i=0;i<ngroups;i++)
83 if (group == groups[i])
89 /*******************************************************************
90 Check if a file exists - call vfs_file_exist for samba files.
91 ********************************************************************/
93 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
99 if (sys_stat(fname,sbuf) != 0)
102 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
105 /*******************************************************************
106 Check a files mod time.
107 ********************************************************************/
109 time_t file_modtime(const char *fname)
113 if (sys_stat(fname,&st) != 0)
119 /*******************************************************************
120 Check if a directory exists.
121 ********************************************************************/
123 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
131 if (sys_stat(dname,st) != 0)
134 ret = S_ISDIR(st->st_mode);
140 /*******************************************************************
141 Returns the size in bytes of the named file.
142 ********************************************************************/
143 SMB_OFF_T get_file_size(char *file_name)
147 if(sys_stat(file_name,&buf) != 0)
148 return (SMB_OFF_T)-1;
152 /*******************************************************************
153 Close the low 3 fd's and open dev/null in their place.
154 ********************************************************************/
155 void close_low_fds(BOOL stderr_too)
167 /* try and use up these file descriptors, so silly
168 library routines writing to stdout etc won't cause havoc */
170 if (i == 2 && !stderr_too)
173 fd = sys_open("/dev/null",O_RDWR,0);
175 fd = sys_open("/dev/null",O_WRONLY,0);
177 DEBUG(0,("Can't open /dev/null\n"));
181 DEBUG(0,("Didn't get file descriptor %d\n",i));
188 /****************************************************************************
189 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
193 ****************************************************************************/
195 int set_blocking(int fd, BOOL set)
199 #define FLAG_TO_SET O_NONBLOCK
202 #define FLAG_TO_SET O_NDELAY
204 #define FLAG_TO_SET FNDELAY
208 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
210 if(set) /* Turn blocking on - ie. clear nonblock flag */
214 return sys_fcntl_long( fd, F_SETFL, val);
219 /*******************************************************************
220 Sleep for a specified number of milliseconds.
221 ********************************************************************/
223 void msleep(unsigned int t)
227 tval.tv_sec = t/1000;
228 tval.tv_usec = 1000*(t%1000);
229 /* this should be the real select - do NOT replace
231 select(0,NULL,NULL,NULL,&tval);
234 /****************************************************************************
235 Become a daemon, discarding the controlling terminal.
236 ****************************************************************************/
238 void become_daemon(BOOL Fork)
246 /* detach from the terminal */
249 #elif defined(TIOCNOTTY)
251 int i = sys_open("/dev/tty", O_RDWR, 0);
253 ioctl(i, (int) TIOCNOTTY, (char *)0);
257 #endif /* HAVE_SETSID */
259 /* Close fd's 0,1,2. Needed if started by rsh */
260 close_low_fds(False); /* Don't close stderr, let the debug system
261 attach it to the logfile */
265 /****************************************************************************
266 Expand a pointer to be a particular size.
267 ****************************************************************************/
269 void *Realloc(void *p,size_t size)
275 DEBUG(5,("Realloc asked for 0 bytes\n"));
280 ret = (void *)malloc(size);
282 ret = (void *)realloc(p,size);
285 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
290 /****************************************************************************
291 Free memory, checks for NULL.
292 Use directly SAFE_FREE()
293 Exists only because we need to pass a function pointer somewhere --SSS
294 ****************************************************************************/
296 void safe_free(void *p)
303 see if a string matches either our primary or one of our secondary
304 netbios aliases. do a case insensitive match
306 BOOL is_myname(const char *name)
308 const char **aliases;
311 if (strcasecmp(name, lp_netbios_name()) == 0) {
315 aliases = lp_netbios_aliases();
316 for (i=0; aliases && aliases[i]; i++) {
317 if (strcasecmp(name, aliases[i]) == 0) {
326 /****************************************************************************
327 Get my own name, return in malloc'ed storage.
328 ****************************************************************************/
330 char* get_myname(void)
333 const int host_name_max = 255;
336 hostname = malloc(host_name_max+1);
339 /* get my host name */
340 if (gethostname(hostname, host_name_max+1) == -1) {
341 DEBUG(0,("gethostname failed\n"));
345 /* Ensure null termination. */
346 hostname[host_name_max] = '\0';
348 /* split off any parts after an initial . */
349 p = strchr_m(hostname,'.');
357 /****************************************************************************
358 Get my own name, including domain.
359 ****************************************************************************/
361 BOOL get_myfullname(char *my_name)
367 /* get my host name */
368 if (gethostname(hostname, sizeof(hostname)) == -1) {
369 DEBUG(0,("gethostname failed\n"));
373 /* Ensure null termination. */
374 hostname[sizeof(hostname)-1] = '\0';
377 fstrcpy(my_name, hostname);
381 /****************************************************************************
382 Get my own domain name.
383 ****************************************************************************/
385 BOOL get_mydomname(fstring my_domname)
391 /* get my host name */
392 if (gethostname(hostname, sizeof(hostname)) == -1) {
393 DEBUG(0,("gethostname failed\n"));
397 /* Ensure null termination. */
398 hostname[sizeof(hostname)-1] = '\0';
400 p = strchr_m(hostname, '.');
408 fstrcpy(my_domname, p);
413 /****************************************************************************
414 Interpret a protocol description string, with a default.
415 ****************************************************************************/
417 int interpret_protocol(char *str,int def)
419 if (strequal(str,"NT1"))
420 return(PROTOCOL_NT1);
421 if (strequal(str,"LANMAN2"))
422 return(PROTOCOL_LANMAN2);
423 if (strequal(str,"LANMAN1"))
424 return(PROTOCOL_LANMAN1);
425 if (strequal(str,"CORE"))
426 return(PROTOCOL_CORE);
427 if (strequal(str,"COREPLUS"))
428 return(PROTOCOL_COREPLUS);
429 if (strequal(str,"CORE+"))
430 return(PROTOCOL_COREPLUS);
432 DEBUG(0,("Unrecognised protocol level %s\n",str));
437 /****************************************************************************
438 Return true if a string could be a pure IP address.
439 ****************************************************************************/
441 BOOL is_ipaddress(const char *str)
443 BOOL pure_address = True;
446 for (i=0; pure_address && str[i]; i++)
447 if (!(isdigit((int)str[i]) || str[i] == '.'))
448 pure_address = False;
450 /* Check that a pure number is not misinterpreted as an IP */
451 pure_address = pure_address && (strchr_m(str, '.') != NULL);
456 /****************************************************************************
457 Interpret an internet address or name into an IP address in 4 byte form.
458 ****************************************************************************/
460 uint32 interpret_addr(const char *str)
465 if (strcmp(str,"0.0.0.0") == 0)
467 if (strcmp(str,"255.255.255.255") == 0)
470 /* if it's in the form of an IP address then get the lib to interpret it */
471 if (is_ipaddress(str)) {
472 res = inet_addr(str);
474 /* otherwise assume it's a network name of some sort and use
476 if ((hp = sys_gethostbyname(str)) == 0) {
477 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
481 if(hp->h_addr == NULL) {
482 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
485 putip((char *)&res,(char *)hp->h_addr);
488 if (res == (uint32)-1)
494 /*******************************************************************
495 A convenient addition to interpret_addr().
496 ******************************************************************/
498 struct in_addr *interpret_addr2(TALLOC_CTX *mem_ctx, const char *str)
501 uint32 a = interpret_addr(str);
503 ret = talloc(mem_ctx, sizeof(struct in_addr));
504 if (!ret) return NULL;
509 /*******************************************************************
510 Check if an IP is the 0.0.0.0.
511 ******************************************************************/
513 BOOL is_zero_ip(struct in_addr ip)
516 putip((char *)&a,(char *)&ip);
520 /*******************************************************************
521 Set an IP to 0.0.0.0.
522 ******************************************************************/
524 void zero_ip(struct in_addr *ip)
526 *ip = inet_makeaddr(0,0);
531 /*******************************************************************
532 Are two IPs on the same subnet?
533 ********************************************************************/
535 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
537 uint32 net1,net2,nmask;
539 nmask = ntohl(mask.s_addr);
540 net1 = ntohl(ip1.s_addr);
541 net2 = ntohl(ip2.s_addr);
543 return((net1 & nmask) == (net2 & nmask));
547 /****************************************************************************
548 Check if a process exists. Does this work on all unixes?
549 ****************************************************************************/
551 BOOL process_exists(pid_t pid)
553 /* Doing kill with a non-positive pid causes messages to be
554 * sent to places we don't want. */
556 return(kill(pid,0) == 0 || errno != ESRCH);
559 /*******************************************************************
560 Convert a gid into a group name.
561 ********************************************************************/
563 char *gidtoname(TALLOC_CTX *mem_ctx, gid_t gid)
570 return(grp->gr_name);
571 name = talloc_asprintf(mem_ctx, "%d",(int)gid);
576 /*******************************************************************
577 Convert a name to a gid_t if possible. Return -1 if not a group.
578 ********************************************************************/
580 gid_t nametogid(const char *name)
586 g = (gid_t)strtol(name, &p, 0);
587 if ((p != name) && (*p == '\0'))
590 grp = sys_getgrnam(name);
596 /*******************************************************************
597 Something really nasty happened - panic !
598 ********************************************************************/
600 void smb_panic(const char *why)
602 char *cmd = lp_panic_action();
606 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
607 result = system(cmd);
610 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
613 DEBUG(0, ("smb_panic(): action returned status %d\n",
614 WEXITSTATUS(result)));
616 DEBUG(0,("PANIC: %s\n", why));
620 /****************************************************************************
621 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
622 is dealt with in posix.c
623 ****************************************************************************/
625 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
627 SMB_STRUCT_FLOCK lock;
630 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
633 lock.l_whence = SEEK_SET;
634 lock.l_start = offset;
638 ret = sys_fcntl_ptr(fd,op,&lock);
640 if (ret == -1 && errno != 0)
641 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
644 if (op == SMB_F_GETLK) {
646 (lock.l_type != F_UNLCK) &&
648 (lock.l_pid != getpid())) {
649 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
653 /* it must be not locked or locked by me */
657 /* a lock set or unset */
659 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
660 (double)offset,(double)count,op,type,strerror(errno)));
664 /* everything went OK */
665 DEBUG(8,("fcntl_lock: Lock call successful\n"));
670 /*******************************************************************
671 Set the remote_arch string based on an enum. This is used in places
672 where we desperately need to distinguish client type.
673 ********************************************************************/
674 void set_remote_arch(struct server_context *smb, enum remote_arch_types type)
678 smb->negotiate.ra_type = type;
702 smb->negotiate.ra_type = RA_UNKNOWN;
707 sub_set_remote_arch(arch);
711 void print_asc(int level, const unsigned char *buf,int len)
715 DEBUGADD(level,("%c", isprint(buf[i])?buf[i]:'.'));
718 void dump_data(int level, const char *buf1,int len)
720 const unsigned char *buf = (const unsigned char *)buf1;
724 if (!DEBUGLVL(level)) return;
726 DEBUGADD(level,("[%03X] ",i));
728 DEBUGADD(level,("%02X ",(int)buf[i]));
730 if (i%8 == 0) DEBUGADD(level,(" "));
732 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
733 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
734 if (i<len) DEBUGADD(level,("[%03X] ",i));
740 DEBUGADD(level,(" "));
741 if (n>8) DEBUGADD(level,(" "));
742 while (n--) DEBUGADD(level,(" "));
744 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
746 if (n>0) print_asc(level,&buf[i-n],n);
747 DEBUGADD(level,("\n"));
751 /*****************************************************************
752 Possibly replace mkstemp if it is broken.
753 *****************************************************************/
755 int smb_mkstemp(char *template)
757 #if HAVE_SECURE_MKSTEMP
758 return mkstemp(template);
760 /* have a reasonable go at emulating it. Hope that
761 the system mktemp() isn't completly hopeless */
762 char *p = mktemp(template);
765 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
769 /*****************************************************************
770 malloc that aborts with smb_panic on fail or zero size.
771 *****************************************************************/
773 void *smb_xmalloc(size_t size)
777 smb_panic("smb_xmalloc: called with zero size.\n");
778 if ((p = malloc(size)) == NULL)
779 smb_panic("smb_xmalloc: malloc fail.\n");
784 Memdup with smb_panic on fail.
787 void *smb_xmemdup(const void *p, size_t size)
790 p2 = smb_xmalloc(size);
796 strdup that aborts on malloc fail.
799 char *smb_xstrdup(const char *s)
801 char *s1 = strdup(s);
803 smb_panic("smb_xstrdup: malloc fail\n");
809 vasprintf that aborts on malloc fail
812 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
819 n = vasprintf(ptr, format, ap2);
820 if (n == -1 || ! *ptr)
821 smb_panic("smb_xvasprintf: out of memory");
825 /*****************************************************************
826 Like strdup but for memory.
827 *****************************************************************/
829 void *memdup(const void *p, size_t size)
841 /*****************************************************************
842 Get local hostname and cache result.
843 *****************************************************************/
845 char *myhostname(TALLOC_CTX *mem_ctx)
848 myname = get_myname();
849 ret = talloc_strdup(mem_ctx, myname);
855 /*****************************************************************
856 A useful function for returning a path in the Samba lock directory.
857 *****************************************************************/
859 char *lock_path(TALLOC_CTX* mem_ctx, const char *name)
863 fname = talloc_strdup(mem_ctx, lp_lockdir());
864 trim_string(fname,"","/");
866 if (!directory_exist(fname,NULL))
869 fname = talloc_asprintf(mem_ctx, "%s/%s", fname, name);
875 * @brief Returns an absolute path to a file in the Samba lib directory.
877 * @param name File to find, relative to LIBDIR.
879 * @retval Pointer to a talloc'ed string containing the full path.
882 char *lib_path(TALLOC_CTX* mem_ctx, const char *name)
885 fname = talloc_asprintf(mem_ctx, "%s/%s", dyn_LIBDIR, name);
890 * @brief Returns the platform specific shared library extension.
892 * @retval Pointer to a static #fstring containing the extension.
895 const char *shlib_ext(void)
901 /*********************************************************
902 Recursive routine that is called by unix_wild_match.
903 *********************************************************/
905 static BOOL unix_do_match(char *regexp, char *str)
909 for( p = regexp; *p && *str; ) {
920 * Look for a character matching
921 * the one after the '*'.
925 return True; /* Automatic match */
928 while(*str && (*p != *str))
932 * Patch from weidel@multichart.de. In the case of the regexp
933 * '*XX*' we want to ensure there are at least 2 'X' characters
934 * in the string after the '*' for a match to be made.
941 * Eat all the characters that match, but count how many there were.
944 while(*str && (*p == *str)) {
950 * Now check that if the regexp had n identical characters that
951 * matchcount had at least that many matches.
954 while ( *(p+1) && (*(p+1) == *p)) {
959 if ( matchcount <= 0 )
963 str--; /* We've eaten the match char after the '*' */
965 if(unix_do_match(p, str))
987 if (!*p && str[0] == '.' && str[1] == 0)
990 if (!*str && *p == '?') {
996 if(!*str && (*p == '*' && p[1] == '\0'))