2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
25 #ifdef WITH_NISPLUS_HOME
26 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
28 * The following lines are needed due to buggy include files
29 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
30 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
31 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
32 * an enum in /usr/include/rpcsvc/nis.h.
39 #if defined(GROUP_OBJ)
43 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
45 #include <rpcsvc/nis.h>
47 #else /* !WITH_NISPLUS_HOME */
49 #include "rpcsvc/ypclnt.h"
51 #endif /* WITH_NISPLUS_HOME */
52 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
56 #undef Realloc /* SSLeay defines this and samba has a function of this name */
61 extern int DEBUGLEVEL;
63 int Protocol = PROTOCOL_COREPLUS;
65 /* a default finfo structure to ensure all fields are sensible */
66 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
68 /* this is used by the chaining code */
74 case handling on filenames
76 int case_default = CASE_LOWER;
78 /* the following control case operations - they are put here so the
79 client can link easily */
82 BOOL use_mangled_map = False;
83 BOOL short_case_preserve;
86 static enum remote_arch_types ra_type = RA_UNKNOWN;
87 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
89 pstring global_myname = "";
90 fstring global_myworkgroup = "";
91 char **my_netbios_names;
94 /****************************************************************************
95 find a suitable temporary directory. The result should be copied immediately
96 as it may be overwritten by a subsequent call
97 ****************************************************************************/
101 if ((p = getenv("TMPDIR"))) {
107 /****************************************************************************
108 determine whether we are in the specified group
109 ****************************************************************************/
111 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
115 if (group == current_gid) return(True);
117 for (i=0;i<ngroups;i++)
118 if (group == groups[i])
125 /****************************************************************************
126 like atoi but gets the value up to the separater character
127 ****************************************************************************/
128 char *Atoic(char *p, int *n, char *c)
130 if (!isdigit((int)*p))
132 DEBUG(5, ("Atoic: malformed number\n"));
138 while ((*p) && isdigit((int)*p))
143 if (strchr(c, *p) == NULL)
145 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
152 /*************************************************************************
153 reads a list of numbers
154 *************************************************************************/
155 char *get_numlist(char *p, uint32 **num, int *count)
159 if (num == NULL || count == NULL)
167 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':')
169 (*num) = Realloc((*num), ((*count)+1) * sizeof(uint32));
174 (*num)[(*count)] = val;
183 /*******************************************************************
184 check if a file exists - call vfs_file_exist for samba files
185 ********************************************************************/
186 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
189 if (!sbuf) sbuf = &st;
191 if (sys_stat(fname,sbuf) != 0)
194 return(S_ISREG(sbuf->st_mode));
197 /*******************************************************************
199 ********************************************************************/
200 int file_rename(char *from, char *to)
202 int rcode = rename (from, to);
206 /* Rename across filesystems needed. */
207 rcode = copy_reg (from, to);
212 /*******************************************************************
213 check a files mod time
214 ********************************************************************/
215 time_t file_modtime(char *fname)
219 if (sys_stat(fname,&st) != 0)
225 /*******************************************************************
226 check if a directory exists
227 ********************************************************************/
228 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
235 if (sys_stat(dname,st) != 0)
238 ret = S_ISDIR(st->st_mode);
244 /*******************************************************************
245 returns the size in bytes of the named file
246 ********************************************************************/
247 SMB_OFF_T get_file_size(char *file_name)
251 if(sys_stat(file_name,&buf) != 0)
252 return (SMB_OFF_T)-1;
256 /*******************************************************************
257 return a string representing an attribute for a file
258 ********************************************************************/
259 char *attrib_string(uint16 mode)
261 static fstring attrstr;
265 if (mode & aVOLID) fstrcat(attrstr,"V");
266 if (mode & aDIR) fstrcat(attrstr,"D");
267 if (mode & aARCH) fstrcat(attrstr,"A");
268 if (mode & aHIDDEN) fstrcat(attrstr,"H");
269 if (mode & aSYSTEM) fstrcat(attrstr,"S");
270 if (mode & aRONLY) fstrcat(attrstr,"R");
275 /*******************************************************************
276 show a smb message structure
277 ********************************************************************/
278 void show_msg(char *buf)
283 if (DEBUGLEVEL < 5) return;
285 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
287 (int)CVAL(buf,smb_com),
288 (int)CVAL(buf,smb_rcls),
289 (int)CVAL(buf,smb_reh),
290 (int)SVAL(buf,smb_err),
291 (int)CVAL(buf,smb_flg),
292 (int)SVAL(buf,smb_flg2)));
293 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
294 (int)SVAL(buf,smb_tid),
295 (int)SVAL(buf,smb_pid),
296 (int)SVAL(buf,smb_uid),
297 (int)SVAL(buf,smb_mid),
298 (int)CVAL(buf,smb_wct)));
300 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
302 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
303 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
306 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
308 DEBUG(5,("smb_bcc=%d\n",bcc));
310 if (DEBUGLEVEL < 10) return;
317 dump_data(10, smb_buf(buf), bcc);
320 /*******************************************************************
321 set the length and marker of an smb packet
322 ********************************************************************/
323 void smb_setlen(char *buf,int len)
325 _smb_setlen(buf,len);
333 /*******************************************************************
334 setup the word count and byte count for a smb message
335 ********************************************************************/
336 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
339 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
340 CVAL(buf,smb_wct) = num_words;
341 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
342 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
343 return (smb_size + num_words*2 + num_bytes);
346 /*******************************************************************
347 reduce a file name, removing .. elements.
348 ********************************************************************/
349 void dos_clean_name(char *s)
353 DEBUG(3,("dos_clean_name [%s]\n",s));
355 /* remove any double slashes */
356 all_string_sub(s, "\\\\", "\\", 0);
358 while ((p = strstr(s,"\\..\\")) != NULL)
365 if ((p=strrchr(s,'\\')) != NULL)
372 trim_string(s,NULL,"\\..");
374 all_string_sub(s, "\\.\\", "\\", 0);
377 /*******************************************************************
378 reduce a file name, removing .. elements.
379 ********************************************************************/
380 void unix_clean_name(char *s)
384 DEBUG(3,("unix_clean_name [%s]\n",s));
386 /* remove any double slashes */
387 all_string_sub(s, "//","/", 0);
389 /* Remove leading ./ characters */
390 if(strncmp(s, "./", 2) == 0) {
391 trim_string(s, "./", NULL);
396 while ((p = strstr(s,"/../")) != NULL)
403 if ((p=strrchr(s,'/')) != NULL)
410 trim_string(s,NULL,"/..");
413 /*******************************************************************
414 reduce a file name, removing .. elements and checking that
415 it is below dir in the heirachy. This uses dos_GetWd() and so must be run
416 on the system that has the referenced file system.
418 widelinks are allowed if widelinks is true
419 ********************************************************************/
421 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
431 BOOL relative = (*s != '/');
433 *dir2 = *wd = *base_name = *newname = 0;
438 /* can't have a leading .. */
439 if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
441 DEBUG(3,("Illegal file name? (%s)\n",s));
451 DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
453 /* remove any double slashes */
454 all_string_sub(s,"//","/",0);
456 pstrcpy(base_name,s);
457 p = strrchr(base_name,'/');
464 DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
468 if (dos_ChDir(dir) != 0)
470 DEBUG(0,("couldn't chdir to %s\n",dir));
474 if (!dos_GetWd(dir2))
476 DEBUG(0,("couldn't getwd for %s\n",dir));
481 if (p && (p != base_name))
484 if (strcmp(p+1,".")==0)
486 if (strcmp(p+1,"..")==0)
490 if (dos_ChDir(base_name) != 0)
493 DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,base_name));
497 if (!dos_GetWd(newname))
500 DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
504 if (p && (p != base_name))
506 pstrcat(newname,"/");
507 pstrcat(newname,p+1);
511 size_t l = strlen(dir2);
512 if (dir2[l-1] == '/')
515 if (strncmp(newname,dir2,l) != 0)
518 DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,(int)l));
524 if (newname[l] == '/')
525 pstrcpy(s,newname + l + 1);
527 pstrcpy(s,newname+l);
538 DEBUG(3,("reduced to %s\n",s));
544 /****************************************************************************
546 ****************************************************************************/
547 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
554 if ((mode & aDIR) != 0)
557 memset(buf+1,' ',11);
558 if ((p = strchr(mask2,'.')) != NULL)
561 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
562 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
566 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
568 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
570 put_dos_date(buf,22,date);
571 SSVAL(buf,26,size & 0xFFFF);
572 SSVAL(buf,28,(size >> 16)&0xFFFF);
573 StrnCpy(buf+30,fname,12);
576 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
580 /*******************************************************************
581 close the low 3 fd's and open dev/null in their place
582 ********************************************************************/
583 void close_low_fds(void)
591 /* try and use up these file descriptors, so silly
592 library routines writing to stdout etc won't cause havoc */
594 fd = sys_open("/dev/null",O_RDWR,0);
595 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
597 DEBUG(0,("Can't open /dev/null\n"));
601 DEBUG(0,("Didn't get file descriptor %d\n",i));
607 /****************************************************************************
608 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
612 ****************************************************************************/
613 int set_blocking(int fd, BOOL set)
617 #define FLAG_TO_SET O_NONBLOCK
620 #define FLAG_TO_SET O_NDELAY
622 #define FLAG_TO_SET FNDELAY
626 if((val = fcntl(fd, F_GETFL, 0)) == -1)
628 if(set) /* Turn blocking on - ie. clear nonblock flag */
632 return fcntl( fd, F_SETFL, val);
636 /****************************************************************************
637 transfer some data between two fd's
638 ****************************************************************************/
639 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n,char *header,int headlen,int align)
641 static char *buf=NULL;
646 DEBUG(4,("transfer_file n=%.0f (head=%d) called\n",(double)n,headlen));
649 size = lp_readsize();
650 size = MAX(size,1024);
653 while (!buf && size>0) {
654 buf = (char *)Realloc(buf,size+8);
659 DEBUG(0,("Can't allocate transfer buffer!\n"));
663 abuf = buf + (align%8);
670 int s = (int)MIN(n,(SMB_OFF_T)size);
675 if (header && (headlen >= MIN(s,1024))) {
685 if (header && headlen > 0)
687 ret = MIN(headlen,size);
688 memcpy(buf1,header,ret);
691 if (headlen <= 0) header = NULL;
695 ret += read(infd,buf1+ret,s-ret);
699 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
700 if (ret2 > 0) total += ret2;
701 /* if we can't write then dump excess data */
703 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
705 if (ret <= 0 || ret2 != ret)
713 /*******************************************************************
714 sleep for a specified number of milliseconds
715 ********************************************************************/
719 struct timeval tval,t1,t2;
726 tval.tv_sec = (t-tdiff)/1000;
727 tval.tv_usec = 1000*((t-tdiff)%1000);
731 sys_select_intr(0,&fds,&tval);
734 tdiff = TvalDiff(&t1,&t2);
739 /****************************************************************************
740 become a daemon, discarding the controlling terminal
741 ****************************************************************************/
742 void become_daemon(void)
748 /* detach from the terminal */
751 #elif defined(TIOCNOTTY)
753 int i = sys_open("/dev/tty", O_RDWR, 0);
755 ioctl(i, (int) TIOCNOTTY, (char *)0);
759 #endif /* HAVE_SETSID */
761 /* Close fd's 0,1,2. Needed if started by rsh */
766 /****************************************************************************
767 put up a yes/no prompt
768 ****************************************************************************/
774 if (!fgets(ans,sizeof(ans)-1,stdin))
777 if (*ans == 'y' || *ans == 'Y')
783 /****************************************************************************
784 set the length of a file from a filedescriptor.
785 Returns 0 on success, -1 on failure.
786 ****************************************************************************/
788 /* tpot vfs need to recode this function */
790 int set_filelen(int fd, SMB_OFF_T len)
792 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
793 extend a file with ftruncate. Provide alternate implementation
796 #ifdef HAVE_FTRUNCATE_EXTEND
797 return sys_ftruncate(fd, len);
801 SMB_OFF_T currpos = sys_lseek(fd, (SMB_OFF_T)0, SEEK_CUR);
805 /* Do an fstat to see if the file is longer than
806 the requested size (call ftruncate),
807 or shorter, in which case seek to len - 1 and write 1
809 if(sys_fstat(fd, &st)<0)
813 if (S_ISFIFO(st.st_mode))
817 if(st.st_size == len)
820 return sys_ftruncate(fd, len);
822 if(sys_lseek(fd, len-1, SEEK_SET) != len -1)
824 if(write(fd, &c, 1)!=1)
826 /* Seek to where we were */
827 if(sys_lseek(fd, currpos, SEEK_SET) != currpos)
835 /****************************************************************************
836 this is a version of setbuffer() for those machines that only have setvbuf
837 ****************************************************************************/
838 void setbuffer(FILE *f,char *buf,int bufsize)
840 setvbuf(f,buf,_IOFBF,bufsize);
844 /****************************************************************************
845 expand a pointer to be a particular size
846 ****************************************************************************/
847 void *Realloc(void *p,size_t size)
853 DEBUG(5,("Realloc asked for 0 bytes\n"));
858 ret = (void *)malloc(size);
860 ret = (void *)realloc(p,size);
863 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
869 /****************************************************************************
870 free memory, checks for NULL
871 ****************************************************************************/
872 void safe_free(void *p)
881 /****************************************************************************
882 get my own name and IP
883 ****************************************************************************/
884 BOOL get_myname(char *my_name)
890 /* get my host name */
891 if (gethostname(hostname, sizeof(hostname)) == -1) {
892 DEBUG(0,("gethostname failed\n"));
896 /* Ensure null termination. */
897 hostname[sizeof(hostname)-1] = '\0';
900 /* split off any parts after an initial . */
901 char *p = strchr(hostname,'.');
904 fstrcpy(my_name,hostname);
910 /****************************************************************************
911 interpret a protocol description string, with a default
912 ****************************************************************************/
913 int interpret_protocol(char *str,int def)
915 if (strequal(str,"NT1"))
916 return(PROTOCOL_NT1);
917 if (strequal(str,"LANMAN2"))
918 return(PROTOCOL_LANMAN2);
919 if (strequal(str,"LANMAN1"))
920 return(PROTOCOL_LANMAN1);
921 if (strequal(str,"CORE"))
922 return(PROTOCOL_CORE);
923 if (strequal(str,"COREPLUS"))
924 return(PROTOCOL_COREPLUS);
925 if (strequal(str,"CORE+"))
926 return(PROTOCOL_COREPLUS);
928 DEBUG(0,("Unrecognised protocol level %s\n",str));
933 /****************************************************************************
934 Return true if a string could be a pure IP address.
935 ****************************************************************************/
937 BOOL is_ipaddress(const char *str)
939 BOOL pure_address = True;
942 for (i=0; pure_address && str[i]; i++)
943 if (!(isdigit((int)str[i]) || str[i] == '.'))
944 pure_address = False;
946 /* Check that a pure number is not misinterpreted as an IP */
947 pure_address = pure_address && (strchr(str, '.') != NULL);
952 /****************************************************************************
953 interpret an internet address or name into an IP address in 4 byte form
954 ****************************************************************************/
956 uint32 interpret_addr(char *str)
961 if (strcmp(str,"0.0.0.0") == 0) return(0);
962 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
964 /* if it's in the form of an IP address then get the lib to interpret it */
965 if (is_ipaddress(str)) {
966 res = inet_addr(str);
968 /* otherwise assume it's a network name of some sort and use
970 if ((hp = Get_Hostbyname(str)) == 0) {
971 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
974 if(hp->h_addr == NULL) {
975 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s\n",str));
978 putip((char *)&res,(char *)hp->h_addr);
981 if (res == (uint32)-1) return(0);
986 /*******************************************************************
987 a convenient addition to interpret_addr()
988 ******************************************************************/
989 struct in_addr *interpret_addr2(char *str)
991 static struct in_addr ret;
992 uint32 a = interpret_addr(str);
997 /*******************************************************************
998 check if an IP is the 0.0.0.0
999 ******************************************************************/
1000 BOOL zero_ip(struct in_addr ip)
1003 putip((char *)&a,(char *)&ip);
1008 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1009 /******************************************************************
1010 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1011 Based on a fix from <Thomas.Hepper@icem.de>.
1012 *******************************************************************/
1014 static void strip_mount_options( pstring *str)
1019 while(*p && !isspace(*p))
1021 while(*p && isspace(*p))
1026 pstrcpy(tmp_str, p);
1027 pstrcpy(*str, tmp_str);
1032 /*******************************************************************
1033 Patch from jkf@soton.ac.uk
1034 Split Luke's automount_server into YP lookup and string splitter
1035 so can easily implement automount_path().
1036 As we may end up doing both, cache the last YP result.
1037 *******************************************************************/
1039 #ifdef WITH_NISPLUS_HOME
1040 static char *automount_lookup(char *user_name)
1042 static fstring last_key = "";
1043 static pstring last_value = "";
1045 char *nis_map = (char *)lp_nis_home_map_name();
1047 char nis_domain[NIS_MAXNAMELEN + 1];
1048 char buffer[NIS_MAXATTRVAL + 1];
1053 strncpy(nis_domain, (char *)nis_local_directory(), NIS_MAXNAMELEN);
1054 nis_domain[NIS_MAXNAMELEN] = '\0';
1056 DEBUG(5, ("NIS+ Domain: %s\n", nis_domain));
1058 if (strcmp(user_name, last_key))
1060 slprintf(buffer, sizeof(buffer)-1, "[%s=%s]%s.%s", "key", user_name, nis_map, nis_domain);
1061 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1063 if (result = nis_list(buffer, RETURN_RESULT, NULL, NULL))
1065 if (result->status != NIS_SUCCESS)
1067 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1068 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1072 object = result->objects.objects_val;
1073 if (object->zo_data.zo_type == ENTRY_OBJ)
1075 entry = &object->zo_data.objdata_u.en_data;
1076 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1077 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1079 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1080 pstring_sub(last_value, "&", user_name);
1081 fstrcpy(last_key, user_name);
1085 nis_freeresult(result);
1088 strip_mount_options(&last_value);
1090 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1093 #else /* WITH_NISPLUS_HOME */
1094 static char *automount_lookup(char *user_name)
1096 static fstring last_key = "";
1097 static pstring last_value = "";
1099 int nis_error; /* returned by yp all functions */
1100 char *nis_result; /* yp_match inits this */
1101 int nis_result_len; /* and set this */
1102 char *nis_domain; /* yp_get_default_domain inits this */
1103 char *nis_map = (char *)lp_nis_home_map_name();
1105 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
1107 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1111 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1113 if (!strcmp(user_name, last_key))
1115 nis_result = last_value;
1116 nis_result_len = strlen(last_value);
1121 if ((nis_error = yp_match(nis_domain, nis_map,
1122 user_name, strlen(user_name),
1123 &nis_result, &nis_result_len)) != 0)
1125 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1126 yperr_string(nis_error), user_name, nis_map));
1128 if (!nis_error && nis_result_len >= sizeof(pstring))
1130 nis_result_len = sizeof(pstring)-1;
1132 fstrcpy(last_key, user_name);
1133 strncpy(last_value, nis_result, nis_result_len);
1134 last_value[nis_result_len] = '\0';
1137 strip_mount_options(&last_value);
1139 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1142 #endif /* WITH_NISPLUS_HOME */
1146 /*******************************************************************
1147 are two IPs on the same subnet?
1148 ********************************************************************/
1149 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1151 uint32 net1,net2,nmask;
1153 nmask = ntohl(mask.s_addr);
1154 net1 = ntohl(ip1.s_addr);
1155 net2 = ntohl(ip2.s_addr);
1157 return((net1 & nmask) == (net2 & nmask));
1161 /****************************************************************************
1162 a wrapper for gethostbyname() that tries with all lower and all upper case
1163 if the initial name fails
1164 ****************************************************************************/
1165 struct hostent *Get_Hostbyname(const char *name)
1167 char *name2 = strdup(name);
1168 struct hostent *ret;
1172 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
1178 * This next test is redundent and causes some systems (with
1179 * broken isalnum() calls) problems.
1184 if (!isalnum(*name2))
1191 ret = sys_gethostbyname(name2);
1198 /* try with all lowercase */
1200 ret = sys_gethostbyname(name2);
1207 /* try with all uppercase */
1209 ret = sys_gethostbyname(name2);
1216 /* nothing works :-( */
1222 /****************************************************************************
1223 check if a process exists. Does this work on all unixes?
1224 ****************************************************************************/
1226 BOOL process_exists(pid_t pid)
1228 return(kill(pid,0) == 0 || errno != ESRCH);
1232 /*******************************************************************
1233 turn a uid into a user name
1234 ********************************************************************/
1235 char *uidtoname(uid_t uid)
1237 static char name[40];
1238 struct passwd *pass = sys_getpwuid(uid);
1239 if (pass) return(pass->pw_name);
1240 slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1245 /*******************************************************************
1246 turn a gid into a group name
1247 ********************************************************************/
1249 char *gidtoname(gid_t gid)
1251 static char name[40];
1252 struct group *grp = getgrgid(gid);
1253 if (grp) return(grp->gr_name);
1254 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1258 /*******************************************************************
1259 turn a user name into a uid
1260 ********************************************************************/
1261 uid_t nametouid(const char *name)
1263 struct passwd *pass;
1267 u = strtol(name, &p, 0);
1268 if (p != name) return u;
1270 pass = sys_getpwnam(name);
1271 if (pass) return(pass->pw_uid);
1275 /*******************************************************************
1276 turn a group name into a gid
1277 ********************************************************************/
1278 gid_t nametogid(const char *name)
1284 g = strtol(name, &p, 0);
1285 if (p != name) return g;
1287 grp = getgrnam(name);
1288 if (grp) return(grp->gr_gid);
1292 /*******************************************************************
1293 something really nasty happened - panic!
1294 ********************************************************************/
1295 void smb_panic(char *why)
1297 char *cmd = lp_panic_action();
1301 DEBUG(0,("PANIC: %s\n", why));
1307 /*******************************************************************
1308 a readdir wrapper which just returns the file name
1309 ********************************************************************/
1310 char *readdirname(DIR *p)
1312 SMB_STRUCT_DIRENT *ptr;
1315 if (!p) return(NULL);
1317 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1318 if (!ptr) return(NULL);
1320 dname = ptr->d_name;
1323 if (telldir(p) < 0) return(NULL);
1326 #ifdef HAVE_BROKEN_READDIR
1327 /* using /usr/ucb/cc is BAD */
1333 memcpy(buf, dname, NAMLEN(ptr)+1);
1340 /*******************************************************************
1341 Utility function used to decide if the last component
1342 of a path matches a (possibly wildcarded) entry in a namelist.
1343 ********************************************************************/
1345 BOOL is_in_path(char *name, name_compare_entry *namelist)
1347 pstring last_component;
1350 DEBUG(8, ("is_in_path: %s\n", name));
1352 /* if we have no list it's obviously not in the path */
1353 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1355 DEBUG(8,("is_in_path: no name list.\n"));
1359 /* Get the last component of the unix name. */
1360 p = strrchr(name, '/');
1361 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1362 last_component[sizeof(last_component)-1] = '\0';
1364 for(; namelist->name != NULL; namelist++)
1366 if(namelist->is_wild)
1368 if (mask_match(last_component, namelist->name, case_sensitive))
1370 DEBUG(8,("is_in_path: mask match succeeded\n"));
1376 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1377 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1379 DEBUG(8,("is_in_path: match succeeded\n"));
1384 DEBUG(8,("is_in_path: match not found\n"));
1389 /*******************************************************************
1390 Strip a '/' separated list into an array of
1391 name_compare_enties structures suitable for
1392 passing to is_in_path(). We do this for
1393 speed so we can pre-parse all the names in the list
1394 and don't do it for each call to is_in_path().
1395 namelist is modified here and is assumed to be
1396 a copy owned by the caller.
1397 We also check if the entry contains a wildcard to
1398 remove a potentially expensive call to mask_match
1400 ********************************************************************/
1402 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1405 char *nameptr = namelist;
1406 int num_entries = 0;
1409 (*ppname_array) = NULL;
1411 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1414 /* We need to make two passes over the string. The
1415 first to count the number of elements, the second
1420 if ( *nameptr == '/' )
1422 /* cope with multiple (useless) /s) */
1426 /* find the next / */
1427 name_end = strchr(nameptr, '/');
1429 /* oops - the last check for a / didn't find one. */
1430 if (name_end == NULL)
1433 /* next segment please */
1434 nameptr = name_end + 1;
1438 if(num_entries == 0)
1441 if(( (*ppname_array) = (name_compare_entry *)malloc(
1442 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1444 DEBUG(0,("set_namearray: malloc fail\n"));
1448 /* Now copy out the names */
1453 if ( *nameptr == '/' )
1455 /* cope with multiple (useless) /s) */
1459 /* find the next / */
1460 if ((name_end = strchr(nameptr, '/')) != NULL)
1465 /* oops - the last check for a / didn't find one. */
1466 if(name_end == NULL)
1469 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1470 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1472 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1476 /* next segment please */
1477 nameptr = name_end + 1;
1481 (*ppname_array)[i].name = NULL;
1486 /****************************************************************************
1487 routine to free a namearray.
1488 ****************************************************************************/
1490 void free_namearray(name_compare_entry *name_array)
1495 if(name_array->name != NULL)
1496 free(name_array->name);
1498 free((char *)name_array);
1501 /****************************************************************************
1502 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1503 is dealt with in posix.c
1504 ****************************************************************************/
1506 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1508 SMB_STRUCT_FLOCK lock;
1511 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1514 lock.l_whence = SEEK_SET;
1515 lock.l_start = offset;
1521 ret = fcntl(fd,op,&lock);
1524 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1527 if (op == SMB_F_GETLK)
1530 (lock.l_type != F_UNLCK) &&
1531 (lock.l_pid != 0) &&
1532 (lock.l_pid != sys_getpid()))
1534 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1538 /* it must be not locked or locked by me */
1542 /* a lock set or unset */
1545 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1546 (double)offset,(double)count,op,type,strerror(errno)));
1550 /* everything went OK */
1551 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1556 /*******************************************************************
1557 is the name specified one of my netbios names
1558 returns true is it is equal, false otherwise
1559 ********************************************************************/
1560 BOOL is_myname(char *s)
1565 for (n=0; my_netbios_names[n]; n++) {
1566 if (strequal(my_netbios_names[n], s))
1569 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1573 /*******************************************************************
1574 set the horrid remote_arch string based on an enum.
1575 ********************************************************************/
1576 void set_remote_arch(enum remote_arch_types type)
1578 extern fstring remote_arch;
1583 fstrcpy(remote_arch, "WfWg");
1586 fstrcpy(remote_arch, "OS2");
1589 fstrcpy(remote_arch, "Win95");
1592 fstrcpy(remote_arch, "WinNT");
1595 fstrcpy(remote_arch, "Win2K");
1598 fstrcpy(remote_arch,"Samba");
1601 ra_type = RA_UNKNOWN;
1602 fstrcpy(remote_arch, "UNKNOWN");
1607 /*******************************************************************
1608 Get the remote_arch type.
1609 ********************************************************************/
1610 enum remote_arch_types get_remote_arch(void)
1616 void out_ascii(FILE *f, unsigned char *buf,int len)
1621 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1625 void out_data(FILE *f,char *buf1,int len, int per_line)
1627 unsigned char *buf = (unsigned char *)buf1;
1634 fprintf(f, "[%03X] ",i);
1637 fprintf(f, "%02X ",(int)buf[i]);
1639 if (i%(per_line/2) == 0) fprintf(f, " ");
1640 if (i%per_line == 0)
1642 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1643 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1644 if (i<len) fprintf(f, "[%03X] ",i);
1647 if ((i%per_line) != 0)
1651 n = per_line - (i%per_line);
1653 if (n>(per_line/2)) fprintf(f, " ");
1658 n = MIN(per_line/2,i%per_line);
1659 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1660 n = (i%per_line) - n;
1661 if (n>0) out_ascii(f,&buf[i-n],n);
1666 void print_asc(int level, unsigned char *buf,int len)
1670 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1673 void dump_data(int level,char *buf1,int len)
1675 unsigned char *buf = (unsigned char *)buf1;
1679 DEBUG(level,("[%03X] ",i));
1681 DEBUG(level,("%02X ",(int)buf[i]));
1683 if (i%8 == 0) DEBUG(level,(" "));
1685 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1686 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1687 if (i<len) DEBUG(level,("[%03X] ",i));
1695 if (n>8) DEBUG(level,(" "));
1696 while (n--) DEBUG(level,(" "));
1699 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1701 if (n>0) print_asc(level,&buf[i-n],n);
1702 DEBUG(level,("\n"));
1706 char *tab_depth(int depth)
1708 static pstring spaces;
1709 memset(spaces, ' ', depth * 4);
1710 spaces[depth * 4] = 0;
1714 /*****************************************************************************
1715 * Provide a checksum on a string
1717 * Input: s - the null-terminated character string for which the checksum
1718 * will be calculated.
1720 * Output: The checksum value calculated for s.
1722 * ****************************************************************************
1724 int str_checksum(const char *s)
1732 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1737 } /* str_checksum */
1741 /*****************************************************************
1742 zero a memory area then free it. Used to catch bugs faster
1743 *****************************************************************/
1744 void zero_free(void *p, size_t size)
1751 /*****************************************************************
1752 set our open file limit to a requested max and return the limit
1753 *****************************************************************/
1754 int set_maxfiles(int requested_max)
1756 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1758 int saved_current_limit;
1760 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1761 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1764 return requested_max;
1768 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1769 * account for the extra fd we need
1770 * as well as the log files and standard
1771 * handles etc. Save the limit we want to set in case
1772 * we are running on an OS that doesn't support this limit (AIX)
1773 * which always returns RLIM_INFINITY for rlp.rlim_max.
1776 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1778 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1779 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1780 (int)rlp.rlim_cur, strerror(errno) ));
1782 return saved_current_limit;
1785 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1786 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1789 return saved_current_limit;
1792 #if defined(RLIM_INFINITY)
1793 if(rlp.rlim_cur == RLIM_INFINITY)
1794 return saved_current_limit;
1797 if((int)rlp.rlim_cur > saved_current_limit)
1798 return saved_current_limit;
1800 return rlp.rlim_cur;
1801 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1803 * No way to know - just guess...
1805 return requested_max;
1809 /*****************************************************************
1810 splits out the start of the key (HKLM or HKU) and the rest of the key
1811 *****************************************************************/
1812 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1816 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1823 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1825 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1827 (*reg_type) = HKEY_LOCAL_MACHINE;
1829 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1831 (*reg_type) = HKEY_USERS;
1835 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1839 if (next_token(NULL, tmp, "\n\r", sizeof(tmp)))
1841 fstrcpy(key_name, tmp);
1848 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1854 /*****************************************************************
1855 like mktemp() but make sure that no % characters are used
1856 % characters are bad for us because of the macro subs
1857 *****************************************************************/
1858 char *smbd_mktemp(char *template)
1860 char *p = mktemp(template);
1864 if (!p) return NULL;
1866 while ((p2=strchr(p,'%'))) {
1868 while (sys_stat(p,&st) == 0 && p2[0] < 'Z') {
1869 /* damn, it exists */
1873 /* oh well ... better return something */
1883 /*****************************************************************
1884 like strdup but for memory
1885 *****************************************************************/
1886 void *memdup(void *p, size_t size)
1889 if (size == 0) return NULL;
1891 if (!p2) return NULL;
1892 memcpy(p2, p, size);
1896 /*****************************************************************
1897 get local hostname and cache result
1898 *****************************************************************/
1899 char *myhostname(void)
1909 /*****************************************************************
1910 a useful function for returning a path in the Samba lock directory
1911 *****************************************************************/
1912 char *lock_path(char *name)
1914 static pstring fname;
1916 pstrcpy(fname,lp_lockdir());
1917 trim_string(fname,"","/");
1919 if (!directory_exist(fname,NULL)) {
1924 pstrcat(fname,name);
1929 /*******************************************************************
1930 Given a filename - get its directory name
1931 NB: Returned in static storage. Caveats:
1932 o Not safe in thread environment.
1933 o Caller must not free.
1934 o If caller wishes to preserve, they should copy.
1935 ********************************************************************/
1937 char *parent_dirname(const char *path)
1939 static pstring dirpath;
1945 pstrcpy(dirpath, path);
1946 p = strrchr(dirpath, '/'); /* Find final '/', if any */
1948 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1951 ++p; /* For root "/", leave "/" in place */
1958 /*******************************************************************
1959 determine if a pattern contains any Microsoft wildcard characters
1960 *******************************************************************/
1961 BOOL ms_has_wild(char *s)
1964 while ((c = *s++)) {
1978 /*******************************************************************
1979 a wrapper that handles case sensitivity and the special handling
1981 *******************************************************************/
1982 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1985 if (strcmp(string,"..") == 0) string = ".";
1986 if (strcmp(pattern,".") == 0) return False;
1988 if (is_case_sensitive) {
1989 return ms_fnmatch(pattern, string) == 0;
1992 fstrcpy(p2, pattern);
1993 fstrcpy(s2, string);
1996 return ms_fnmatch(p2, s2) == 0;
2003 /*******************************************************************
2004 This routine is a trick to immediately catch errors when debugging
2005 with insure. A xterm with a gdb is popped up when insure catches
2006 a error. It is Linux specific.
2007 ********************************************************************/
2008 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2013 pstring cmd = "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";
2015 slprintf(pidstr, sizeof(pidstr), "%d", sys_getpid());
2016 pstring_sub(cmd, "%d", pidstr);
2020 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2021 fn = dlsym(h, "_Insure_trap_error");
2024 ret = fn(a1, a2, a3, a4, a5, a6);