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 */
55 #include <openssl/ssl.h>
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 ****************************************************************************/
102 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
)
118 for (i
=0;i
<ngroups
;i
++)
119 if (group
== groups
[i
])
125 /****************************************************************************
126 Like atoi but gets the value up to the separater character.
127 ****************************************************************************/
129 char *Atoic(char *p
, int *n
, char *c
)
131 if (!isdigit((int)*p
)) {
132 DEBUG(5, ("Atoic: malformed number\n"));
138 while ((*p
) && isdigit((int)*p
))
141 if (strchr(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(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(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 CVAL(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 void 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);
343 /*******************************************************************
344 setup only the byte count for a smb message, using the end of the
346 ********************************************************************/
347 void set_message_end(void *outbuf
,void *end_ptr
)
349 set_message_bcc((char *)outbuf
,PTR_DIFF(end_ptr
,smb_buf((char *)outbuf
)));
352 /*******************************************************************
353 reduce a file name, removing .. elements.
354 ********************************************************************/
355 void dos_clean_name(char *s
)
359 DEBUG(3,("dos_clean_name [%s]\n",s
));
361 /* remove any double slashes */
362 all_string_sub(s
, "\\\\", "\\", 0);
364 while ((p
= strstr(s
,"\\..\\")) != NULL
)
371 if ((p
=strrchr(s
,'\\')) != NULL
)
378 trim_string(s
,NULL
,"\\..");
380 all_string_sub(s
, "\\.\\", "\\", 0);
383 /*******************************************************************
384 reduce a file name, removing .. elements.
385 ********************************************************************/
386 void unix_clean_name(char *s
)
390 DEBUG(3,("unix_clean_name [%s]\n",s
));
392 /* remove any double slashes */
393 all_string_sub(s
, "//","/", 0);
395 /* Remove leading ./ characters */
396 if(strncmp(s
, "./", 2) == 0) {
397 trim_string(s
, "./", NULL
);
402 while ((p
= strstr(s
,"/../")) != NULL
)
409 if ((p
=strrchr(s
,'/')) != NULL
)
416 trim_string(s
,NULL
,"/..");
419 /****************************************************************************
421 ****************************************************************************/
422 void make_dir_struct(char *buf
,char *mask
,char *fname
,SMB_OFF_T size
,int mode
,time_t date
)
429 if ((mode
& aDIR
) != 0)
432 memset(buf
+1,' ',11);
433 if ((p
= strchr(mask2
,'.')) != NULL
)
436 memcpy(buf
+1,mask2
,MIN(strlen(mask2
),8));
437 memcpy(buf
+9,p
+1,MIN(strlen(p
+1),3));
441 memcpy(buf
+1,mask2
,MIN(strlen(mask2
),11));
443 memset(buf
+21,'\0',DIR_STRUCT_SIZE
-21);
445 put_dos_date(buf
,22,date
);
446 SSVAL(buf
,26,size
& 0xFFFF);
447 SSVAL(buf
,28,(size
>> 16)&0xFFFF);
448 StrnCpy(buf
+30,fname
,12);
451 DEBUG(8,("put name [%s] into dir struct\n",buf
+30));
455 /*******************************************************************
456 close the low 3 fd's and open dev/null in their place
457 ********************************************************************/
458 void close_low_fds(void)
466 /* try and use up these file descriptors, so silly
467 library routines writing to stdout etc won't cause havoc */
469 fd
= sys_open("/dev/null",O_RDWR
,0);
470 if (fd
< 0) fd
= sys_open("/dev/null",O_WRONLY
,0);
472 DEBUG(0,("Can't open /dev/null\n"));
476 DEBUG(0,("Didn't get file descriptor %d\n",i
));
482 /****************************************************************************
483 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
487 ****************************************************************************/
488 int set_blocking(int fd
, BOOL set
)
492 #define FLAG_TO_SET O_NONBLOCK
495 #define FLAG_TO_SET O_NDELAY
497 #define FLAG_TO_SET FNDELAY
501 if((val
= fcntl(fd
, F_GETFL
, 0)) == -1)
503 if(set
) /* Turn blocking on - ie. clear nonblock flag */
507 return fcntl( fd
, F_SETFL
, val
);
511 /****************************************************************************
512 Transfer some data between two fd's.
513 ****************************************************************************/
515 ssize_t
transfer_file_internal(int infd
, int outfd
, size_t n
, ssize_t (*read_fn
)(int, void *, size_t),
516 ssize_t (*write_fn
)(int, const void *, size_t))
518 static char buf
[16384];
521 size_t write_total
= 0;
525 size_t num_to_read_thistime
= MIN((n
- total
), sizeof(buf
));
527 read_ret
= (*read_fn
)(infd
, buf
+ total
, num_to_read_thistime
);
528 if (read_ret
== -1) {
529 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno
) ));
537 while (write_total
< read_ret
) {
538 write_ret
= (*write_fn
)(outfd
,buf
+ total
, read_ret
);
540 if (write_ret
== -1) {
541 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno
) ));
545 return (ssize_t
)total
;
547 write_total
+= (size_t)write_ret
;
550 total
+= (size_t)read_ret
;
553 return (ssize_t
)total
;
556 SMB_OFF_T
transfer_file(int infd
,int outfd
,SMB_OFF_T n
)
558 return (SMB_OFF_T
)transfer_file_internal(infd
, outfd
, (size_t)n
, read
, write
);
561 /*******************************************************************
562 Sleep for a specified number of milliseconds.
563 ********************************************************************/
568 struct timeval tval
,t1
,t2
;
575 tval
.tv_sec
= (t
-tdiff
)/1000;
576 tval
.tv_usec
= 1000*((t
-tdiff
)%1000);
580 sys_select_intr(0,&fds
,&tval
);
583 tdiff
= TvalDiff(&t1
,&t2
);
587 /****************************************************************************
588 Become a daemon, discarding the controlling terminal.
589 ****************************************************************************/
591 void become_daemon(void)
597 /* detach from the terminal */
600 #elif defined(TIOCNOTTY)
602 int i
= sys_open("/dev/tty", O_RDWR
, 0);
604 ioctl(i
, (int) TIOCNOTTY
, (char *)0);
608 #endif /* HAVE_SETSID */
610 /* Close fd's 0,1,2. Needed if started by rsh */
614 /****************************************************************************
615 Put up a yes/no prompt
616 ****************************************************************************/
623 if (!fgets(ans
,sizeof(ans
)-1,stdin
))
626 if (*ans
== 'y' || *ans
== 'Y')
632 /****************************************************************************
633 Expand a pointer to be a particular size.
634 ****************************************************************************/
636 void *Realloc(void *p
,size_t size
)
643 DEBUG(5,("Realloc asked for 0 bytes\n"));
648 ret
= (void *)malloc(size
);
650 ret
= (void *)realloc(p
,size
);
653 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size
));
658 /****************************************************************************
659 Free memory, checks for NULL.
660 ****************************************************************************/
662 void safe_free(void *p
)
668 /****************************************************************************
669 Get my own name and IP.
670 ****************************************************************************/
672 BOOL
get_myname(char *my_name
)
678 /* get my host name */
679 if (gethostname(hostname
, sizeof(hostname
)) == -1) {
680 DEBUG(0,("gethostname failed\n"));
684 /* Ensure null termination. */
685 hostname
[sizeof(hostname
)-1] = '\0';
688 /* split off any parts after an initial . */
689 char *p
= strchr(hostname
,'.');
693 fstrcpy(my_name
,hostname
);
699 /****************************************************************************
700 Interpret a protocol description string, with a default.
701 ****************************************************************************/
703 int interpret_protocol(char *str
,int def
)
705 if (strequal(str
,"NT1"))
706 return(PROTOCOL_NT1
);
707 if (strequal(str
,"LANMAN2"))
708 return(PROTOCOL_LANMAN2
);
709 if (strequal(str
,"LANMAN1"))
710 return(PROTOCOL_LANMAN1
);
711 if (strequal(str
,"CORE"))
712 return(PROTOCOL_CORE
);
713 if (strequal(str
,"COREPLUS"))
714 return(PROTOCOL_COREPLUS
);
715 if (strequal(str
,"CORE+"))
716 return(PROTOCOL_COREPLUS
);
718 DEBUG(0,("Unrecognised protocol level %s\n",str
));
723 /****************************************************************************
724 Return true if a string could be a pure IP address.
725 ****************************************************************************/
727 BOOL
is_ipaddress(const char *str
)
729 BOOL pure_address
= True
;
732 for (i
=0; pure_address
&& str
[i
]; i
++)
733 if (!(isdigit((int)str
[i
]) || str
[i
] == '.'))
734 pure_address
= False
;
736 /* Check that a pure number is not misinterpreted as an IP */
737 pure_address
= pure_address
&& (strchr(str
, '.') != NULL
);
742 /****************************************************************************
743 interpret an internet address or name into an IP address in 4 byte form
744 ****************************************************************************/
746 uint32
interpret_addr(char *str
)
751 if (strcmp(str
,"0.0.0.0") == 0) return(0);
752 if (strcmp(str
,"255.255.255.255") == 0) return(0xFFFFFFFF);
754 /* if it's in the form of an IP address then get the lib to interpret it */
755 if (is_ipaddress(str
)) {
756 res
= inet_addr(str
);
758 /* otherwise assume it's a network name of some sort and use
760 if ((hp
= sys_gethostbyname(str
)) == 0) {
761 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str
));
764 if(hp
->h_addr
== NULL
) {
765 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str
));
768 putip((char *)&res
,(char *)hp
->h_addr
);
771 if (res
== (uint32
)-1) return(0);
776 /*******************************************************************
777 a convenient addition to interpret_addr()
778 ******************************************************************/
779 struct in_addr
*interpret_addr2(char *str
)
781 static struct in_addr ret
;
782 uint32 a
= interpret_addr(str
);
787 /*******************************************************************
788 check if an IP is the 0.0.0.0
789 ******************************************************************/
790 BOOL
zero_ip(struct in_addr ip
)
793 putip((char *)&a
,(char *)&ip
);
798 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
799 /******************************************************************
800 Remove any mount options such as -rsize=2048,wsize=2048 etc.
801 Based on a fix from <Thomas.Hepper@icem.de>.
802 *******************************************************************/
804 static void strip_mount_options( pstring
*str
)
809 while(*p
&& !isspace(*p
))
811 while(*p
&& isspace(*p
))
817 pstrcpy(*str
, tmp_str
);
822 /*******************************************************************
823 Patch from jkf@soton.ac.uk
824 Split Luke's automount_server into YP lookup and string splitter
825 so can easily implement automount_path().
826 As we may end up doing both, cache the last YP result.
827 *******************************************************************/
829 #ifdef WITH_NISPLUS_HOME
830 char *automount_lookup(char *user_name
)
832 static fstring last_key
= "";
833 static pstring last_value
= "";
835 char *nis_map
= (char *)lp_nis_home_map_name();
837 char buffer
[NIS_MAXATTRVAL
+ 1];
842 if (strcmp(user_name
, last_key
))
844 slprintf(buffer
, sizeof(buffer
)-1, "[key=%s],%s", user_name
, nis_map
);
845 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
847 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
))
849 if (result
->status
!= NIS_SUCCESS
)
851 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
852 fstrcpy(last_key
, ""); pstrcpy(last_value
, "");
856 object
= result
->objects
.objects_val
;
857 if (object
->zo_data
.zo_type
== ENTRY_OBJ
)
859 entry
= &object
->zo_data
.objdata_u
.en_data
;
860 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
861 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
863 pstrcpy(last_value
, entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
864 pstring_sub(last_value
, "&", user_name
);
865 fstrcpy(last_key
, user_name
);
869 nis_freeresult(result
);
872 strip_mount_options(&last_value
);
874 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name
, last_value
));
877 #else /* WITH_NISPLUS_HOME */
878 char *automount_lookup(char *user_name
)
880 static fstring last_key
= "";
881 static pstring last_value
= "";
883 int nis_error
; /* returned by yp all functions */
884 char *nis_result
; /* yp_match inits this */
885 int nis_result_len
; /* and set this */
886 char *nis_domain
; /* yp_get_default_domain inits this */
887 char *nis_map
= (char *)lp_nis_home_map_name();
889 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
890 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
894 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
896 if (!strcmp(user_name
, last_key
)) {
897 nis_result
= last_value
;
898 nis_result_len
= strlen(last_value
);
903 if ((nis_error
= yp_match(nis_domain
, nis_map
,
904 user_name
, strlen(user_name
),
905 &nis_result
, &nis_result_len
)) == 0) {
906 if (!nis_error
&& nis_result_len
>= sizeof(pstring
)) {
907 nis_result_len
= sizeof(pstring
)-1;
909 fstrcpy(last_key
, user_name
);
910 strncpy(last_value
, nis_result
, nis_result_len
);
911 last_value
[nis_result_len
] = '\0';
912 strip_mount_options(&last_value
);
914 } else if(nis_error
== YPERR_KEY
) {
916 /* If Key lookup fails user home server is not in nis_map
917 use default information for server, and home directory */
919 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
920 user_name
, nis_map
));
921 DEBUG(3, ("using defaults for server and home directory\n"));
923 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
924 yperr_string(nis_error
), user_name
, nis_map
));
929 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, last_value
));
932 #endif /* WITH_NISPLUS_HOME */
936 /*******************************************************************
937 are two IPs on the same subnet?
938 ********************************************************************/
939 BOOL
same_net(struct in_addr ip1
,struct in_addr ip2
,struct in_addr mask
)
941 uint32 net1
,net2
,nmask
;
943 nmask
= ntohl(mask
.s_addr
);
944 net1
= ntohl(ip1
.s_addr
);
945 net2
= ntohl(ip2
.s_addr
);
947 return((net1
& nmask
) == (net2
& nmask
));
951 /****************************************************************************
952 check if a process exists. Does this work on all unixes?
953 ****************************************************************************/
955 BOOL
process_exists(pid_t pid
)
957 return(kill(pid
,0) == 0 || errno
!= ESRCH
);
961 /*******************************************************************
962 Convert a uid into a user name.
963 ********************************************************************/
965 char *uidtoname(uid_t uid
)
970 if (winbind_uidtoname(name
, uid
))
973 pass
= sys_getpwuid(uid
);
974 if (pass
) return(pass
->pw_name
);
975 slprintf(name
, sizeof(name
) - 1, "%d",(int)uid
);
980 /*******************************************************************
981 Convert a gid into a group name.
982 ********************************************************************/
984 char *gidtoname(gid_t gid
)
989 if (winbind_gidtoname(name
, gid
))
993 if (grp
) return(grp
->gr_name
);
994 slprintf(name
,sizeof(name
) - 1, "%d",(int)gid
);
998 /*******************************************************************
999 Convert a user name into a uid. If winbindd is present uses this.
1000 ********************************************************************/
1002 uid_t
nametouid(char *name
)
1004 struct passwd
*pass
;
1008 u
= (uid_t
)strtol(name
, &p
, 0);
1009 if ((p
!= name
) && (*p
== '\0'))
1012 if (winbind_nametouid(&u
, name
))
1015 pass
= sys_getpwnam(name
);
1017 return(pass
->pw_uid
);
1021 /*******************************************************************
1022 Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1023 is present does a shortcut lookup...
1024 ********************************************************************/
1026 gid_t
nametogid(char *name
)
1032 g
= (gid_t
)strtol(name
, &p
, 0);
1033 if ((p
!= name
) && (*p
== '\0'))
1036 if (winbind_nametogid(&g
, name
))
1039 grp
= getgrnam(name
);
1041 return(grp
->gr_gid
);
1045 /*******************************************************************
1046 something really nasty happened - panic!
1047 ********************************************************************/
1048 void smb_panic(char *why
)
1050 char *cmd
= lp_panic_action();
1054 DEBUG(0,("PANIC: %s\n", why
));
1060 /*******************************************************************
1061 a readdir wrapper which just returns the file name
1062 ********************************************************************/
1063 char *readdirname(DIR *p
)
1065 SMB_STRUCT_DIRENT
*ptr
;
1068 if (!p
) return(NULL
);
1070 ptr
= (SMB_STRUCT_DIRENT
*)sys_readdir(p
);
1071 if (!ptr
) return(NULL
);
1073 dname
= ptr
->d_name
;
1076 if (telldir(p
) < 0) return(NULL
);
1079 #ifdef HAVE_BROKEN_READDIR
1080 /* using /usr/ucb/cc is BAD */
1086 int len
= NAMLEN(ptr
);
1087 memcpy(buf
, dname
, len
);
1095 /*******************************************************************
1096 Utility function used to decide if the last component
1097 of a path matches a (possibly wildcarded) entry in a namelist.
1098 ********************************************************************/
1100 BOOL
is_in_path(char *name
, name_compare_entry
*namelist
)
1102 pstring last_component
;
1105 DEBUG(8, ("is_in_path: %s\n", name
));
1107 /* if we have no list it's obviously not in the path */
1108 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
)))
1110 DEBUG(8,("is_in_path: no name list.\n"));
1114 /* Get the last component of the unix name. */
1115 p
= strrchr(name
, '/');
1116 strncpy(last_component
, p
? ++p
: name
, sizeof(last_component
)-1);
1117 last_component
[sizeof(last_component
)-1] = '\0';
1119 for(; namelist
->name
!= NULL
; namelist
++)
1121 if(namelist
->is_wild
)
1123 if (mask_match(last_component
, namelist
->name
, case_sensitive
))
1125 DEBUG(8,("is_in_path: mask match succeeded\n"));
1131 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
1132 (!case_sensitive
&& (StrCaseCmp(last_component
, namelist
->name
) == 0)))
1134 DEBUG(8,("is_in_path: match succeeded\n"));
1139 DEBUG(8,("is_in_path: match not found\n"));
1144 /*******************************************************************
1145 Strip a '/' separated list into an array of
1146 name_compare_enties structures suitable for
1147 passing to is_in_path(). We do this for
1148 speed so we can pre-parse all the names in the list
1149 and don't do it for each call to is_in_path().
1150 namelist is modified here and is assumed to be
1151 a copy owned by the caller.
1152 We also check if the entry contains a wildcard to
1153 remove a potentially expensive call to mask_match
1155 ********************************************************************/
1157 void set_namearray(name_compare_entry
**ppname_array
, char *namelist
)
1160 char *nameptr
= namelist
;
1161 int num_entries
= 0;
1164 (*ppname_array
) = NULL
;
1166 if((nameptr
== NULL
) || ((nameptr
!= NULL
) && (*nameptr
== '\0')))
1169 /* We need to make two passes over the string. The
1170 first to count the number of elements, the second
1175 if ( *nameptr
== '/' )
1177 /* cope with multiple (useless) /s) */
1181 /* find the next / */
1182 name_end
= strchr(nameptr
, '/');
1184 /* oops - the last check for a / didn't find one. */
1185 if (name_end
== NULL
)
1188 /* next segment please */
1189 nameptr
= name_end
+ 1;
1193 if(num_entries
== 0)
1196 if(( (*ppname_array
) = (name_compare_entry
*)malloc(
1197 (num_entries
+ 1) * sizeof(name_compare_entry
))) == NULL
)
1199 DEBUG(0,("set_namearray: malloc fail\n"));
1203 /* Now copy out the names */
1208 if ( *nameptr
== '/' )
1210 /* cope with multiple (useless) /s) */
1214 /* find the next / */
1215 if ((name_end
= strchr(nameptr
, '/')) != NULL
)
1220 /* oops - the last check for a / didn't find one. */
1221 if(name_end
== NULL
)
1224 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1225 if(((*ppname_array
)[i
].name
= strdup(nameptr
)) == NULL
)
1227 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1231 /* next segment please */
1232 nameptr
= name_end
+ 1;
1236 (*ppname_array
)[i
].name
= NULL
;
1241 /****************************************************************************
1242 routine to free a namearray.
1243 ****************************************************************************/
1245 void free_namearray(name_compare_entry
*name_array
)
1250 if(name_array
->name
!= NULL
)
1251 free(name_array
->name
);
1253 free((char *)name_array
);
1256 /****************************************************************************
1257 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1258 is dealt with in posix.c
1259 ****************************************************************************/
1261 BOOL
fcntl_lock(int fd
, int op
, SMB_OFF_T offset
, SMB_OFF_T count
, int type
)
1263 SMB_STRUCT_FLOCK lock
;
1266 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd
,op
,(double)offset
,(double)count
,type
));
1269 lock
.l_whence
= SEEK_SET
;
1270 lock
.l_start
= offset
;
1276 ret
= fcntl(fd
,op
,&lock
);
1279 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno
,strerror(errno
)));
1282 if (op
== SMB_F_GETLK
)
1285 (lock
.l_type
!= F_UNLCK
) &&
1286 (lock
.l_pid
!= 0) &&
1287 (lock
.l_pid
!= sys_getpid()))
1289 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd
,(int)lock
.l_pid
));
1293 /* it must be not locked or locked by me */
1297 /* a lock set or unset */
1300 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1301 (double)offset
,(double)count
,op
,type
,strerror(errno
)));
1305 /* everything went OK */
1306 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1311 /*******************************************************************
1312 is the name specified one of my netbios names
1313 returns true is it is equal, false otherwise
1314 ********************************************************************/
1315 BOOL
is_myname(char *s
)
1320 for (n
=0; my_netbios_names
[n
]; n
++) {
1321 if (strequal(my_netbios_names
[n
], s
))
1324 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1328 /*******************************************************************
1329 set the horrid remote_arch string based on an enum.
1330 ********************************************************************/
1331 void set_remote_arch(enum remote_arch_types type
)
1333 extern fstring remote_arch
;
1338 fstrcpy(remote_arch
, "WfWg");
1341 fstrcpy(remote_arch
, "OS2");
1344 fstrcpy(remote_arch
, "Win95");
1347 fstrcpy(remote_arch
, "WinNT");
1350 fstrcpy(remote_arch
, "Win2K");
1353 fstrcpy(remote_arch
,"Samba");
1356 ra_type
= RA_UNKNOWN
;
1357 fstrcpy(remote_arch
, "UNKNOWN");
1362 /*******************************************************************
1363 Get the remote_arch type.
1364 ********************************************************************/
1365 enum remote_arch_types
get_remote_arch(void)
1371 void out_ascii(FILE *f
, unsigned char *buf
,int len
)
1376 fprintf(f
, "%c", isprint(buf
[i
])?buf
[i
]:'.');
1380 void out_data(FILE *f
,char *buf1
,int len
, int per_line
)
1382 unsigned char *buf
= (unsigned char *)buf1
;
1389 fprintf(f
, "[%03X] ",i
);
1392 fprintf(f
, "%02X ",(int)buf
[i
]);
1394 if (i
%(per_line
/2) == 0) fprintf(f
, " ");
1395 if (i
%per_line
== 0)
1397 out_ascii(f
,&buf
[i
-per_line
],per_line
/2); fprintf(f
, " ");
1398 out_ascii(f
,&buf
[i
-per_line
/2],per_line
/2); fprintf(f
, "\n");
1399 if (i
<len
) fprintf(f
, "[%03X] ",i
);
1402 if ((i
%per_line
) != 0)
1406 n
= per_line
- (i
%per_line
);
1408 if (n
>(per_line
/2)) fprintf(f
, " ");
1413 n
= MIN(per_line
/2,i
%per_line
);
1414 out_ascii(f
,&buf
[i
-(i
%per_line
)],n
); fprintf(f
, " ");
1415 n
= (i
%per_line
) - n
;
1416 if (n
>0) out_ascii(f
,&buf
[i
-n
],n
);
1421 void print_asc(int level
, unsigned char *buf
,int len
)
1425 DEBUG(level
,("%c", isprint(buf
[i
])?buf
[i
]:'.'));
1428 void dump_data(int level
,char *buf1
,int len
)
1430 unsigned char *buf
= (unsigned char *)buf1
;
1434 DEBUG(level
,("[%03X] ",i
));
1436 DEBUG(level
,("%02X ",(int)buf
[i
]));
1438 if (i
%8 == 0) DEBUG(level
,(" "));
1440 print_asc(level
,&buf
[i
-16],8); DEBUG(level
,(" "));
1441 print_asc(level
,&buf
[i
-8],8); DEBUG(level
,("\n"));
1442 if (i
<len
) DEBUG(level
,("[%03X] ",i
));
1450 if (n
>8) DEBUG(level
,(" "));
1451 while (n
--) DEBUG(level
,(" "));
1454 print_asc(level
,&buf
[i
-(i
%16)],n
); DEBUG(level
,(" "));
1456 if (n
>0) print_asc(level
,&buf
[i
-n
],n
);
1457 DEBUG(level
,("\n"));
1461 char *tab_depth(int depth
)
1463 static pstring spaces
;
1464 memset(spaces
, ' ', depth
* 4);
1465 spaces
[depth
* 4] = 0;
1469 /*****************************************************************************
1470 * Provide a checksum on a string
1472 * Input: s - the null-terminated character string for which the checksum
1473 * will be calculated.
1475 * Output: The checksum value calculated for s.
1477 * ****************************************************************************
1479 int str_checksum(const char *s
)
1487 res
^= (c
<< (i
% 15)) ^ (c
>> (15-(i
%15)));
1492 } /* str_checksum */
1496 /*****************************************************************
1497 zero a memory area then free it. Used to catch bugs faster
1498 *****************************************************************/
1499 void zero_free(void *p
, size_t size
)
1506 /*****************************************************************
1507 set our open file limit to a requested max and return the limit
1508 *****************************************************************/
1509 int set_maxfiles(int requested_max
)
1511 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1513 int saved_current_limit
;
1515 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1516 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1519 return requested_max
;
1523 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1524 * account for the extra fd we need
1525 * as well as the log files and standard
1526 * handles etc. Save the limit we want to set in case
1527 * we are running on an OS that doesn't support this limit (AIX)
1528 * which always returns RLIM_INFINITY for rlp.rlim_max.
1531 /* Try raising the hard (max) limit to the requested amount. */
1533 #if defined(RLIM_INFINITY)
1534 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1535 int orig_max
= rlp
.rlim_max
;
1537 if ( rlp
.rlim_max
< requested_max
)
1538 rlp
.rlim_max
= requested_max
;
1540 /* This failing is not an error - many systems (Linux) don't
1541 support our default request of 10,000 open files. JRA. */
1543 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1544 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1545 (int)rlp
.rlim_max
, strerror(errno
) ));
1547 /* Set failed - restore original value from get. */
1548 rlp
.rlim_max
= orig_max
;
1553 /* Now try setting the soft (current) limit. */
1555 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1557 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1558 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1559 (int)rlp
.rlim_cur
, strerror(errno
) ));
1561 return saved_current_limit
;
1564 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1565 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1568 return saved_current_limit
;
1571 #if defined(RLIM_INFINITY)
1572 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1573 return saved_current_limit
;
1576 if((int)rlp
.rlim_cur
> saved_current_limit
)
1577 return saved_current_limit
;
1579 return rlp
.rlim_cur
;
1580 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1582 * No way to know - just guess...
1584 return requested_max
;
1588 /*****************************************************************
1589 splits out the start of the key (HKLM or HKU) and the rest of the key
1590 *****************************************************************/
1591 BOOL
reg_split_key(char *full_keyname
, uint32
*reg_type
, char *key_name
)
1595 if (!next_token(&full_keyname
, tmp
, "\\", sizeof(tmp
)))
1602 DEBUG(10, ("reg_split_key: hive %s\n", tmp
));
1604 if (strequal(tmp
, "HKLM") || strequal(tmp
, "HKEY_LOCAL_MACHINE"))
1606 (*reg_type
) = HKEY_LOCAL_MACHINE
;
1608 else if (strequal(tmp
, "HKU") || strequal(tmp
, "HKEY_USERS"))
1610 (*reg_type
) = HKEY_USERS
;
1614 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp
));
1618 if (next_token(NULL
, tmp
, "\n\r", sizeof(tmp
)))
1620 fstrcpy(key_name
, tmp
);
1627 DEBUG(10, ("reg_split_key: name %s\n", key_name
));
1633 /*****************************************************************
1634 possibly replace mkstemp if it is broken
1635 *****************************************************************/
1636 int smb_mkstemp(char *template)
1638 #if HAVE_SECURE_MKSTEMP
1639 return mkstemp(template);
1641 /* have a reasonable go at emulating it. Hope that
1642 the system mktemp() isn't completly hopeless */
1643 char *p
= mktemp(template);
1645 return open(p
, O_CREAT
|O_EXCL
|O_RDWR
, 0600);
1649 /*****************************************************************
1650 like strdup but for memory
1651 *****************************************************************/
1652 void *memdup(void *p
, size_t size
)
1655 if (size
== 0) return NULL
;
1657 if (!p2
) return NULL
;
1658 memcpy(p2
, p
, size
);
1662 /*****************************************************************
1663 get local hostname and cache result
1664 *****************************************************************/
1665 char *myhostname(void)
1675 /*****************************************************************
1676 a useful function for returning a path in the Samba lock directory
1677 *****************************************************************/
1678 char *lock_path(char *name
)
1680 static pstring fname
;
1682 pstrcpy(fname
,lp_lockdir());
1683 trim_string(fname
,"","/");
1685 if (!directory_exist(fname
,NULL
)) {
1690 pstrcat(fname
,name
);
1695 /*******************************************************************
1696 Given a filename - get its directory name
1697 NB: Returned in static storage. Caveats:
1698 o Not safe in thread environment.
1699 o Caller must not free.
1700 o If caller wishes to preserve, they should copy.
1701 ********************************************************************/
1703 char *parent_dirname(const char *path
)
1705 static pstring dirpath
;
1711 pstrcpy(dirpath
, path
);
1712 p
= strrchr(dirpath
, '/'); /* Find final '/', if any */
1714 pstrcpy(dirpath
, "."); /* No final "/", so dir is "." */
1717 ++p
; /* For root "/", leave "/" in place */
1724 /*******************************************************************
1725 determine if a pattern contains any Microsoft wildcard characters
1726 *******************************************************************/
1727 BOOL
ms_has_wild(char *s
)
1730 while ((c
= *s
++)) {
1743 /*******************************************************************
1744 a wrapper that handles case sensitivity and the special handling
1746 *******************************************************************/
1747 BOOL
mask_match(char *string
, char *pattern
, BOOL is_case_sensitive
)
1750 if (strcmp(string
,"..") == 0) string
= ".";
1751 if (strcmp(pattern
,".") == 0) return False
;
1753 if (is_case_sensitive
) {
1754 return ms_fnmatch(pattern
, string
) == 0;
1757 fstrcpy(p2
, pattern
);
1758 fstrcpy(s2
, string
);
1761 return ms_fnmatch(p2
, s2
) == 0;
1764 /*******************************************************************
1765 Simple case insensitive interface to ms_fnmatch.
1766 *******************************************************************/
1768 BOOL
wild_match(char *string
, char *pattern
)
1772 pstrcpy(p2
, pattern
);
1773 pstrcpy(s2
, string
);
1776 return ms_fnmatch(p2
, s2
) == 0;
1781 /*******************************************************************
1782 This routine is a trick to immediately catch errors when debugging
1783 with insure. A xterm with a gdb is popped up when insure catches
1784 a error. It is Linux specific.
1785 ********************************************************************/
1786 int _Insure_trap_error(int a1
, int a2
, int a3
, int a4
, int a5
, int a6
)
1791 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'";
1793 slprintf(pidstr
, sizeof(pidstr
)-1, "%d", sys_getpid());
1794 pstring_sub(cmd
, "%d", pidstr
);
1798 h
= dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY
);
1799 fn
= dlsym(h
, "_Insure_trap_error");
1802 ret
= fn(a1
, a2
, a3
, a4
, a5
, a6
);