2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001
6 Copyright (C) Simo Sorce 2001
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
26 #ifdef WITH_NISPLUS_HOME
27 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
29 * The following lines are needed due to buggy include files
30 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
31 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
32 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
33 * an enum in /usr/include/rpcsvc/nis.h.
40 #if defined(GROUP_OBJ)
44 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
46 #include <rpcsvc/nis.h>
48 #else /* !WITH_NISPLUS_HOME */
50 #include "rpcsvc/ypclnt.h"
52 #endif /* WITH_NISPLUS_HOME */
53 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
55 int Protocol = PROTOCOL_COREPLUS;
57 /* a default finfo structure to ensure all fields are sensible */
58 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
60 /* this is used by the chaining code */
66 case handling on filenames
68 int case_default = CASE_LOWER;
70 /* the following control case operations - they are put here so the
71 client can link easily */
74 BOOL use_mangled_map = False;
75 BOOL short_case_preserve;
78 static enum remote_arch_types ra_type = RA_UNKNOWN;
79 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
81 pstring global_myname = "";
82 fstring global_myworkgroup = "";
83 char **my_netbios_names;
86 /****************************************************************************
87 Find a suitable temporary directory. The result should be copied immediately
88 as it may be overwritten by a subsequent call.
89 ****************************************************************************/
94 if ((p = getenv("TMPDIR")))
99 /****************************************************************************
100 Determine whether we are in the specified group.
101 ****************************************************************************/
103 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
107 if (group == current_gid)
110 for (i=0;i<ngroups;i++)
111 if (group == groups[i])
117 /****************************************************************************
118 Like atoi but gets the value up to the separator character.
119 ****************************************************************************/
121 static char *Atoic(char *p, int *n, char *c)
123 if (!isdigit((int)*p)) {
124 DEBUG(5, ("Atoic: malformed number\n"));
130 while ((*p) && isdigit((int)*p))
133 if (strchr_m(c, *p) == NULL)
135 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
142 /*************************************************************************
143 Reads a list of numbers.
144 *************************************************************************/
146 char *get_numlist(char *p, uint32 **num, int *count)
150 if (num == NULL || count == NULL)
156 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
159 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
166 (*num)[(*count)] = val;
174 /*******************************************************************
175 Check if a file exists - call vfs_file_exist for samba files.
176 ********************************************************************/
178 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
184 if (sys_stat(fname,sbuf) != 0)
187 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
190 /*******************************************************************
191 Check a files mod time.
192 ********************************************************************/
194 time_t file_modtime(const char *fname)
198 if (sys_stat(fname,&st) != 0)
204 /*******************************************************************
205 Check if a directory exists.
206 ********************************************************************/
208 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
215 if (sys_stat(dname,st) != 0)
218 ret = S_ISDIR(st->st_mode);
224 /*******************************************************************
225 returns the size in bytes of the named file
226 ********************************************************************/
227 SMB_OFF_T get_file_size(char *file_name)
231 if(sys_stat(file_name,&buf) != 0)
232 return (SMB_OFF_T)-1;
236 /*******************************************************************
237 return a string representing an attribute for a file
238 ********************************************************************/
239 char *attrib_string(uint16 mode)
241 static fstring attrstr;
245 if (mode & aVOLID) fstrcat(attrstr,"V");
246 if (mode & aDIR) fstrcat(attrstr,"D");
247 if (mode & aARCH) fstrcat(attrstr,"A");
248 if (mode & aHIDDEN) fstrcat(attrstr,"H");
249 if (mode & aSYSTEM) fstrcat(attrstr,"S");
250 if (mode & aRONLY) fstrcat(attrstr,"R");
255 /*******************************************************************
256 show a smb message structure
257 ********************************************************************/
258 void show_msg(char *buf)
263 if (DEBUGLEVEL < 5) return;
265 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
267 (int)CVAL(buf,smb_com),
268 (int)CVAL(buf,smb_rcls),
269 (int)CVAL(buf,smb_reh),
270 (int)SVAL(buf,smb_err),
271 (int)CVAL(buf,smb_flg),
272 (int)SVAL(buf,smb_flg2)));
273 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
274 (int)SVAL(buf,smb_tid),
275 (int)SVAL(buf,smb_pid),
276 (int)SVAL(buf,smb_uid),
277 (int)SVAL(buf,smb_mid),
278 (int)CVAL(buf,smb_wct)));
280 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
282 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
283 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
286 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
288 DEBUG(5,("smb_bcc=%d\n",bcc));
290 if (DEBUGLEVEL < 10) return;
297 dump_data(10, smb_buf(buf), bcc);
300 /*******************************************************************
301 set the length and marker of an smb packet
302 ********************************************************************/
303 void smb_setlen(char *buf,int len)
305 _smb_setlen(buf,len);
313 /*******************************************************************
314 setup the word count and byte count for a smb message
315 ********************************************************************/
316 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
319 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
320 SCVAL(buf,smb_wct,num_words);
321 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
322 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
323 return (smb_size + num_words*2 + num_bytes);
326 /*******************************************************************
327 setup only the byte count for a smb message
328 ********************************************************************/
329 int set_message_bcc(char *buf,int num_bytes)
331 int num_words = CVAL(buf,smb_wct);
332 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
333 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
334 return (smb_size + num_words*2 + num_bytes);
337 /*******************************************************************
338 setup only the byte count for a smb message, using the end of the
340 ********************************************************************/
341 int set_message_end(void *outbuf,void *end_ptr)
343 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
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_m(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_m(s,'/')) != NULL)
410 trim_string(s,NULL,"/..");
413 /*******************************************************************
415 reduce a file name, removing or reducing /../ , /./ , // elements.
416 remove also any trailing . and /
417 return a new allocated string.
418 ********************************************************************/
419 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
422 smb_ucs2_t *p, *r, *t;
424 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
427 /* convert '\' to '/' */
429 if (!ns) return NULL;
432 /* remove all double slashes */
434 ns = all_string_sub_wa(p, "//", "/");
436 if (!ns) return NULL;
440 ns = all_string_sub_wa(p, "/./", "/");
442 if (!ns) return NULL;
444 /* reduce any /../ */
446 while (*t && (r = strstr_wa(t, "/.."))) {
448 if (*t == UCS2_CHAR('/') || *t == 0) {
450 p = strrchr_w(ns, UCS2_CHAR('/'));
453 else memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
458 /* remove any leading ./ trailing /. */
459 trim_string_wa(ns, "./", "/.");
461 /* remove any leading and trailing / */
462 trim_string_wa(ns, "/", "/");
467 /****************************************************************************
469 ****************************************************************************/
470 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
477 if ((mode & aDIR) != 0)
480 memset(buf+1,' ',11);
481 if ((p = strchr_m(mask2,'.')) != NULL)
484 push_ascii(buf+1,mask2,8, 0);
485 push_ascii(buf+9,p+1,3, 0);
489 push_ascii(buf+1,mask2,11, 0);
491 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
493 put_dos_date(buf,22,date);
494 SSVAL(buf,26,size & 0xFFFF);
495 SSVAL(buf,28,(size >> 16)&0xFFFF);
496 push_ascii(buf+30,fname,12, 0);
499 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
503 /*******************************************************************
504 close the low 3 fd's and open dev/null in their place
505 ********************************************************************/
506 void close_low_fds(void)
514 /* try and use up these file descriptors, so silly
515 library routines writing to stdout etc won't cause havoc */
517 fd = sys_open("/dev/null",O_RDWR,0);
518 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
520 DEBUG(0,("Can't open /dev/null\n"));
524 DEBUG(0,("Didn't get file descriptor %d\n",i));
530 /****************************************************************************
531 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
535 ****************************************************************************/
536 int set_blocking(int fd, BOOL set)
540 #define FLAG_TO_SET O_NONBLOCK
543 #define FLAG_TO_SET O_NDELAY
545 #define FLAG_TO_SET FNDELAY
549 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
551 if(set) /* Turn blocking on - ie. clear nonblock flag */
555 return sys_fcntl_long( fd, F_SETFL, val);
559 /****************************************************************************
560 Transfer some data between two fd's.
561 ****************************************************************************/
563 #ifndef TRANSFER_BUF_SIZE
564 #define TRANSFER_BUF_SIZE 65536
567 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
568 ssize_t (*write_fn)(int, const void *, size_t))
574 size_t num_to_read_thistime;
575 size_t num_written = 0;
577 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
581 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
583 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
584 if (read_ret == -1) {
585 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
594 while (num_written < read_ret) {
595 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
597 if (write_ret == -1) {
598 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
603 return (ssize_t)total;
605 num_written += (size_t)write_ret;
608 total += (size_t)read_ret;
612 return (ssize_t)total;
615 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
617 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
620 /*******************************************************************
621 Sleep for a specified number of milliseconds.
622 ********************************************************************/
624 void msleep(unsigned int t)
626 unsigned int tdiff=0;
627 struct timeval tval,t1,t2;
634 tval.tv_sec = (t-tdiff)/1000;
635 tval.tv_usec = 1000*((t-tdiff)%1000);
637 /* Never wait for more than 1 sec. */
638 if (tval.tv_sec > 1) {
645 sys_select_intr(0,&fds,NULL,NULL,&tval);
648 if (t2.tv_sec < t1.tv_sec) {
649 /* Someone adjusted time... */
653 tdiff = TvalDiff(&t1,&t2);
657 /****************************************************************************
658 Become a daemon, discarding the controlling terminal.
659 ****************************************************************************/
661 void become_daemon(void)
667 /* detach from the terminal */
670 #elif defined(TIOCNOTTY)
672 int i = sys_open("/dev/tty", O_RDWR, 0);
674 ioctl(i, (int) TIOCNOTTY, (char *)0);
678 #endif /* HAVE_SETSID */
680 /* Close fd's 0,1,2. Needed if started by rsh */
685 /****************************************************************************
686 Put up a yes/no prompt
687 ****************************************************************************/
693 if (!fgets(ans,sizeof(ans)-1,stdin))
696 if (*ans == 'y' || *ans == 'Y')
702 /****************************************************************************
703 Expand a pointer to be a particular size.
704 ****************************************************************************/
706 void *Realloc(void *p,size_t size)
712 DEBUG(5,("Realloc asked for 0 bytes\n"));
717 ret = (void *)malloc(size);
719 ret = (void *)realloc(p,size);
722 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
727 /****************************************************************************
728 Free memory, checks for NULL.
729 use directly SAFE_FREE()
730 exist only because we need to pass a function pointer somewhere --SSS
731 ****************************************************************************/
733 void safe_free(void *p)
738 /****************************************************************************
739 Get my own name and IP.
740 ****************************************************************************/
742 BOOL get_myname(char *my_name)
748 /* get my host name */
749 if (gethostname(hostname, sizeof(hostname)) == -1) {
750 DEBUG(0,("gethostname failed\n"));
754 /* Ensure null termination. */
755 hostname[sizeof(hostname)-1] = '\0';
758 /* split off any parts after an initial . */
759 char *p = strchr_m(hostname,'.');
764 fstrcpy(my_name,hostname);
770 /****************************************************************************
771 Interpret a protocol description string, with a default.
772 ****************************************************************************/
774 int interpret_protocol(char *str,int def)
776 if (strequal(str,"NT1"))
777 return(PROTOCOL_NT1);
778 if (strequal(str,"LANMAN2"))
779 return(PROTOCOL_LANMAN2);
780 if (strequal(str,"LANMAN1"))
781 return(PROTOCOL_LANMAN1);
782 if (strequal(str,"CORE"))
783 return(PROTOCOL_CORE);
784 if (strequal(str,"COREPLUS"))
785 return(PROTOCOL_COREPLUS);
786 if (strequal(str,"CORE+"))
787 return(PROTOCOL_COREPLUS);
789 DEBUG(0,("Unrecognised protocol level %s\n",str));
794 /****************************************************************************
795 Return true if a string could be a pure IP address.
796 ****************************************************************************/
798 BOOL is_ipaddress(const char *str)
800 BOOL pure_address = True;
803 for (i=0; pure_address && str[i]; i++)
804 if (!(isdigit((int)str[i]) || str[i] == '.'))
805 pure_address = False;
807 /* Check that a pure number is not misinterpreted as an IP */
808 pure_address = pure_address && (strchr_m(str, '.') != NULL);
813 /****************************************************************************
814 interpret an internet address or name into an IP address in 4 byte form
815 ****************************************************************************/
817 uint32 interpret_addr(const char *str)
822 if (strcmp(str,"0.0.0.0") == 0) return(0);
823 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
825 /* if it's in the form of an IP address then get the lib to interpret it */
826 if (is_ipaddress(str)) {
827 res = inet_addr(str);
829 /* otherwise assume it's a network name of some sort and use
831 if ((hp = sys_gethostbyname(str)) == 0) {
832 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
835 if(hp->h_addr == NULL) {
836 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
839 putip((char *)&res,(char *)hp->h_addr);
842 if (res == (uint32)-1) return(0);
847 /*******************************************************************
848 a convenient addition to interpret_addr()
849 ******************************************************************/
850 struct in_addr *interpret_addr2(const char *str)
852 static struct in_addr ret;
853 uint32 a = interpret_addr(str);
858 /*******************************************************************
859 Check if an IP is the 0.0.0.0
860 ******************************************************************/
861 BOOL is_zero_ip(struct in_addr ip)
864 putip((char *)&a,(char *)&ip);
868 /*******************************************************************
870 ******************************************************************/
872 void zero_ip(struct in_addr *ip)
875 static struct in_addr ipzero;
878 ipzero = *interpret_addr2("0.0.0.0");
885 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
886 /******************************************************************
887 Remove any mount options such as -rsize=2048,wsize=2048 etc.
888 Based on a fix from <Thomas.Hepper@icem.de>.
889 *******************************************************************/
891 static void strip_mount_options( pstring *str)
896 while(*p && !isspace(*p))
898 while(*p && isspace(*p))
904 pstrcpy(*str, tmp_str);
909 /*******************************************************************
910 Patch from jkf@soton.ac.uk
911 Split Luke's automount_server into YP lookup and string splitter
912 so can easily implement automount_path().
913 As we may end up doing both, cache the last YP result.
914 *******************************************************************/
916 #ifdef WITH_NISPLUS_HOME
917 char *automount_lookup(const char *user_name)
919 static fstring last_key = "";
920 static pstring last_value = "";
922 char *nis_map = (char *)lp_nis_home_map_name();
924 char buffer[NIS_MAXATTRVAL + 1];
929 if (strcmp(user_name, last_key))
931 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
932 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
934 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
936 if (result->status != NIS_SUCCESS)
938 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
939 fstrcpy(last_key, ""); pstrcpy(last_value, "");
943 object = result->objects.objects_val;
944 if (object->zo_data.zo_type == ENTRY_OBJ)
946 entry = &object->zo_data.objdata_u.en_data;
947 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
948 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
950 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
951 pstring_sub(last_value, "&", user_name);
952 fstrcpy(last_key, user_name);
956 nis_freeresult(result);
959 strip_mount_options(&last_value);
961 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
964 #else /* WITH_NISPLUS_HOME */
965 char *automount_lookup(const char *user_name)
967 static fstring last_key = "";
968 static pstring last_value = "";
970 int nis_error; /* returned by yp all functions */
971 char *nis_result; /* yp_match inits this */
972 int nis_result_len; /* and set this */
973 char *nis_domain; /* yp_get_default_domain inits this */
974 char *nis_map = (char *)lp_nis_home_map_name();
976 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
977 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
981 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
983 if (!strcmp(user_name, last_key)) {
984 nis_result = last_value;
985 nis_result_len = strlen(last_value);
990 if ((nis_error = yp_match(nis_domain, nis_map,
991 user_name, strlen(user_name),
992 &nis_result, &nis_result_len)) == 0) {
993 if (!nis_error && nis_result_len >= sizeof(pstring)) {
994 nis_result_len = sizeof(pstring)-1;
996 fstrcpy(last_key, user_name);
997 strncpy(last_value, nis_result, nis_result_len);
998 last_value[nis_result_len] = '\0';
999 strip_mount_options(&last_value);
1001 } else if(nis_error == YPERR_KEY) {
1003 /* If Key lookup fails user home server is not in nis_map
1004 use default information for server, and home directory */
1006 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1007 user_name, nis_map));
1008 DEBUG(3, ("using defaults for server and home directory\n"));
1010 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1011 yperr_string(nis_error), user_name, nis_map));
1016 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1019 #endif /* WITH_NISPLUS_HOME */
1023 /*******************************************************************
1024 are two IPs on the same subnet?
1025 ********************************************************************/
1026 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1028 uint32 net1,net2,nmask;
1030 nmask = ntohl(mask.s_addr);
1031 net1 = ntohl(ip1.s_addr);
1032 net2 = ntohl(ip2.s_addr);
1034 return((net1 & nmask) == (net2 & nmask));
1038 /****************************************************************************
1039 check if a process exists. Does this work on all unixes?
1040 ****************************************************************************/
1042 BOOL process_exists(pid_t pid)
1044 /* Doing kill with a non-positive pid causes messages to be
1045 * sent to places we don't want. */
1046 SMB_ASSERT(pid > 0);
1047 return(kill(pid,0) == 0 || errno != ESRCH);
1051 /*******************************************************************
1052 Convert a uid into a user name.
1053 ********************************************************************/
1055 const char *uidtoname(uid_t uid)
1057 static fstring name;
1058 struct passwd *pass;
1060 pass = getpwuid_alloc(uid);
1062 fstrcpy(name, pass->pw_name);
1065 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1071 /*******************************************************************
1072 Convert a gid into a group name.
1073 ********************************************************************/
1075 char *gidtoname(gid_t gid)
1077 static fstring name;
1080 grp = getgrgid(gid);
1082 return(grp->gr_name);
1083 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1087 /*******************************************************************
1088 Convert a user name into a uid.
1089 ********************************************************************/
1091 uid_t nametouid(char *name)
1093 struct passwd *pass;
1097 pass = getpwnam_alloc(name);
1104 u = (uid_t)strtol(name, &p, 0);
1105 if ((p != name) && (*p == '\0'))
1111 /*******************************************************************
1112 Convert a name to a gid_t if possible. Return -1 if not a group.
1113 ********************************************************************/
1115 gid_t nametogid(const char *name)
1121 g = (gid_t)strtol(name, &p, 0);
1122 if ((p != name) && (*p == '\0'))
1125 grp = sys_getgrnam(name);
1127 return(grp->gr_gid);
1131 /*******************************************************************
1132 something really nasty happened - panic!
1133 ********************************************************************/
1134 void smb_panic(char *why)
1136 char *cmd = lp_panic_action();
1140 DEBUG(0,("PANIC: %s\n", why));
1146 /*******************************************************************
1147 a readdir wrapper which just returns the file name
1148 ********************************************************************/
1149 char *readdirname(DIR *p)
1151 SMB_STRUCT_DIRENT *ptr;
1154 if (!p) return(NULL);
1156 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1157 if (!ptr) return(NULL);
1159 dname = ptr->d_name;
1162 if (telldir(p) < 0) return(NULL);
1165 #ifdef HAVE_BROKEN_READDIR
1166 /* using /usr/ucb/cc is BAD */
1172 int len = NAMLEN(ptr);
1173 memcpy(buf, dname, len);
1181 /*******************************************************************
1182 Utility function used to decide if the last component
1183 of a path matches a (possibly wildcarded) entry in a namelist.
1184 ********************************************************************/
1186 BOOL is_in_path(char *name, name_compare_entry *namelist)
1188 pstring last_component;
1191 DEBUG(8, ("is_in_path: %s\n", name));
1193 /* if we have no list it's obviously not in the path */
1194 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1196 DEBUG(8,("is_in_path: no name list.\n"));
1200 /* Get the last component of the unix name. */
1201 p = strrchr_m(name, '/');
1202 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1203 last_component[sizeof(last_component)-1] = '\0';
1205 for(; namelist->name != NULL; namelist++)
1207 if(namelist->is_wild)
1209 if (mask_match(last_component, namelist->name, case_sensitive))
1211 DEBUG(8,("is_in_path: mask match succeeded\n"));
1217 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1218 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1220 DEBUG(8,("is_in_path: match succeeded\n"));
1225 DEBUG(8,("is_in_path: match not found\n"));
1230 /*******************************************************************
1231 Strip a '/' separated list into an array of
1232 name_compare_enties structures suitable for
1233 passing to is_in_path(). We do this for
1234 speed so we can pre-parse all the names in the list
1235 and don't do it for each call to is_in_path().
1236 namelist is modified here and is assumed to be
1237 a copy owned by the caller.
1238 We also check if the entry contains a wildcard to
1239 remove a potentially expensive call to mask_match
1241 ********************************************************************/
1243 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1246 char *nameptr = namelist;
1247 int num_entries = 0;
1250 (*ppname_array) = NULL;
1252 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1255 /* We need to make two passes over the string. The
1256 first to count the number of elements, the second
1261 if ( *nameptr == '/' )
1263 /* cope with multiple (useless) /s) */
1267 /* find the next / */
1268 name_end = strchr_m(nameptr, '/');
1270 /* oops - the last check for a / didn't find one. */
1271 if (name_end == NULL)
1274 /* next segment please */
1275 nameptr = name_end + 1;
1279 if(num_entries == 0)
1282 if(( (*ppname_array) = (name_compare_entry *)malloc(
1283 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1285 DEBUG(0,("set_namearray: malloc fail\n"));
1289 /* Now copy out the names */
1294 if ( *nameptr == '/' )
1296 /* cope with multiple (useless) /s) */
1300 /* find the next / */
1301 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1306 /* oops - the last check for a / didn't find one. */
1307 if(name_end == NULL)
1310 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1311 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1313 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1317 /* next segment please */
1318 nameptr = name_end + 1;
1322 (*ppname_array)[i].name = NULL;
1327 /****************************************************************************
1328 routine to free a namearray.
1329 ****************************************************************************/
1331 void free_namearray(name_compare_entry *name_array)
1333 if(name_array == NULL)
1336 SAFE_FREE(name_array->name);
1337 SAFE_FREE(name_array);
1340 /****************************************************************************
1341 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1342 is dealt with in posix.c
1343 ****************************************************************************/
1345 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1347 SMB_STRUCT_FLOCK lock;
1350 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1353 lock.l_whence = SEEK_SET;
1354 lock.l_start = offset;
1358 ret = sys_fcntl_ptr(fd,op,&lock);
1360 if (ret == -1 && errno != 0)
1361 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1364 if (op == SMB_F_GETLK)
1367 (lock.l_type != F_UNLCK) &&
1368 (lock.l_pid != 0) &&
1369 (lock.l_pid != sys_getpid()))
1371 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1375 /* it must be not locked or locked by me */
1379 /* a lock set or unset */
1382 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1383 (double)offset,(double)count,op,type,strerror(errno)));
1387 /* everything went OK */
1388 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1393 /*******************************************************************
1394 Is the name specified one of my netbios names.
1395 Returns true if it is equal, false otherwise.
1396 ********************************************************************/
1398 BOOL is_myname(char *s)
1403 for (n=0; my_netbios_names[n]; n++) {
1404 if (strequal(my_netbios_names[n], s))
1407 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1411 /********************************************************************
1412 Return only the first IP address of our configured interfaces
1414 *******************************************************************/
1416 const char* get_my_primary_ip (void)
1418 static fstring ip_string;
1420 struct iface_struct nics[MAX_INTERFACES];
1422 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1425 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1429 BOOL is_myname_or_ipaddr(char *s)
1433 /* optimize for the common case */
1434 if (strequal(s, global_myname))
1437 /* maybe its an IP address? */
1438 if (is_ipaddress(s)) {
1439 struct iface_struct nics[MAX_INTERFACES];
1443 ip = interpret_addr(s);
1444 if ((ip==0) || (ip==0xffffffff))
1447 n = get_interfaces(nics, MAX_INTERFACES);
1448 for (i=0; i<n; i++) {
1449 if (ip == nics[i].ip.s_addr)
1454 /* check for an alias */
1455 ptr = lp_netbios_aliases();
1456 for ( ; *ptr; ptr++ ) {
1457 if (StrCaseCmp(s, *ptr) == 0)
1465 /*******************************************************************
1466 Set the horrid remote_arch string based on an enum.
1467 ********************************************************************/
1469 void set_remote_arch(enum remote_arch_types type)
1471 extern fstring remote_arch;
1475 fstrcpy(remote_arch, "WfWg");
1478 fstrcpy(remote_arch, "OS2");
1481 fstrcpy(remote_arch, "Win95");
1484 fstrcpy(remote_arch, "WinNT");
1487 fstrcpy(remote_arch, "Win2K");
1490 fstrcpy(remote_arch,"Samba");
1493 ra_type = RA_UNKNOWN;
1494 fstrcpy(remote_arch, "UNKNOWN");
1499 /*******************************************************************
1500 Get the remote_arch type.
1501 ********************************************************************/
1503 enum remote_arch_types get_remote_arch(void)
1509 void out_ascii(FILE *f, unsigned char *buf,int len)
1513 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1516 void out_data(FILE *f,char *buf1,int len, int per_line)
1518 unsigned char *buf = (unsigned char *)buf1;
1524 fprintf(f, "[%03X] ",i);
1526 fprintf(f, "%02X ",(int)buf[i]);
1528 if (i%(per_line/2) == 0) fprintf(f, " ");
1529 if (i%per_line == 0) {
1530 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1531 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1532 if (i<len) fprintf(f, "[%03X] ",i);
1535 if ((i%per_line) != 0) {
1538 n = per_line - (i%per_line);
1540 if (n>(per_line/2)) fprintf(f, " ");
1544 n = MIN(per_line/2,i%per_line);
1545 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1546 n = (i%per_line) - n;
1547 if (n>0) out_ascii(f,&buf[i-n],n);
1552 void print_asc(int level, const unsigned char *buf,int len)
1556 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1559 void dump_data(int level, const char *buf1,int len)
1561 const unsigned char *buf = (const unsigned char *)buf1;
1565 DEBUG(level,("[%03X] ",i));
1567 DEBUG(level,("%02X ",(int)buf[i]));
1569 if (i%8 == 0) DEBUG(level,(" "));
1571 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1572 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1573 if (i<len) DEBUG(level,("[%03X] ",i));
1581 if (n>8) DEBUG(level,(" "));
1582 while (n--) DEBUG(level,(" "));
1585 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1587 if (n>0) print_asc(level,&buf[i-n],n);
1588 DEBUG(level,("\n"));
1592 char *tab_depth(int depth)
1594 static pstring spaces;
1595 memset(spaces, ' ', depth * 4);
1596 spaces[depth * 4] = 0;
1600 /*****************************************************************************
1601 * Provide a checksum on a string
1603 * Input: s - the null-terminated character string for which the checksum
1604 * will be calculated.
1606 * Output: The checksum value calculated for s.
1608 * ****************************************************************************
1610 int str_checksum(const char *s)
1618 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1623 } /* str_checksum */
1627 /*****************************************************************
1628 zero a memory area then free it. Used to catch bugs faster
1629 *****************************************************************/
1630 void zero_free(void *p, size_t size)
1637 /*****************************************************************
1638 set our open file limit to a requested max and return the limit
1639 *****************************************************************/
1640 int set_maxfiles(int requested_max)
1642 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1644 int saved_current_limit;
1646 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1647 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1650 return requested_max;
1654 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1655 * account for the extra fd we need
1656 * as well as the log files and standard
1657 * handles etc. Save the limit we want to set in case
1658 * we are running on an OS that doesn't support this limit (AIX)
1659 * which always returns RLIM_INFINITY for rlp.rlim_max.
1662 /* Try raising the hard (max) limit to the requested amount. */
1664 #if defined(RLIM_INFINITY)
1665 if (rlp.rlim_max != RLIM_INFINITY) {
1666 int orig_max = rlp.rlim_max;
1668 if ( rlp.rlim_max < requested_max )
1669 rlp.rlim_max = requested_max;
1671 /* This failing is not an error - many systems (Linux) don't
1672 support our default request of 10,000 open files. JRA. */
1674 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1675 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1676 (int)rlp.rlim_max, strerror(errno) ));
1678 /* Set failed - restore original value from get. */
1679 rlp.rlim_max = orig_max;
1684 /* Now try setting the soft (current) limit. */
1686 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1688 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1689 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1690 (int)rlp.rlim_cur, strerror(errno) ));
1692 return saved_current_limit;
1695 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1696 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1699 return saved_current_limit;
1702 #if defined(RLIM_INFINITY)
1703 if(rlp.rlim_cur == RLIM_INFINITY)
1704 return saved_current_limit;
1707 if((int)rlp.rlim_cur > saved_current_limit)
1708 return saved_current_limit;
1710 return rlp.rlim_cur;
1711 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1713 * No way to know - just guess...
1715 return requested_max;
1719 /*****************************************************************
1720 splits out the start of the key (HKLM or HKU) and the rest of the key
1721 *****************************************************************/
1722 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1726 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1733 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1735 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1737 (*reg_type) = HKEY_LOCAL_MACHINE;
1739 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1741 (*reg_type) = HKEY_USERS;
1745 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1749 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
1751 fstrcpy(key_name, tmp);
1758 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1764 /*****************************************************************
1765 possibly replace mkstemp if it is broken
1766 *****************************************************************/
1767 int smb_mkstemp(char *template)
1769 #if HAVE_SECURE_MKSTEMP
1770 return mkstemp(template);
1772 /* have a reasonable go at emulating it. Hope that
1773 the system mktemp() isn't completly hopeless */
1774 char *p = mktemp(template);
1776 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1780 /*****************************************************************
1781 malloc that aborts with smb_panic on fail or zero size.
1782 *****************************************************************/
1784 void *smb_xmalloc(size_t size)
1788 smb_panic("smb_xmalloc: called with zero size.\n");
1789 if ((p = malloc(size)) == NULL)
1790 smb_panic("smb_xmalloc: malloc fail.\n");
1795 Memdup with smb_panic on fail.
1797 void *smb_xmemdup(const void *p, size_t size)
1800 p2 = smb_xmalloc(size);
1801 memcpy(p2, p, size);
1806 strdup that aborts on malloc fail.
1808 char *smb_xstrdup(const char *s)
1810 char *s1 = strdup(s);
1812 smb_panic("smb_xstrdup: malloc fail\n");
1817 vasprintf that aborts on malloc fail
1819 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1826 n = vasprintf(ptr, format, ap2);
1827 if (n == -1 || ! *ptr) {
1828 smb_panic("smb_xvasprintf: out of memory");
1833 /*****************************************************************
1834 like strdup but for memory
1835 *****************************************************************/
1836 void *memdup(const void *p, size_t size)
1839 if (size == 0) return NULL;
1841 if (!p2) return NULL;
1842 memcpy(p2, p, size);
1846 /*****************************************************************
1847 get local hostname and cache result
1848 *****************************************************************/
1849 char *myhostname(void)
1859 /*****************************************************************
1860 a useful function for returning a path in the Samba lock directory
1861 *****************************************************************/
1862 char *lock_path(const char *name)
1864 static pstring fname;
1866 pstrcpy(fname,lp_lockdir());
1867 trim_string(fname,"","/");
1869 if (!directory_exist(fname,NULL)) {
1874 pstrcat(fname,name);
1879 /*****************************************************************
1880 a useful function for returning a path in the Samba pid directory
1881 *****************************************************************/
1882 char *pid_path(const char *name)
1884 static pstring fname;
1886 pstrcpy(fname,lp_piddir());
1887 trim_string(fname,"","/");
1889 if (!directory_exist(fname,NULL)) {
1894 pstrcat(fname,name);
1901 * @brief Returns an absolute path to a file in the Samba lib directory.
1903 * @param name File to find, relative to LIBDIR.
1905 * @retval Pointer to a static #pstring containing the full path.
1907 char *lib_path(const char *name)
1909 static pstring fname;
1910 snprintf(fname, sizeof(fname), "%s/%s", dyn_LIBDIR, name);
1914 /*******************************************************************
1915 Given a filename - get its directory name
1916 NB: Returned in static storage. Caveats:
1917 o Not safe in thread environment.
1918 o Caller must not free.
1919 o If caller wishes to preserve, they should copy.
1920 ********************************************************************/
1922 char *parent_dirname(const char *path)
1924 static pstring dirpath;
1930 pstrcpy(dirpath, path);
1931 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
1933 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1936 ++p; /* For root "/", leave "/" in place */
1943 /*******************************************************************
1944 determine if a pattern contains any Microsoft wildcard characters
1945 *******************************************************************/
1946 BOOL ms_has_wild(char *s)
1949 while ((c = *s++)) {
1962 BOOL ms_has_wild_w(const smb_ucs2_t *s)
1965 if (!s) return False;
1966 while ((c = *s++)) {
1968 case UCS2_CHAR('*'):
1969 case UCS2_CHAR('?'):
1970 case UCS2_CHAR('<'):
1971 case UCS2_CHAR('>'):
1972 case UCS2_CHAR('"'):
1979 /*******************************************************************
1980 a wrapper that handles case sensitivity and the special handling
1982 *******************************************************************/
1983 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1987 if (strcmp(string,"..") == 0) string = ".";
1988 if (strcmp(pattern,".") == 0) return False;
1990 if (is_case_sensitive) {
1991 return ms_fnmatch(pattern, string, Protocol) == 0;
1994 fstrcpy(p2, pattern);
1995 fstrcpy(s2, string);
1998 return ms_fnmatch(p2, s2, Protocol) == 0;
2001 /*********************************************************
2002 Recursive routine that is called by unix_wild_match.
2003 *********************************************************/
2005 static BOOL unix_do_match(char *regexp, char *str)
2009 for( p = regexp; *p && *str; ) {
2020 * Look for a character matching
2021 * the one after the '*'.
2025 return True; /* Automatic match */
2028 while(*str && (*p != *str))
2032 * Patch from weidel@multichart.de. In the case of the regexp
2033 * '*XX*' we want to ensure there are at least 2 'X' characters
2034 * in the string after the '*' for a match to be made.
2041 * Eat all the characters that match, but count how many there were.
2044 while(*str && (*p == *str)) {
2050 * Now check that if the regexp had n identical characters that
2051 * matchcount had at least that many matches.
2054 while ( *(p+1) && (*(p+1) == *p)) {
2059 if ( matchcount <= 0 )
2063 str--; /* We've eaten the match char after the '*' */
2065 if(unix_do_match(p, str))
2087 if (!*p && str[0] == '.' && str[1] == 0)
2090 if (!*str && *p == '?') {
2096 if(!*str && (*p == '*' && p[1] == '\0'))
2102 /*******************************************************************
2103 Simple case insensitive interface to a UNIX wildcard matcher.
2104 *******************************************************************/
2106 BOOL unix_wild_match(char *pattern, char *string)
2111 pstrcpy(p2, pattern);
2112 pstrcpy(s2, string);
2116 /* Remove any *? and ** from the pattern as they are meaningless */
2117 for(p = p2; *p; p++)
2118 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2119 pstrcpy( &p[1], &p[2]);
2121 if (strequal(p2,"*"))
2124 return unix_do_match(p2, s2) == 0;
2129 /*******************************************************************
2130 This routine is a trick to immediately catch errors when debugging
2131 with insure. A xterm with a gdb is popped up when insure catches
2132 a error. It is Linux specific.
2133 ********************************************************************/
2134 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2139 /* you can get /usr/bin/backtrace from
2140 http://samba.org/ftp/unpacked/junkcode/backtrace */
2141 pstring cmd = "/usr/bin/backtrace %d";
2143 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2144 pstring_sub(cmd, "%d", pidstr);
2148 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2149 fn = dlsym(h, "_Insure_trap_error");
2151 if (!h || h == _Insure_trap_error) {
2152 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2153 fn = dlsym(h, "_Insure_trap_error");
2157 ret = fn(a1, a2, a3, a4, a5, a6);