2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
6 Copyright (C) Jeremy Allison 2001
7 Copyright (C) Simo Sorce 2001
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
30 * The following lines are needed due to buggy include files
31 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
32 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
33 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
34 * an enum in /usr/include/rpcsvc/nis.h.
41 #if defined(GROUP_OBJ)
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
47 #include <rpcsvc/nis.h>
49 #else /* !WITH_NISPLUS_HOME */
51 #include "rpcsvc/ypclnt.h"
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
57 #include <openssl/ssl.h>
58 #undef Realloc /* SSLeay defines this and samba has a function of this name */
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")))
106 /****************************************************************************
107 Determine whether we are in the specified group.
108 ****************************************************************************/
110 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
114 if (group == current_gid)
117 for (i=0;i<ngroups;i++)
118 if (group == groups[i])
124 /****************************************************************************
125 Like atoi but gets the value up to the separator character.
126 ****************************************************************************/
128 char *Atoic(char *p, int *n, char *c)
130 if (!isdigit((int)*p)) {
131 DEBUG(5, ("Atoic: malformed number\n"));
137 while ((*p) && isdigit((int)*p))
140 if (strchr_m(c, *p) == NULL)
142 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
149 /*************************************************************************
150 Reads a list of numbers.
151 *************************************************************************/
153 char *get_numlist(char *p, uint32 **num, int *count)
157 if (num == NULL || count == NULL)
163 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
166 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
173 (*num)[(*count)] = val;
181 /*******************************************************************
182 Check if a file exists - call vfs_file_exist for samba files.
183 ********************************************************************/
185 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
191 if (sys_stat(fname,sbuf) != 0)
194 return(S_ISREG(sbuf->st_mode));
197 /*******************************************************************
198 Check a files mod time.
199 ********************************************************************/
201 time_t file_modtime(const char *fname)
205 if (sys_stat(fname,&st) != 0)
211 /*******************************************************************
212 Check if a directory exists.
213 ********************************************************************/
215 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
222 if (sys_stat(dname,st) != 0)
225 ret = S_ISDIR(st->st_mode);
231 /*******************************************************************
232 returns the size in bytes of the named file
233 ********************************************************************/
234 SMB_OFF_T get_file_size(char *file_name)
238 if(sys_stat(file_name,&buf) != 0)
239 return (SMB_OFF_T)-1;
243 /*******************************************************************
244 return a string representing an attribute for a file
245 ********************************************************************/
246 char *attrib_string(uint16 mode)
248 static fstring attrstr;
252 if (mode & aVOLID) fstrcat(attrstr,"V");
253 if (mode & aDIR) fstrcat(attrstr,"D");
254 if (mode & aARCH) fstrcat(attrstr,"A");
255 if (mode & aHIDDEN) fstrcat(attrstr,"H");
256 if (mode & aSYSTEM) fstrcat(attrstr,"S");
257 if (mode & aRONLY) fstrcat(attrstr,"R");
262 /*******************************************************************
263 show a smb message structure
264 ********************************************************************/
265 void show_msg(char *buf)
270 if (DEBUGLEVEL < 5) return;
272 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
274 (int)CVAL(buf,smb_com),
275 (int)CVAL(buf,smb_rcls),
276 (int)CVAL(buf,smb_reh),
277 (int)SVAL(buf,smb_err),
278 (int)CVAL(buf,smb_flg),
279 (int)SVAL(buf,smb_flg2)));
280 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
281 (int)SVAL(buf,smb_tid),
282 (int)SVAL(buf,smb_pid),
283 (int)SVAL(buf,smb_uid),
284 (int)SVAL(buf,smb_mid),
285 (int)CVAL(buf,smb_wct)));
287 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
289 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
290 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
293 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
295 DEBUG(5,("smb_bcc=%d\n",bcc));
297 if (DEBUGLEVEL < 10) return;
304 dump_data(10, smb_buf(buf), bcc);
307 /*******************************************************************
308 set the length and marker of an smb packet
309 ********************************************************************/
310 void smb_setlen(char *buf,int len)
312 _smb_setlen(buf,len);
320 /*******************************************************************
321 setup the word count and byte count for a smb message
322 ********************************************************************/
323 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
326 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
327 SCVAL(buf,smb_wct,num_words);
328 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
329 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
330 return (smb_size + num_words*2 + num_bytes);
333 /*******************************************************************
334 setup only the byte count for a smb message
335 ********************************************************************/
336 int set_message_bcc(char *buf,int num_bytes)
338 int num_words = CVAL(buf,smb_wct);
339 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
340 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
341 return (smb_size + num_words*2 + num_bytes);
344 /*******************************************************************
345 setup only the byte count for a smb message, using the end of the
347 ********************************************************************/
348 int set_message_end(void *outbuf,void *end_ptr)
350 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
353 /*******************************************************************
354 reduce a file name, removing .. elements.
355 ********************************************************************/
356 void dos_clean_name(char *s)
360 DEBUG(3,("dos_clean_name [%s]\n",s));
362 /* remove any double slashes */
363 all_string_sub(s, "\\\\", "\\", 0);
365 while ((p = strstr(s,"\\..\\")) != NULL)
372 if ((p=strrchr_m(s,'\\')) != NULL)
379 trim_string(s,NULL,"\\..");
381 all_string_sub(s, "\\.\\", "\\", 0);
384 /*******************************************************************
385 reduce a file name, removing .. elements.
386 ********************************************************************/
387 void unix_clean_name(char *s)
391 DEBUG(3,("unix_clean_name [%s]\n",s));
393 /* remove any double slashes */
394 all_string_sub(s, "//","/", 0);
396 /* Remove leading ./ characters */
397 if(strncmp(s, "./", 2) == 0) {
398 trim_string(s, "./", NULL);
403 while ((p = strstr(s,"/../")) != NULL)
410 if ((p=strrchr_m(s,'/')) != NULL)
417 trim_string(s,NULL,"/..");
420 /*******************************************************************
422 reduce a file name, removing or reducing /../ , /./ , // elements.
423 remove also any trailing . and /
424 return a new allocated string.
425 ********************************************************************/
426 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
429 smb_ucs2_t *p, *r, *t;
431 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
433 /* convert '\' to '/' */
435 if (!ns) return NULL;
438 /* remove all double slashes */
440 ns = all_string_sub_wa(p, "//", "/");
442 if (!ns) return NULL;
446 ns = all_string_sub_wa(p, "/./", "/");
448 if (!ns) return NULL;
450 /* reduce any /../ */
452 while (*t && (r = strstr_wa(t, "/.."))) {
454 if (*t == UCS2_CHAR('/') || *t == 0) {
456 p = strrchr_w(ns, UCS2_CHAR('/'));
459 else memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
464 /* remove any trailing /. */
465 trim_string_wa(ns, NULL, "/.");
467 /* remove any leading and trailing / */
468 trim_string_wa(ns, "/", "/");
473 /****************************************************************************
475 ****************************************************************************/
476 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
483 if ((mode & aDIR) != 0)
486 memset(buf+1,' ',11);
487 if ((p = strchr_m(mask2,'.')) != NULL)
490 push_ascii(buf+1,mask2,8, 0);
491 push_ascii(buf+9,p+1,3, 0);
495 push_ascii(buf+1,mask2,11, 0);
497 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
499 put_dos_date(buf,22,date);
500 SSVAL(buf,26,size & 0xFFFF);
501 SSVAL(buf,28,(size >> 16)&0xFFFF);
502 push_ascii(buf+30,fname,12, 0);
505 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
509 /*******************************************************************
510 close the low 3 fd's and open dev/null in their place
511 ********************************************************************/
512 void close_low_fds(void)
520 /* try and use up these file descriptors, so silly
521 library routines writing to stdout etc won't cause havoc */
523 fd = sys_open("/dev/null",O_RDWR,0);
524 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
526 DEBUG(0,("Can't open /dev/null\n"));
530 DEBUG(0,("Didn't get file descriptor %d\n",i));
536 /****************************************************************************
537 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
541 ****************************************************************************/
542 int set_blocking(int fd, BOOL set)
546 #define FLAG_TO_SET O_NONBLOCK
549 #define FLAG_TO_SET O_NDELAY
551 #define FLAG_TO_SET FNDELAY
555 if((val = fcntl(fd, F_GETFL, 0)) == -1)
557 if(set) /* Turn blocking on - ie. clear nonblock flag */
561 return fcntl( fd, F_SETFL, val);
565 /****************************************************************************
566 Transfer some data between two fd's.
567 ****************************************************************************/
569 #ifndef TRANSFER_BUF_SIZE
570 #define TRANSFER_BUF_SIZE 65536
573 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
574 ssize_t (*write_fn)(int, const void *, size_t))
580 size_t num_to_read_thistime;
581 size_t num_written = 0;
583 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
587 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
589 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
590 if (read_ret == -1) {
591 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
600 while (num_written < read_ret) {
601 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
603 if (write_ret == -1) {
604 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
609 return (ssize_t)total;
611 num_written += (size_t)write_ret;
614 total += (size_t)read_ret;
618 return (ssize_t)total;
621 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
623 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, read, write);
626 /*******************************************************************
627 Sleep for a specified number of milliseconds.
628 ********************************************************************/
633 struct timeval tval,t1,t2;
640 tval.tv_sec = (t-tdiff)/1000;
641 tval.tv_usec = 1000*((t-tdiff)%1000);
645 sys_select_intr(0,&fds,&tval);
648 tdiff = TvalDiff(&t1,&t2);
652 /****************************************************************************
653 Become a daemon, discarding the controlling terminal.
654 ****************************************************************************/
656 void become_daemon(void)
662 /* detach from the terminal */
665 #elif defined(TIOCNOTTY)
667 int i = sys_open("/dev/tty", O_RDWR, 0);
669 ioctl(i, (int) TIOCNOTTY, (char *)0);
673 #endif /* HAVE_SETSID */
675 /* Close fd's 0,1,2. Needed if started by rsh */
680 /****************************************************************************
681 put up a yes/no prompt
682 ****************************************************************************/
688 if (!fgets(ans,sizeof(ans)-1,stdin))
691 if (*ans == 'y' || *ans == 'Y')
697 /****************************************************************************
698 Expand a pointer to be a particular size.
699 ****************************************************************************/
701 void *Realloc(void *p,size_t size)
707 DEBUG(5,("Realloc asked for 0 bytes\n"));
712 ret = (void *)malloc(size);
714 ret = (void *)realloc(p,size);
717 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
722 /****************************************************************************
723 Free memory, checks for NULL.
724 use directly SAFE_FREE()
725 exist only because we need to pass a function pointer somewhere --SSS
726 ****************************************************************************/
728 void safe_free(void *p)
733 /****************************************************************************
734 Get my own name and IP.
735 ****************************************************************************/
737 BOOL get_myname(char *my_name)
743 /* get my host name */
744 if (gethostname(hostname, sizeof(hostname)) == -1) {
745 DEBUG(0,("gethostname failed\n"));
749 /* Ensure null termination. */
750 hostname[sizeof(hostname)-1] = '\0';
753 /* split off any parts after an initial . */
754 char *p = strchr_m(hostname,'.');
759 fstrcpy(my_name,hostname);
765 /****************************************************************************
766 Interpret a protocol description string, with a default.
767 ****************************************************************************/
769 int interpret_protocol(char *str,int def)
771 if (strequal(str,"NT1"))
772 return(PROTOCOL_NT1);
773 if (strequal(str,"LANMAN2"))
774 return(PROTOCOL_LANMAN2);
775 if (strequal(str,"LANMAN1"))
776 return(PROTOCOL_LANMAN1);
777 if (strequal(str,"CORE"))
778 return(PROTOCOL_CORE);
779 if (strequal(str,"COREPLUS"))
780 return(PROTOCOL_COREPLUS);
781 if (strequal(str,"CORE+"))
782 return(PROTOCOL_COREPLUS);
784 DEBUG(0,("Unrecognised protocol level %s\n",str));
789 /****************************************************************************
790 Return true if a string could be a pure IP address.
791 ****************************************************************************/
793 BOOL is_ipaddress(const char *str)
795 BOOL pure_address = True;
798 for (i=0; pure_address && str[i]; i++)
799 if (!(isdigit((int)str[i]) || str[i] == '.'))
800 pure_address = False;
802 /* Check that a pure number is not misinterpreted as an IP */
803 pure_address = pure_address && (strchr_m(str, '.') != NULL);
808 /****************************************************************************
809 interpret an internet address or name into an IP address in 4 byte form
810 ****************************************************************************/
812 uint32 interpret_addr(const char *str)
817 if (strcmp(str,"0.0.0.0") == 0) return(0);
818 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
820 /* if it's in the form of an IP address then get the lib to interpret it */
821 if (is_ipaddress(str)) {
822 res = inet_addr(str);
824 /* otherwise assume it's a network name of some sort and use
826 if ((hp = sys_gethostbyname(str)) == 0) {
827 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
830 if(hp->h_addr == NULL) {
831 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
834 putip((char *)&res,(char *)hp->h_addr);
837 if (res == (uint32)-1) return(0);
842 /*******************************************************************
843 a convenient addition to interpret_addr()
844 ******************************************************************/
845 struct in_addr *interpret_addr2(const char *str)
847 static struct in_addr ret;
848 uint32 a = interpret_addr(str);
853 /*******************************************************************
854 check if an IP is the 0.0.0.0
855 ******************************************************************/
856 BOOL is_zero_ip(struct in_addr ip)
859 putip((char *)&a,(char *)&ip);
863 /* Set an IP to 0.0.0.0 */
865 void zero_ip(struct in_addr *ip)
868 static struct in_addr ipzero;
871 ipzero = *interpret_addr2("0.0.0.0");
878 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
879 /******************************************************************
880 Remove any mount options such as -rsize=2048,wsize=2048 etc.
881 Based on a fix from <Thomas.Hepper@icem.de>.
882 *******************************************************************/
884 static void strip_mount_options( pstring *str)
889 while(*p && !isspace(*p))
891 while(*p && isspace(*p))
897 pstrcpy(*str, tmp_str);
902 /*******************************************************************
903 Patch from jkf@soton.ac.uk
904 Split Luke's automount_server into YP lookup and string splitter
905 so can easily implement automount_path().
906 As we may end up doing both, cache the last YP result.
907 *******************************************************************/
909 #ifdef WITH_NISPLUS_HOME
910 char *automount_lookup(const char *user_name)
912 static fstring last_key = "";
913 static pstring last_value = "";
915 char *nis_map = (char *)lp_nis_home_map_name();
917 char buffer[NIS_MAXATTRVAL + 1];
922 if (strcmp(user_name, last_key))
924 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
925 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
927 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
929 if (result->status != NIS_SUCCESS)
931 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
932 fstrcpy(last_key, ""); pstrcpy(last_value, "");
936 object = result->objects.objects_val;
937 if (object->zo_data.zo_type == ENTRY_OBJ)
939 entry = &object->zo_data.objdata_u.en_data;
940 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
941 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
943 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
944 pstring_sub(last_value, "&", user_name);
945 fstrcpy(last_key, user_name);
949 nis_freeresult(result);
952 strip_mount_options(&last_value);
954 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
957 #else /* WITH_NISPLUS_HOME */
958 char *automount_lookup(const char *user_name)
960 static fstring last_key = "";
961 static pstring last_value = "";
963 int nis_error; /* returned by yp all functions */
964 char *nis_result; /* yp_match inits this */
965 int nis_result_len; /* and set this */
966 char *nis_domain; /* yp_get_default_domain inits this */
967 char *nis_map = (char *)lp_nis_home_map_name();
969 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
970 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
974 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
976 if (!strcmp(user_name, last_key)) {
977 nis_result = last_value;
978 nis_result_len = strlen(last_value);
983 if ((nis_error = yp_match(nis_domain, nis_map,
984 user_name, strlen(user_name),
985 &nis_result, &nis_result_len)) == 0) {
986 if (!nis_error && nis_result_len >= sizeof(pstring)) {
987 nis_result_len = sizeof(pstring)-1;
989 fstrcpy(last_key, user_name);
990 strncpy(last_value, nis_result, nis_result_len);
991 last_value[nis_result_len] = '\0';
992 strip_mount_options(&last_value);
994 } else if(nis_error == YPERR_KEY) {
996 /* If Key lookup fails user home server is not in nis_map
997 use default information for server, and home directory */
999 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1000 user_name, nis_map));
1001 DEBUG(3, ("using defaults for server and home directory\n"));
1003 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1004 yperr_string(nis_error), user_name, nis_map));
1009 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1012 #endif /* WITH_NISPLUS_HOME */
1016 /*******************************************************************
1017 are two IPs on the same subnet?
1018 ********************************************************************/
1019 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1021 uint32 net1,net2,nmask;
1023 nmask = ntohl(mask.s_addr);
1024 net1 = ntohl(ip1.s_addr);
1025 net2 = ntohl(ip2.s_addr);
1027 return((net1 & nmask) == (net2 & nmask));
1031 /****************************************************************************
1032 check if a process exists. Does this work on all unixes?
1033 ****************************************************************************/
1035 BOOL process_exists(pid_t pid)
1037 return(kill(pid,0) == 0 || errno != ESRCH);
1041 /*******************************************************************
1042 Convert a uid into a user name.
1043 ********************************************************************/
1045 char *uidtoname(uid_t uid)
1047 static fstring name;
1048 struct passwd *pass;
1050 if (winbind_uidtoname(name, uid))
1053 pass = sys_getpwuid(uid);
1054 if (pass) return(pass->pw_name);
1055 slprintf(name, sizeof(name) - 1, "%d",(int)uid);
1060 /*******************************************************************
1061 Convert a gid into a group name.
1062 ********************************************************************/
1064 char *gidtoname(gid_t gid)
1066 static fstring name;
1069 if (winbind_gidtoname(name, gid))
1072 grp = getgrgid(gid);
1073 if (grp) return(grp->gr_name);
1074 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1078 /*******************************************************************
1079 Convert a user name into a uid. If winbindd is present uses this.
1080 ********************************************************************/
1082 uid_t nametouid(char *name)
1084 struct passwd *pass;
1088 u = (uid_t)strtol(name, &p, 0);
1089 if ((p != name) && (*p == '\0'))
1092 if (winbind_nametouid(&u, name))
1095 pass = getpwnam_alloc(name);
1097 return(pass->pw_uid);
1103 /*******************************************************************
1104 Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1105 is present does a shortcut lookup...
1106 ********************************************************************/
1108 gid_t nametogid(const char *name)
1114 g = (gid_t)strtol(name, &p, 0);
1115 if ((p != name) && (*p == '\0'))
1118 if (winbind_nametogid(&g, name))
1121 grp = getgrnam(name);
1123 return(grp->gr_gid);
1127 /*******************************************************************
1128 something really nasty happened - panic!
1129 ********************************************************************/
1130 void smb_panic(char *why)
1132 char *cmd = lp_panic_action();
1136 DEBUG(0,("PANIC: %s\n", why));
1142 /*******************************************************************
1143 a readdir wrapper which just returns the file name
1144 ********************************************************************/
1145 char *readdirname(DIR *p)
1147 SMB_STRUCT_DIRENT *ptr;
1150 if (!p) return(NULL);
1152 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1153 if (!ptr) return(NULL);
1155 dname = ptr->d_name;
1158 if (telldir(p) < 0) return(NULL);
1161 #ifdef HAVE_BROKEN_READDIR
1162 /* using /usr/ucb/cc is BAD */
1168 int len = NAMLEN(ptr);
1169 memcpy(buf, dname, len);
1177 /*******************************************************************
1178 Utility function used to decide if the last component
1179 of a path matches a (possibly wildcarded) entry in a namelist.
1180 ********************************************************************/
1182 BOOL is_in_path(char *name, name_compare_entry *namelist)
1184 pstring last_component;
1187 DEBUG(8, ("is_in_path: %s\n", name));
1189 /* if we have no list it's obviously not in the path */
1190 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1192 DEBUG(8,("is_in_path: no name list.\n"));
1196 /* Get the last component of the unix name. */
1197 p = strrchr_m(name, '/');
1198 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1199 last_component[sizeof(last_component)-1] = '\0';
1201 for(; namelist->name != NULL; namelist++)
1203 if(namelist->is_wild)
1205 if (mask_match(last_component, namelist->name, case_sensitive))
1207 DEBUG(8,("is_in_path: mask match succeeded\n"));
1213 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1214 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1216 DEBUG(8,("is_in_path: match succeeded\n"));
1221 DEBUG(8,("is_in_path: match not found\n"));
1226 /*******************************************************************
1227 Strip a '/' separated list into an array of
1228 name_compare_enties structures suitable for
1229 passing to is_in_path(). We do this for
1230 speed so we can pre-parse all the names in the list
1231 and don't do it for each call to is_in_path().
1232 namelist is modified here and is assumed to be
1233 a copy owned by the caller.
1234 We also check if the entry contains a wildcard to
1235 remove a potentially expensive call to mask_match
1237 ********************************************************************/
1239 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1242 char *nameptr = namelist;
1243 int num_entries = 0;
1246 (*ppname_array) = NULL;
1248 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1251 /* We need to make two passes over the string. The
1252 first to count the number of elements, the second
1257 if ( *nameptr == '/' )
1259 /* cope with multiple (useless) /s) */
1263 /* find the next / */
1264 name_end = strchr_m(nameptr, '/');
1266 /* oops - the last check for a / didn't find one. */
1267 if (name_end == NULL)
1270 /* next segment please */
1271 nameptr = name_end + 1;
1275 if(num_entries == 0)
1278 if(( (*ppname_array) = (name_compare_entry *)malloc(
1279 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1281 DEBUG(0,("set_namearray: malloc fail\n"));
1285 /* Now copy out the names */
1290 if ( *nameptr == '/' )
1292 /* cope with multiple (useless) /s) */
1296 /* find the next / */
1297 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1302 /* oops - the last check for a / didn't find one. */
1303 if(name_end == NULL)
1306 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1307 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1309 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1313 /* next segment please */
1314 nameptr = name_end + 1;
1318 (*ppname_array)[i].name = NULL;
1323 /****************************************************************************
1324 routine to free a namearray.
1325 ****************************************************************************/
1327 void free_namearray(name_compare_entry *name_array)
1329 if(name_array == NULL)
1332 SAFE_FREE(name_array->name);
1333 SAFE_FREE(name_array);
1336 /****************************************************************************
1337 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1338 is dealt with in posix.c
1339 ****************************************************************************/
1341 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1343 SMB_STRUCT_FLOCK lock;
1346 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1349 lock.l_whence = SEEK_SET;
1350 lock.l_start = offset;
1356 ret = fcntl(fd,op,&lock);
1359 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1362 if (op == SMB_F_GETLK)
1365 (lock.l_type != F_UNLCK) &&
1366 (lock.l_pid != 0) &&
1367 (lock.l_pid != sys_getpid()))
1369 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1373 /* it must be not locked or locked by me */
1377 /* a lock set or unset */
1380 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1381 (double)offset,(double)count,op,type,strerror(errno)));
1385 /* everything went OK */
1386 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1391 /*******************************************************************
1392 is the name specified one of my netbios names
1393 returns true is it is equal, false otherwise
1394 ********************************************************************/
1395 BOOL is_myname(char *s)
1400 for (n=0; my_netbios_names[n]; n++) {
1401 if (strequal(my_netbios_names[n], s))
1404 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1408 BOOL is_myname_or_ipaddr(char *s)
1412 /* optimize for the common case */
1413 if (strequal(s, global_myname))
1416 /* maybe its an IP address? */
1417 if (is_ipaddress(s))
1419 struct iface_struct nics[MAX_INTERFACES];
1423 ip = interpret_addr(s);
1424 if ((ip==0) || (ip==0xffffffff))
1427 n = get_interfaces(nics, MAX_INTERFACES);
1428 for (i=0; i<n; i++) {
1429 if (ip == nics[i].ip.s_addr)
1434 /* check for an alias */
1435 ptr = lp_netbios_aliases();
1436 for ( ; *ptr; ptr++ )
1438 if (StrCaseCmp(s, *ptr) == 0)
1449 /*******************************************************************
1450 set the horrid remote_arch string based on an enum.
1451 ********************************************************************/
1452 void set_remote_arch(enum remote_arch_types type)
1454 extern fstring remote_arch;
1459 fstrcpy(remote_arch, "WfWg");
1462 fstrcpy(remote_arch, "OS2");
1465 fstrcpy(remote_arch, "Win95");
1468 fstrcpy(remote_arch, "WinNT");
1471 fstrcpy(remote_arch, "Win2K");
1474 fstrcpy(remote_arch,"Samba");
1477 ra_type = RA_UNKNOWN;
1478 fstrcpy(remote_arch, "UNKNOWN");
1483 /*******************************************************************
1484 Get the remote_arch type.
1485 ********************************************************************/
1486 enum remote_arch_types get_remote_arch(void)
1492 void out_ascii(FILE *f, unsigned char *buf,int len)
1497 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1501 void out_data(FILE *f,char *buf1,int len, int per_line)
1503 unsigned char *buf = (unsigned char *)buf1;
1510 fprintf(f, "[%03X] ",i);
1513 fprintf(f, "%02X ",(int)buf[i]);
1515 if (i%(per_line/2) == 0) fprintf(f, " ");
1516 if (i%per_line == 0)
1518 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1519 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1520 if (i<len) fprintf(f, "[%03X] ",i);
1523 if ((i%per_line) != 0)
1527 n = per_line - (i%per_line);
1529 if (n>(per_line/2)) fprintf(f, " ");
1534 n = MIN(per_line/2,i%per_line);
1535 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1536 n = (i%per_line) - n;
1537 if (n>0) out_ascii(f,&buf[i-n],n);
1542 void print_asc(int level, const unsigned char *buf,int len)
1546 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1549 void dump_data(int level, const char *buf1,int len)
1551 const unsigned char *buf = (const unsigned char *)buf1;
1555 DEBUG(level,("[%03X] ",i));
1557 DEBUG(level,("%02X ",(int)buf[i]));
1559 if (i%8 == 0) DEBUG(level,(" "));
1561 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1562 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1563 if (i<len) DEBUG(level,("[%03X] ",i));
1571 if (n>8) DEBUG(level,(" "));
1572 while (n--) DEBUG(level,(" "));
1575 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1577 if (n>0) print_asc(level,&buf[i-n],n);
1578 DEBUG(level,("\n"));
1582 char *tab_depth(int depth)
1584 static pstring spaces;
1585 memset(spaces, ' ', depth * 4);
1586 spaces[depth * 4] = 0;
1590 /*****************************************************************************
1591 * Provide a checksum on a string
1593 * Input: s - the null-terminated character string for which the checksum
1594 * will be calculated.
1596 * Output: The checksum value calculated for s.
1598 * ****************************************************************************
1600 int str_checksum(const char *s)
1608 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1613 } /* str_checksum */
1617 /*****************************************************************
1618 zero a memory area then free it. Used to catch bugs faster
1619 *****************************************************************/
1620 void zero_free(void *p, size_t size)
1627 /*****************************************************************
1628 set our open file limit to a requested max and return the limit
1629 *****************************************************************/
1630 int set_maxfiles(int requested_max)
1632 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1634 int saved_current_limit;
1636 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1637 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1640 return requested_max;
1644 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1645 * account for the extra fd we need
1646 * as well as the log files and standard
1647 * handles etc. Save the limit we want to set in case
1648 * we are running on an OS that doesn't support this limit (AIX)
1649 * which always returns RLIM_INFINITY for rlp.rlim_max.
1652 /* Try raising the hard (max) limit to the requested amount. */
1654 #if defined(RLIM_INFINITY)
1655 if (rlp.rlim_max != RLIM_INFINITY) {
1656 int orig_max = rlp.rlim_max;
1658 if ( rlp.rlim_max < requested_max )
1659 rlp.rlim_max = requested_max;
1661 /* This failing is not an error - many systems (Linux) don't
1662 support our default request of 10,000 open files. JRA. */
1664 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1665 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1666 (int)rlp.rlim_max, strerror(errno) ));
1668 /* Set failed - restore original value from get. */
1669 rlp.rlim_max = orig_max;
1674 /* Now try setting the soft (current) limit. */
1676 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1678 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1679 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1680 (int)rlp.rlim_cur, strerror(errno) ));
1682 return saved_current_limit;
1685 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1686 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1689 return saved_current_limit;
1692 #if defined(RLIM_INFINITY)
1693 if(rlp.rlim_cur == RLIM_INFINITY)
1694 return saved_current_limit;
1697 if((int)rlp.rlim_cur > saved_current_limit)
1698 return saved_current_limit;
1700 return rlp.rlim_cur;
1701 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1703 * No way to know - just guess...
1705 return requested_max;
1709 /*****************************************************************
1710 splits out the start of the key (HKLM or HKU) and the rest of the key
1711 *****************************************************************/
1712 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1716 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1723 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1725 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1727 (*reg_type) = HKEY_LOCAL_MACHINE;
1729 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1731 (*reg_type) = HKEY_USERS;
1735 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1739 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1741 fstrcpy(key_name, tmp);
1748 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1754 /*****************************************************************
1755 possibly replace mkstemp if it is broken
1756 *****************************************************************/
1757 int smb_mkstemp(char *template)
1759 #if HAVE_SECURE_MKSTEMP
1760 return mkstemp(template);
1762 /* have a reasonable go at emulating it. Hope that
1763 the system mktemp() isn't completly hopeless */
1764 char *p = mktemp(template);
1766 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1772 malloc that aborts with smb_panic on fail or zero size.
1774 void *smb_xmalloc(size_t size)
1778 smb_panic("smb_xmalloc: called with zero size.\n");
1779 if ((p = malloc(size)) == NULL)
1780 smb_panic("smb_xmalloc: malloc fail.\n");
1785 Memdup with smb_panic on fail.
1787 void *smb_xmemdup(const void *p, size_t size)
1790 p2 = smb_xmalloc(size);
1791 memcpy(p2, p, size);
1796 strdup that aborts on malloc fail.
1798 char *smb_xstrdup(const char *s)
1800 char *s1 = strdup(s);
1802 smb_panic("smb_xstrdup: malloc fail\n");
1807 vasprintf that aborts on malloc fail
1809 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1812 n = vasprintf(ptr, format, ap);
1813 if (n == -1 || ! *ptr) {
1814 smb_panic("smb_xvasprintf: out of memory");
1819 /*****************************************************************
1820 like strdup but for memory
1821 *****************************************************************/
1822 void *memdup(const void *p, size_t size)
1825 if (size == 0) return NULL;
1827 if (!p2) return NULL;
1828 memcpy(p2, p, size);
1832 /*****************************************************************
1833 get local hostname and cache result
1834 *****************************************************************/
1835 char *myhostname(void)
1845 /*****************************************************************
1846 a useful function for returning a path in the Samba lock directory
1847 *****************************************************************/
1848 char *lock_path(char *name)
1850 static pstring fname;
1852 pstrcpy(fname,lp_lockdir());
1853 trim_string(fname,"","/");
1855 if (!directory_exist(fname,NULL)) {
1860 pstrcat(fname,name);
1867 * @brief Returns an absolute path to a file in the Samba lib directory.
1869 * @param name File to find, relative to LIBDIR.
1871 * @retval Pointer to a static #pstring containing the full path.
1873 char *lib_path(char *name)
1875 static pstring fname;
1876 snprintf(fname, sizeof(fname), "%s/%s", dyn_LIBDIR, name);
1880 /*******************************************************************
1881 Given a filename - get its directory name
1882 NB: Returned in static storage. Caveats:
1883 o Not safe in thread environment.
1884 o Caller must not free.
1885 o If caller wishes to preserve, they should copy.
1886 ********************************************************************/
1888 char *parent_dirname(const char *path)
1890 static pstring dirpath;
1896 pstrcpy(dirpath, path);
1897 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
1899 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1902 ++p; /* For root "/", leave "/" in place */
1909 /*******************************************************************
1910 determine if a pattern contains any Microsoft wildcard characters
1911 *******************************************************************/
1912 BOOL ms_has_wild(char *s)
1915 while ((c = *s++)) {
1928 BOOL ms_has_wild_w(const smb_ucs2_t *s)
1931 while ((c = *s++)) {
1933 case UCS2_CHAR('*'):
1934 case UCS2_CHAR('?'):
1935 case UCS2_CHAR('<'):
1936 case UCS2_CHAR('>'):
1937 case UCS2_CHAR('"'):
1944 /*******************************************************************
1945 a wrapper that handles case sensitivity and the special handling
1947 *******************************************************************/
1948 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1952 if (strcmp(string,"..") == 0) string = ".";
1953 if (strcmp(pattern,".") == 0) return False;
1955 if (is_case_sensitive) {
1956 return ms_fnmatch(pattern, string, Protocol) == 0;
1959 fstrcpy(p2, pattern);
1960 fstrcpy(s2, string);
1963 return ms_fnmatch(p2, s2, Protocol) == 0;
1966 /*********************************************************
1967 Recursive routine that is called by unix_wild_match.
1968 *********************************************************/
1970 static BOOL unix_do_match(char *regexp, char *str)
1974 for( p = regexp; *p && *str; ) {
1985 * Look for a character matching
1986 * the one after the '*'.
1990 return True; /* Automatic match */
1993 while(*str && (*p != *str))
1997 * Patch from weidel@multichart.de. In the case of the regexp
1998 * '*XX*' we want to ensure there are at least 2 'X' characters
1999 * in the string after the '*' for a match to be made.
2006 * Eat all the characters that match, but count how many there were.
2009 while(*str && (*p == *str)) {
2015 * Now check that if the regexp had n identical characters that
2016 * matchcount had at least that many matches.
2019 while ( *(p+1) && (*(p+1) == *p)) {
2024 if ( matchcount <= 0 )
2028 str--; /* We've eaten the match char after the '*' */
2030 if(unix_do_match(p, str))
2052 if (!*p && str[0] == '.' && str[1] == 0)
2055 if (!*str && *p == '?') {
2061 if(!*str && (*p == '*' && p[1] == '\0'))
2067 /*******************************************************************
2068 Simple case insensitive interface to a UNIX wildcard matcher.
2069 *******************************************************************/
2071 BOOL unix_wild_match(char *pattern, char *string)
2076 pstrcpy(p2, pattern);
2077 pstrcpy(s2, string);
2081 /* Remove any *? and ** from the pattern as they are meaningless */
2082 for(p = p2; *p; p++)
2083 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2084 pstrcpy( &p[1], &p[2]);
2086 if (strequal(p2,"*"))
2089 return unix_do_match(p2, s2) == 0;
2092 /*******************************************************************
2094 *******************************************************************/
2095 static void free_data_blob(DATA_BLOB *d)
2097 if ((d) && (d->free)) {
2102 /*******************************************************************
2103 construct a data blob, must be freed with data_blob_free()
2104 you can pass NULL for p and get a blank data blob
2105 *******************************************************************/
2106 DATA_BLOB data_blob(const void *p, size_t length)
2116 ret.data = smb_xmemdup(p, length);
2118 ret.data = smb_xmalloc(length);
2120 ret.length = length;
2121 ret.free = free_data_blob;
2125 /*******************************************************************
2126 construct a data blob, using supplied TALLOC_CTX
2127 *******************************************************************/
2128 DATA_BLOB data_blob_talloc(TALLOC_CTX *mem_ctx, const void *p, size_t length)
2132 if (!p || !length) {
2137 ret.data = talloc_memdup(mem_ctx, p, length);
2138 if (ret.data == NULL)
2139 smb_panic("data_blob_talloc: talloc_memdup failed.\n");
2141 ret.length = length;
2146 /*******************************************************************
2148 *******************************************************************/
2149 void data_blob_free(DATA_BLOB *d)
2159 /*******************************************************************
2160 clear a DATA_BLOB's contents
2161 *******************************************************************/
2162 void data_blob_clear(DATA_BLOB *d)
2165 memset(d->data, 0, d->length);
2169 /*******************************************************************
2170 free a data blob and clear its contents
2171 *******************************************************************/
2172 void data_blob_clear_free(DATA_BLOB *d)
2180 /*******************************************************************
2181 This routine is a trick to immediately catch errors when debugging
2182 with insure. A xterm with a gdb is popped up when insure catches
2183 a error. It is Linux specific.
2184 ********************************************************************/
2185 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2190 /* you can get /usr/bin/backtrace from
2191 http://samba.org/ftp/unpacked/junkcode/backtrace */
2192 pstring cmd = "/usr/bin/backtrace %d";
2194 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2195 pstring_sub(cmd, "%d", pidstr);
2199 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2200 fn = dlsym(h, "_Insure_trap_error");
2203 ret = fn(a1, a2, a3, a4, a5, a6);