2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2007
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8 Copyright (C) James Peach 2006
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "system/passwd.h"
26 #include "system/filesys.h"
27 #include "lib/util/server_id.h"
29 #include "ctdbd_conn.h"
30 #include "../lib/util/util_pw.h"
32 #include "lib/messaging/messages_dgm.h"
33 #include "libcli/security/security.h"
35 #include "lib/util/sys_rw.h"
36 #include "lib/util/sys_rw_data.h"
37 #include "lib/util/util_process.h"
38 #include "lib/dbwrap/dbwrap_ctdb.h"
39 #include "lib/gencache.h"
41 #ifdef HAVE_SYS_PRCTL_H
42 #include <sys/prctl.h>
45 /* Max allowable allococation - 256mb - 0x10000000 */
46 #define MAX_ALLOC_SIZE (1024*1024*256)
48 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
49 /* rpc/xdr.h uses TRUE and FALSE */
58 #include "system/nis.h"
60 #ifdef WITH_NISPLUS_HOME
61 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
63 * The following lines are needed due to buggy include files
64 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
65 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
66 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
67 * an enum in /usr/include/rpcsvc/nis.h.
74 #if defined(GROUP_OBJ)
78 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
80 #include <rpcsvc/nis.h>
82 #endif /* WITH_NISPLUS_HOME */
83 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
85 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
87 enum protocol_types
get_Protocol(void)
92 void set_Protocol(enum protocol_types p
)
97 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
99 void gfree_all( void )
108 /*******************************************************************
109 Check if a file exists - call vfs_file_exist for samba files.
110 ********************************************************************/
112 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
113 bool fake_dir_create_times
)
119 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
122 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
125 /*******************************************************************
126 Check if a unix domain socket exists - call vfs_file_exist for samba files.
127 ********************************************************************/
129 bool socket_exist(const char *fname
)
132 if (sys_stat(fname
, &st
, false) != 0)
135 return S_ISSOCK(st
.st_ex_mode
);
138 /*******************************************************************
139 Returns the size in bytes of the named given the stat struct.
140 ********************************************************************/
142 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
144 return sbuf
->st_ex_size
;
147 /****************************************************************************
148 Check two stats have identical dev and ino fields.
149 ****************************************************************************/
151 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
152 const SMB_STRUCT_STAT
*sbuf2
)
154 if (sbuf1
->st_ex_dev
!= sbuf2
->st_ex_dev
||
155 sbuf1
->st_ex_ino
!= sbuf2
->st_ex_ino
) {
161 /****************************************************************************
162 Check if a stat struct is identical for use.
163 ****************************************************************************/
165 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
166 const SMB_STRUCT_STAT
*sbuf2
)
168 if (sbuf1
->st_ex_uid
!= sbuf2
->st_ex_uid
||
169 sbuf1
->st_ex_gid
!= sbuf2
->st_ex_gid
||
170 !check_same_dev_ino(sbuf1
, sbuf2
)) {
176 /*******************************************************************
177 Show a smb message structure.
178 ********************************************************************/
180 void show_msg(const char *buf
)
188 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
190 (int)CVAL(buf
,smb_com
),
191 (int)CVAL(buf
,smb_rcls
),
192 (int)CVAL(buf
,smb_reh
),
193 (int)SVAL(buf
,smb_err
),
194 (int)CVAL(buf
,smb_flg
),
195 (int)SVAL(buf
,smb_flg2
)));
196 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
197 (int)SVAL(buf
,smb_tid
),
198 (int)SVAL(buf
,smb_pid
),
199 (int)SVAL(buf
,smb_uid
),
200 (int)SVAL(buf
,smb_mid
)));
201 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
203 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
204 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
205 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
207 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
209 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
217 dump_data(10, (const uint8_t *)smb_buf_const(buf
), bcc
);
220 /*******************************************************************
221 Setup only the byte count for a smb message.
222 ********************************************************************/
224 int set_message_bcc(char *buf
,int num_bytes
)
226 int num_words
= CVAL(buf
,smb_wct
);
227 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
228 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
229 return (smb_size
+ num_words
*2 + num_bytes
);
232 /*******************************************************************
233 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
234 Return the bytes added
235 ********************************************************************/
237 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
239 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
242 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
243 DEBUG(0, ("talloc failed\n"));
248 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
249 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
253 /*******************************************************************
254 Reduce a file name, removing .. elements.
255 ********************************************************************/
257 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
262 DEBUG(3,("dos_clean_name [%s]\n",s
));
264 /* remove any double slashes */
265 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
270 /* Remove leading .\\ characters */
271 if(strncmp(str
, ".\\", 2) == 0) {
272 trim_string(str
, ".\\", NULL
);
274 str
= talloc_strdup(ctx
, ".\\");
281 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
287 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
292 str
= talloc_asprintf(ctx
,
301 trim_string(str
,NULL
,"\\..");
302 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
305 /*******************************************************************
306 Reduce a file name, removing .. elements.
307 ********************************************************************/
309 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
314 DEBUG(3,("unix_clean_name [%s]\n",s
));
316 /* remove any double slashes */
317 str
= talloc_all_string_sub(ctx
, s
, "//","/");
322 /* Remove leading ./ characters */
323 if(strncmp(str
, "./", 2) == 0) {
324 trim_string(str
, "./", NULL
);
326 str
= talloc_strdup(ctx
, "./");
333 while ((p
= strstr_m(str
,"/../")) != NULL
) {
339 if ((p
=strrchr_m(str
,'/')) != NULL
) {
344 str
= talloc_asprintf(ctx
,
353 trim_string(str
,NULL
,"/..");
354 return talloc_all_string_sub(ctx
, str
, "/./", "/");
357 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
359 char *str
= dos_clean_name(ctx
, s
);
363 return unix_clean_name(ctx
, str
);
366 /*******************************************************************
367 Write data into an fd at a given offset. Ignore seek errors.
368 ********************************************************************/
370 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
375 if (pos
== (off_t
)-1) {
376 return write_data(fd
, buffer
, N
);
378 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
380 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
381 if (ret
== -1 && errno
== ESPIPE
) {
382 return write_data(fd
, buffer
+ total
,N
- total
);
385 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
394 return (ssize_t
)total
;
396 /* Use lseek and write_data. */
397 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
398 if (errno
!= ESPIPE
) {
402 return write_data(fd
, buffer
, N
);
406 static int reinit_after_fork_pipe
[2] = { -1, -1 };
408 NTSTATUS
init_before_fork(void)
412 ret
= pipe(reinit_after_fork_pipe
);
416 status
= map_nt_error_from_unix_common(errno
);
418 DEBUG(0, ("Error creating child_pipe: %s\n",
428 * Detect died parent by detecting EOF on the pipe
430 static void reinit_after_fork_pipe_handler(struct tevent_context
*ev
,
431 struct tevent_fd
*fde
,
437 if (sys_read(reinit_after_fork_pipe
[0], &c
, 1) != 1) {
439 * we have reached EOF on stdin, which means the
440 * parent has exited. Shutdown the server
443 (void)kill(getpid(), SIGTERM
);
448 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
449 struct tevent_context
*ev_ctx
,
450 bool parent_longlived
,
453 NTSTATUS status
= NT_STATUS_OK
;
457 * The main process thread should never
458 * allow per_thread_cwd_enable() to be
461 per_thread_cwd_disable();
463 if (reinit_after_fork_pipe
[1] != -1) {
464 close(reinit_after_fork_pipe
[1]);
465 reinit_after_fork_pipe
[1] = -1;
468 /* tdb needs special fork handling */
469 if (tdb_reopen_all(parent_longlived
? 1 : 0) != 0) {
470 DEBUG(0,("tdb_reopen_all failed.\n"));
471 status
= NT_STATUS_OPEN_FAILED
;
475 if (ev_ctx
!= NULL
) {
476 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
477 if (tevent_re_initialise(ev_ctx
) != 0) {
478 smb_panic(__location__
": Failed to re-initialise event context");
482 if (reinit_after_fork_pipe
[0] != -1) {
483 struct tevent_fd
*fde
;
485 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
486 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
487 reinit_after_fork_pipe_handler
, NULL
);
489 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
495 * For clustering, we need to re-init our ctdbd connection after the
498 status
= messaging_reinit(msg_ctx
);
499 if (!NT_STATUS_IS_OK(status
)) {
500 DEBUG(0,("messaging_reinit() failed: %s\n",
504 if (lp_clustering()) {
505 ret
= ctdb_async_ctx_reinit(
506 NULL
, messaging_tevent_context(msg_ctx
));
508 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
510 return map_nt_error_from_unix(ret
);
516 prctl_set_comment("%s", comment
);
523 /****************************************************************************
524 (Hopefully) efficient array append.
525 ****************************************************************************/
527 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
528 void *element
, void *_array
, uint32_t *num_elements
,
531 void **array
= (void **)_array
;
533 if (*array_size
< 0) {
537 if (*array
== NULL
) {
538 if (*array_size
== 0) {
542 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
546 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
547 if (*array
== NULL
) {
552 if (*num_elements
== *array_size
) {
555 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
559 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
560 element_size
* (*array_size
));
562 if (*array
== NULL
) {
567 memcpy((char *)(*array
) + element_size
*(*num_elements
),
568 element
, element_size
);
578 /****************************************************************************
579 Get my own domain name, or "" if we have none.
580 ****************************************************************************/
582 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
587 domname
= get_mydnsfullname();
592 p
= strchr_m(domname
, '.');
595 return talloc_strdup(ctx
, p
);
597 return talloc_strdup(ctx
, "");
601 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
602 /******************************************************************
603 Remove any mount options such as -rsize=2048,wsize=2048 etc.
604 Based on a fix from <Thomas.Hepper@icem.de>.
605 Returns a malloc'ed string.
606 *******************************************************************/
608 static char *strip_mount_options(TALLOC_CTX
*ctx
, const char *str
)
612 while(*p
&& !isspace(*p
))
614 while(*p
&& isspace(*p
))
617 return talloc_strdup(ctx
, p
);
623 /*******************************************************************
624 Patch from jkf@soton.ac.uk
625 Split Luke's automount_server into YP lookup and string splitter
626 so can easily implement automount_path().
627 Returns a malloc'ed string.
628 *******************************************************************/
630 #ifdef WITH_NISPLUS_HOME
631 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
633 const struct loadparm_substitution
*lp_sub
=
634 loadparm_s3_global_substitution();
637 char *nis_map
= (char *)lp_homedir_map(talloc_tos(), lp_sub
);
639 char buffer
[NIS_MAXATTRVAL
+ 1];
644 snprintf(buffer
, sizeof(buffer
), "[key=%s],%s", user_name
, nis_map
);
645 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
647 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
)) {
648 if (result
->status
!= NIS_SUCCESS
) {
649 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
651 object
= result
->objects
.objects_val
;
652 if (object
->zo_data
.zo_type
== ENTRY_OBJ
) {
653 entry
= &object
->zo_data
.objdata_u
.en_data
;
654 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
655 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
657 value
= talloc_strdup(ctx
,
658 entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
660 nis_freeresult(result
);
663 value
= talloc_string_sub(ctx
,
670 nis_freeresult(result
);
673 value
= strip_mount_options(ctx
, value
);
674 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
679 #else /* WITH_NISPLUS_HOME */
681 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
683 const struct loadparm_substitution
*lp_sub
=
684 loadparm_s3_global_substitution();
687 int nis_error
; /* returned by yp all functions */
688 char *nis_result
; /* yp_match inits this */
689 int nis_result_len
; /* and set this */
690 char *nis_domain
; /* yp_get_default_domain inits this */
691 char *nis_map
= lp_homedir_map(talloc_tos(), lp_sub
);
693 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
694 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
698 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
700 if ((nis_error
= yp_match(nis_domain
, nis_map
, user_name
,
701 strlen(user_name
), &nis_result
,
702 &nis_result_len
)) == 0) {
703 if (nis_result_len
> 0 && nis_result
[nis_result_len
] == '\n') {
704 nis_result
[nis_result_len
] = '\0';
706 value
= talloc_strdup(ctx
, nis_result
);
710 value
= strip_mount_options(ctx
, value
);
711 } else if(nis_error
== YPERR_KEY
) {
712 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
713 user_name
, nis_map
));
714 DEBUG(3, ("using defaults for server and home directory\n"));
716 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
717 yperr_string(nis_error
), user_name
, nis_map
));
721 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, value
));
725 #endif /* WITH_NISPLUS_HOME */
728 bool process_exists(const struct server_id pid
)
730 return serverid_exists(&pid
);
733 /*******************************************************************
734 Convert a uid into a user name.
735 ********************************************************************/
737 const char *uidtoname(uid_t uid
)
739 TALLOC_CTX
*ctx
= talloc_tos();
741 struct passwd
*pass
= NULL
;
743 pass
= getpwuid_alloc(ctx
,uid
);
745 name
= talloc_strdup(ctx
,pass
->pw_name
);
748 name
= talloc_asprintf(ctx
,
755 /*******************************************************************
756 Convert a gid into a group name.
757 ********************************************************************/
759 char *gidtoname(gid_t gid
)
765 return talloc_strdup(talloc_tos(), grp
->gr_name
);
768 return talloc_asprintf(talloc_tos(),
774 /*******************************************************************
775 Convert a user name into a uid.
776 ********************************************************************/
778 uid_t
nametouid(const char *name
)
784 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
791 u
= (uid_t
)strtol(name
, &p
, 0);
792 if ((p
!= name
) && (*p
== '\0'))
798 /*******************************************************************
799 Convert a name to a gid_t if possible. Return -1 if not a group.
800 ********************************************************************/
802 gid_t
nametogid(const char *name
)
808 g
= (gid_t
)strtol(name
, &p
, 0);
809 if ((p
!= name
) && (*p
== '\0'))
812 grp
= getgrnam(name
);
818 /*******************************************************************
819 Something really nasty happened - panic !
820 ********************************************************************/
822 void smb_panic_s3(const char *why
)
824 const struct loadparm_substitution
*lp_sub
=
825 loadparm_s3_global_substitution();
829 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
831 * Make sure all children can attach a debugger.
833 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
836 cmd
= lp_panic_action(talloc_tos(), lp_sub
);
838 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd
));
839 result
= system(cmd
);
842 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
845 DEBUG(0, ("smb_panic(): action returned status %d\n",
846 WEXITSTATUS(result
)));
852 /*******************************************************************
853 A readdir wrapper which just returns the file name.
854 ********************************************************************/
856 const char *readdirname(DIR *p
)
864 ptr
= (struct dirent
*)readdir(p
);
875 #ifdef HAVE_BROKEN_READDIR_NAME
876 /* using /usr/ucb/cc is BAD */
880 return talloc_strdup(talloc_tos(), dname
);
883 /*******************************************************************
884 Utility function used to decide if the last component
885 of a path matches a (possibly wildcarded) entry in a namelist.
886 ********************************************************************/
888 bool is_in_path(const char *name
, name_compare_entry
*namelist
, bool case_sensitive
)
890 const char *last_component
;
892 /* if we have no list it's obviously not in the path */
893 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
))) {
897 DEBUG(8, ("is_in_path: %s\n", name
));
899 /* Get the last component of the unix name. */
900 last_component
= strrchr_m(name
, '/');
901 if (!last_component
) {
902 last_component
= name
;
904 last_component
++; /* Go past '/' */
907 for(; namelist
->name
!= NULL
; namelist
++) {
908 if(namelist
->is_wild
) {
909 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
910 DEBUG(8,("is_in_path: mask match succeeded\n"));
914 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
915 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
916 DEBUG(8,("is_in_path: match succeeded\n"));
921 DEBUG(8,("is_in_path: match not found\n"));
925 /*******************************************************************
926 Strip a '/' separated list into an array of
927 name_compare_enties structures suitable for
928 passing to is_in_path(). We do this for
929 speed so we can pre-parse all the names in the list
930 and don't do it for each call to is_in_path().
931 We also check if the entry contains a wildcard to
932 remove a potentially expensive call to mask_match
934 ********************************************************************/
936 void set_namearray(name_compare_entry
**ppname_array
, const char *namelist_in
)
945 (*ppname_array
) = NULL
;
947 if((namelist_in
== NULL
) || ((namelist_in
!= NULL
) && (*namelist_in
== '\0')))
950 namelist
= talloc_strdup(talloc_tos(), namelist_in
);
951 if (namelist
== NULL
) {
952 DEBUG(0,("set_namearray: talloc fail\n"));
957 namelist_end
= &namelist
[strlen(namelist
)];
959 /* We need to make two passes over the string. The
960 first to count the number of elements, the second
964 while(nameptr
<= namelist_end
) {
965 if ( *nameptr
== '/' ) {
966 /* cope with multiple (useless) /s) */
971 if ( *nameptr
== '\0' )
974 /* find the next '/' or consume remaining */
975 name_end
= strchr_m(nameptr
, '/');
976 if (name_end
== NULL
) {
977 /* Point nameptr at the terminating '\0' */
978 nameptr
+= strlen(nameptr
);
980 /* next segment please */
981 nameptr
= name_end
+ 1;
986 if(num_entries
== 0) {
987 talloc_free(namelist
);
991 if(( (*ppname_array
) = SMB_MALLOC_ARRAY(name_compare_entry
, num_entries
+ 1)) == NULL
) {
992 DEBUG(0,("set_namearray: malloc fail\n"));
993 talloc_free(namelist
);
997 /* Now copy out the names */
1000 while(nameptr
<= namelist_end
) {
1001 if ( *nameptr
== '/' ) {
1002 /* cope with multiple (useless) /s) */
1006 /* anything left? */
1007 if ( *nameptr
== '\0' )
1010 /* find the next '/' or consume remaining */
1011 name_end
= strchr_m(nameptr
, '/');
1012 if (name_end
!= NULL
) {
1016 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1017 if(((*ppname_array
)[i
].name
= SMB_STRDUP(nameptr
)) == NULL
) {
1018 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1019 talloc_free(namelist
);
1023 if (name_end
== NULL
) {
1024 /* Point nameptr at the terminating '\0' */
1025 nameptr
+= strlen(nameptr
);
1027 /* next segment please */
1028 nameptr
= name_end
+ 1;
1033 (*ppname_array
)[i
].name
= NULL
;
1035 talloc_free(namelist
);
1040 #define DBGC_CLASS DBGC_LOCKING
1042 /****************************************************************************
1043 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1044 is dealt with in posix.c
1045 Returns True if we have information regarding this lock region (and returns
1046 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1047 ****************************************************************************/
1049 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
1054 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1055 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
1057 lock
.l_type
= *ptype
;
1058 lock
.l_whence
= SEEK_SET
;
1059 lock
.l_start
= *poffset
;
1060 lock
.l_len
= *pcount
;
1063 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
1067 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1068 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
1073 *ptype
= lock
.l_type
;
1074 *poffset
= lock
.l_start
;
1075 *pcount
= lock
.l_len
;
1078 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1079 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
1083 #if defined(HAVE_OFD_LOCKS)
1084 int map_process_lock_to_ofd_lock(int op
)
1104 #else /* HAVE_OFD_LOCKS */
1105 int map_process_lock_to_ofd_lock(int op
)
1109 #endif /* HAVE_OFD_LOCKS */
1112 #define DBGC_CLASS DBGC_ALL
1114 /*******************************************************************
1115 Is the name specified one of my netbios names.
1116 Returns true if it is equal, false otherwise.
1117 ********************************************************************/
1119 bool is_myname(const char *s
)
1124 for (n
=0; my_netbios_names(n
); n
++) {
1125 const char *nbt_name
= my_netbios_names(n
);
1127 if (strncasecmp_m(nbt_name
, s
, MAX_NETBIOSNAME_LEN
-1) == 0) {
1132 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1136 /*******************************************************************
1137 we distinguish between 2K and XP by the "Native Lan Manager" string
1138 WinXP => "Windows 2002 5.1"
1139 WinXP 64bit => "Windows XP 5.2"
1140 Win2k => "Windows 2000 5.0"
1141 NT4 => "Windows NT 4.0"
1142 Win9x => "Windows 4.0"
1143 Windows 2003 doesn't set the native lan manager string but
1144 they do set the domain to "Windows 2003 5.2" (probably a bug).
1145 ********************************************************************/
1147 void ra_lanman_string( const char *native_lanman
)
1149 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
1150 set_remote_arch( RA_WINXP
);
1151 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
1152 set_remote_arch( RA_WINXP64
);
1153 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
1154 set_remote_arch( RA_WIN2K3
);
1157 static const char *remote_arch_strings
[] = {
1158 [RA_UNKNOWN
] = "UNKNOWN",
1161 [RA_WIN95
] = "Win95",
1162 [RA_WINNT
] = "WinNT",
1163 [RA_WIN2K
] = "Win2K",
1164 [RA_WINXP
] = "WinXP",
1165 [RA_WIN2K3
] = "Win2K3",
1166 [RA_VISTA
] = "Vista",
1167 [RA_SAMBA
] = "Samba",
1168 [RA_CIFSFS
] = "CIFSFS",
1169 [RA_WINXP64
] = "WinXP64",
1173 const char *get_remote_arch_str(void)
1175 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1177 * set_remote_arch() already checks this so ra_type
1178 * should be in the allowed range, but anyway, let's
1179 * do another bound check here.
1181 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1182 ra_type
= RA_UNKNOWN
;
1184 return remote_arch_strings
[ra_type
];
1187 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
1191 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
1192 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
1199 /*******************************************************************
1200 Set the horrid remote_arch string based on an enum.
1201 ********************************************************************/
1203 void set_remote_arch(enum remote_arch_types type
)
1205 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1207 * This protects against someone adding values to enum
1208 * remote_arch_types without updating
1209 * remote_arch_strings array.
1211 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1212 ra_type
= RA_UNKNOWN
;
1217 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1218 get_remote_arch_str()));
1221 /*******************************************************************
1222 Get the remote_arch type.
1223 ********************************************************************/
1225 enum remote_arch_types
get_remote_arch(void)
1230 #define RA_CACHE_TTL 7*24*3600
1232 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1235 struct GUID_txt_buf guid_buf
;
1236 const char *guid_string
= NULL
;
1238 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1239 if (guid_string
== NULL
) {
1243 fstr_sprintf(key
, "RA/%s", guid_string
);
1247 struct ra_parser_state
{
1249 enum remote_arch_types ra
;
1252 static void ra_parser(const struct gencache_timeout
*t
,
1256 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1257 const char *ra_str
= NULL
;
1259 if (gencache_timeout_expired(t
)) {
1263 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1264 DBG_ERR("Remote arch cache key not a string\n");
1268 ra_str
= (const char *)blob
.data
;
1269 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1271 state
->ra
= get_remote_arch_from_str(ra_str
);
1272 state
->found
= true;
1276 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1280 struct ra_parser_state state
= (struct ra_parser_state
) {
1285 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1290 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1291 if (!ok
|| !state
.found
) {
1295 if (state
.ra
== RA_UNKNOWN
) {
1299 set_remote_arch(state
.ra
);
1303 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1307 const char *ra_str
= NULL
;
1309 if (get_remote_arch() == RA_UNKNOWN
) {
1313 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1318 ra_str
= get_remote_arch_str();
1319 if (ra_str
== NULL
) {
1323 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1331 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1335 if (get_remote_arch() == RA_UNKNOWN
) {
1338 ok
= remote_arch_cache_get(client_guid
);
1345 ok
= remote_arch_cache_set(client_guid
);
1351 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1356 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1362 ok
= gencache_del(ra_key
);
1372 const char *tab_depth(int level
, int depth
)
1374 if( CHECK_DEBUGLVL(level
) ) {
1375 dbgtext("%*s", depth
*4, "");
1380 /*****************************************************************************
1381 Provide a checksum on a string
1383 Input: s - the null-terminated character string for which the checksum
1386 Output: The checksum value calculated for s.
1387 *****************************************************************************/
1389 int str_checksum(const char *s
)
1395 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1396 .dsize
= strlen(s
) };
1398 return tdb_jenkins_hash(&key
);
1401 /*****************************************************************
1402 Zero a memory area then free it. Used to catch bugs faster.
1403 *****************************************************************/
1405 void zero_free(void *p
, size_t size
)
1411 /*****************************************************************
1412 Set our open file limit to a requested max and return the limit.
1413 *****************************************************************/
1415 int set_maxfiles(int requested_max
)
1417 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1419 int saved_current_limit
;
1421 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1422 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1425 return requested_max
;
1429 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1430 * account for the extra fd we need
1431 * as well as the log files and standard
1432 * handles etc. Save the limit we want to set in case
1433 * we are running on an OS that doesn't support this limit (AIX)
1434 * which always returns RLIM_INFINITY for rlp.rlim_max.
1437 /* Try raising the hard (max) limit to the requested amount. */
1439 #if defined(RLIM_INFINITY)
1440 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1441 int orig_max
= rlp
.rlim_max
;
1443 if ( rlp
.rlim_max
< requested_max
)
1444 rlp
.rlim_max
= requested_max
;
1446 /* This failing is not an error - many systems (Linux) don't
1447 support our default request of 10,000 open files. JRA. */
1449 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1450 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1451 (int)rlp
.rlim_max
, strerror(errno
) ));
1453 /* Set failed - restore original value from get. */
1454 rlp
.rlim_max
= orig_max
;
1459 /* Now try setting the soft (current) limit. */
1461 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1463 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1464 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1465 (int)rlp
.rlim_cur
, strerror(errno
) ));
1467 return saved_current_limit
;
1470 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1471 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1474 return saved_current_limit
;
1477 #if defined(RLIM_INFINITY)
1478 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1479 return saved_current_limit
;
1482 if((int)rlp
.rlim_cur
> saved_current_limit
)
1483 return saved_current_limit
;
1485 return rlp
.rlim_cur
;
1486 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1488 * No way to know - just guess...
1490 return requested_max
;
1494 /*****************************************************************
1495 malloc that aborts with smb_panic on fail or zero size.
1496 *****************************************************************/
1498 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1502 smb_panic("smb_xmalloc_array: called with zero size");
1504 if (count
>= MAX_ALLOC_SIZE
/size
) {
1505 smb_panic("smb_xmalloc_array: alloc size too large");
1507 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1508 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1509 (unsigned long)size
, (unsigned long)count
));
1510 smb_panic("smb_xmalloc_array: malloc failed");
1515 /*****************************************************************
1516 Get local hostname and cache result.
1517 *****************************************************************/
1519 char *myhostname(void)
1523 ret
= get_myname(NULL
);
1528 /*****************************************************************
1529 Get local hostname and cache result.
1530 *****************************************************************/
1532 char *myhostname_upper(void)
1536 char *name
= get_myname(NULL
);
1540 ret
= strupper_talloc(NULL
, name
);
1546 /*******************************************************************
1547 Given a filename - get its directory name
1548 ********************************************************************/
1550 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1556 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1559 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1570 if (!(*parent
= (char *)talloc_memdup(mem_ctx
, dir
, len
+1))) {
1573 (*parent
)[len
] = '\0';
1581 /*******************************************************************
1582 Determine if a pattern contains any Microsoft wildcard characters.
1583 *******************************************************************/
1585 bool ms_has_wild(const char *s
)
1589 while ((c
= *s
++)) {
1602 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1605 if (!s
) return False
;
1606 while ((c
= *s
++)) {
1608 case UCS2_CHAR('*'):
1609 case UCS2_CHAR('?'):
1610 case UCS2_CHAR('<'):
1611 case UCS2_CHAR('>'):
1612 case UCS2_CHAR('"'):
1619 /*******************************************************************
1620 A wrapper that handles case sensitivity and the special handling
1622 *******************************************************************/
1624 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1626 if (ISDOTDOT(string
))
1631 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1634 /*******************************************************************
1635 A wrapper that handles case sensitivity and the special handling
1636 of the ".." name. Varient that is only called by old search code which requires
1637 pattern translation.
1638 *******************************************************************/
1640 bool mask_match_search(const char *string
, const char *pattern
, bool is_case_sensitive
)
1642 if (ISDOTDOT(string
))
1647 return ms_fnmatch(pattern
, string
, True
, is_case_sensitive
) == 0;
1650 /*******************************************************************
1651 A wrapper that handles a list of patters and calls mask_match()
1652 on each. Returns True if any of the patterns match.
1653 *******************************************************************/
1655 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1657 while (listLen
-- > 0) {
1658 if (mask_match(string
, *list
++, is_case_sensitive
))
1664 /**********************************************************************
1665 Converts a name to a fully qualified domain name.
1666 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1667 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1668 canonical name of the host. getaddrinfo() may use a variety of sources
1669 including /etc/hosts to obtain the domainname. It expects aliases in
1670 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1671 ************************************************************************/
1673 bool name_to_fqdn(fstring fqdn
, const char *name
)
1676 struct addrinfo hints
;
1677 struct addrinfo
*result
;
1680 /* Configure hints to obtain canonical name */
1682 memset(&hints
, 0, sizeof(struct addrinfo
));
1683 hints
.ai_family
= AF_UNSPEC
; /* Allow IPv4 or IPv6 */
1684 hints
.ai_socktype
= SOCK_DGRAM
; /* Datagram socket */
1685 hints
.ai_flags
= AI_CANONNAME
; /* Get host's FQDN */
1686 hints
.ai_protocol
= 0; /* Any protocol */
1688 s
= getaddrinfo(name
, NULL
, &hints
, &result
);
1690 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s
)));
1691 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name
));
1692 fstrcpy(fqdn
, name
);
1695 full
= result
->ai_canonname
;
1697 /* Find out if the FQDN is returned as an alias
1698 * to cope with /etc/hosts files where the first
1699 * name is not the FQDN but the short name.
1700 * getaddrinfo provides no easy way of handling aliases
1701 * in /etc/hosts. Users should make sure the FQDN
1702 * comes first in /etc/hosts. */
1703 if (full
&& (! strchr_m(full
, '.'))) {
1704 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1705 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1706 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1707 DEBUGADD(1, (" prior to any aliases.\n"));
1709 if (full
&& (strcasecmp_m(full
, "localhost.localdomain") == 0)) {
1710 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1711 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1712 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1713 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1716 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name
, full
));
1717 fstrcpy(fqdn
, full
);
1718 freeaddrinfo(result
); /* No longer needed */
1722 uint32_t map_share_mode_to_deny_mode(uint32_t share_access
, uint32_t private_options
)
1724 switch (share_access
& ~FILE_SHARE_DELETE
) {
1725 case FILE_SHARE_NONE
:
1727 case FILE_SHARE_READ
:
1729 case FILE_SHARE_WRITE
:
1731 case FILE_SHARE_READ
|FILE_SHARE_WRITE
:
1734 if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
) {
1736 } else if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
) {
1740 return (uint32_t)-1;
1743 struct server_id
interpret_pid(const char *pid_string
)
1745 return server_id_from_string(get_my_vnn(), pid_string
);
1748 /****************************************************************
1749 Check if an offset into a buffer is safe.
1750 If this returns True it's safe to indirect into the byte at
1752 ****************************************************************/
1754 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1756 const char *end_base
= buf_base
+ buf_len
;
1757 char *end_ptr
= ptr
+ off
;
1759 if (!buf_base
|| !ptr
) {
1763 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1764 return False
; /* wrap. */
1767 if (end_ptr
< end_base
) {
1773 /****************************************************************
1774 Return a safe pointer into a buffer, or NULL.
1775 ****************************************************************/
1777 char *get_safe_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1779 return is_offset_safe(buf_base
, buf_len
, ptr
, off
) ?
1783 /****************************************************************
1784 Return a safe pointer into a string within a buffer, or NULL.
1785 ****************************************************************/
1787 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1789 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1792 /* Check if a valid string exists at this offset. */
1793 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1799 /****************************************************************
1800 Return an SVAL at a pointer, or failval if beyond the end.
1801 ****************************************************************/
1803 int get_safe_SVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1806 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1809 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+1)) {
1812 return SVAL(ptr
,off
);
1815 /****************************************************************
1816 Return an IVAL at a pointer, or failval if beyond the end.
1817 ****************************************************************/
1819 int get_safe_IVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1822 * Note we use off+3 here, not off+4 as IVAL accesses
1823 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1825 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+3)) {
1828 return IVAL(ptr
,off
);
1831 /****************************************************************
1832 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1833 call (they take care of winbind separator and other winbind specific settings).
1834 ****************************************************************/
1836 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1837 const char *full_name
,
1841 const char *p
= NULL
;
1843 p
= strchr_m(full_name
, '\\');
1846 *domain
= talloc_strndup(mem_ctx
, full_name
,
1847 PTR_DIFF(p
, full_name
));
1848 if (*domain
== NULL
) {
1851 *user
= talloc_strdup(mem_ctx
, p
+1);
1852 if (*user
== NULL
) {
1853 TALLOC_FREE(*domain
);
1858 *user
= talloc_strdup(mem_ctx
, full_name
);
1859 if (*user
== NULL
) {
1867 /****************************************************************
1868 strip off leading '\\' from a hostname
1869 ****************************************************************/
1871 const char *strip_hostname(const char *s
)
1877 if (strlen_m(s
) < 3) {
1881 if (s
[0] == '\\') s
++;
1882 if (s
[0] == '\\') s
++;
1887 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
1889 if (!NT_STATUS_IS_OK(err1
)) {
1893 if (!NT_STATUS_IS_OK(err2
)) {
1900 int timeval_to_msec(struct timeval t
)
1902 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
1905 /*******************************************************************
1906 Check a given DOS pathname is valid for a share.
1907 ********************************************************************/
1909 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
1913 if (!dos_pathname
) {
1917 ptr
= talloc_strdup(ctx
, dos_pathname
);
1921 /* Convert any '\' paths to '/' */
1923 ptr
= unix_clean_name(ctx
, ptr
);
1928 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1929 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
1932 /* Only absolute paths allowed. */
1939 /*******************************************************************
1940 Return True if the filename is one of the special executable types.
1941 ********************************************************************/
1943 bool is_executable(const char *fname
)
1945 if ((fname
= strrchr_m(fname
,'.'))) {
1946 if (strequal(fname
,".com") ||
1947 strequal(fname
,".dll") ||
1948 strequal(fname
,".exe") ||
1949 strequal(fname
,".sym")) {
1956 /****************************************************************************
1957 Open a file with a share mode - old openX method - map into NTCreate.
1958 ****************************************************************************/
1960 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
1961 int deny_mode
, int open_func
,
1962 uint32_t *paccess_mask
,
1963 uint32_t *pshare_mode
,
1964 uint32_t *pcreate_disposition
,
1965 uint32_t *pcreate_options
,
1966 uint32_t *pprivate_flags
)
1968 uint32_t access_mask
;
1969 uint32_t share_mode
;
1970 uint32_t create_disposition
;
1971 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
1972 uint32_t private_flags
= 0;
1974 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1975 "open_func = 0x%x\n",
1976 smb_base_fname
, (unsigned int)deny_mode
,
1977 (unsigned int)open_func
));
1979 /* Create the NT compatible access_mask. */
1980 switch (GET_OPENX_MODE(deny_mode
)) {
1981 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
1982 case DOS_OPEN_RDONLY
:
1983 access_mask
= FILE_GENERIC_READ
;
1985 case DOS_OPEN_WRONLY
:
1986 access_mask
= FILE_GENERIC_WRITE
;
1990 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
1993 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1994 (unsigned int)GET_OPENX_MODE(deny_mode
)));
1998 /* Create the NT compatible create_disposition. */
1999 switch (open_func
) {
2000 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2001 create_disposition
= FILE_CREATE
;
2004 case OPENX_FILE_EXISTS_OPEN
:
2005 create_disposition
= FILE_OPEN
;
2008 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2009 create_disposition
= FILE_OPEN_IF
;
2012 case OPENX_FILE_EXISTS_TRUNCATE
:
2013 create_disposition
= FILE_OVERWRITE
;
2016 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2017 create_disposition
= FILE_OVERWRITE_IF
;
2021 /* From samba4 - to be confirmed. */
2022 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
2023 create_disposition
= FILE_CREATE
;
2026 DEBUG(10,("map_open_params_to_ntcreate: bad "
2027 "open_func 0x%x\n", (unsigned int)open_func
));
2031 /* Create the NT compatible share modes. */
2032 switch (GET_DENY_MODE(deny_mode
)) {
2034 share_mode
= FILE_SHARE_NONE
;
2038 share_mode
= FILE_SHARE_READ
;
2042 share_mode
= FILE_SHARE_WRITE
;
2046 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2050 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
;
2051 if (is_executable(smb_base_fname
)) {
2052 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2054 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
2055 share_mode
= FILE_SHARE_READ
;
2057 share_mode
= FILE_SHARE_NONE
;
2063 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
;
2064 share_mode
= FILE_SHARE_NONE
;
2068 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2069 (unsigned int)GET_DENY_MODE(deny_mode
) ));
2073 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2074 "share_mode = 0x%x, create_disposition = 0x%x, "
2075 "create_options = 0x%x private_flags = 0x%x\n",
2077 (unsigned int)access_mask
,
2078 (unsigned int)share_mode
,
2079 (unsigned int)create_disposition
,
2080 (unsigned int)create_options
,
2081 (unsigned int)private_flags
));
2084 *paccess_mask
= access_mask
;
2087 *pshare_mode
= share_mode
;
2089 if (pcreate_disposition
) {
2090 *pcreate_disposition
= create_disposition
;
2092 if (pcreate_options
) {
2093 *pcreate_options
= create_options
;
2095 if (pprivate_flags
) {
2096 *pprivate_flags
= private_flags
;
2103 /*************************************************************************
2104 Return a talloced copy of a struct security_unix_token. NULL on fail.
2105 *************************************************************************/
2107 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
2109 struct security_unix_token
*cpy
;
2111 cpy
= talloc(ctx
, struct security_unix_token
);
2116 cpy
->uid
= tok
->uid
;
2117 cpy
->gid
= tok
->gid
;
2118 cpy
->ngroups
= tok
->ngroups
;
2120 /* Make this a talloc child of cpy. */
2121 cpy
->groups
= (gid_t
*)talloc_memdup(
2122 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
2133 /****************************************************************************
2135 ****************************************************************************/
2137 struct security_unix_token
*root_unix_token(TALLOC_CTX
*mem_ctx
)
2139 struct security_unix_token
*t
= NULL
;
2141 t
= talloc_zero(mem_ctx
, struct security_unix_token
);
2147 * This is not needed, but lets make it explicit, not implicit.
2149 *t
= (struct security_unix_token
) {
2159 char *utok_string(TALLOC_CTX
*mem_ctx
, const struct security_unix_token
*tok
)
2164 str
= talloc_asprintf(
2166 "uid=%ju, gid=%ju, %"PRIu32
" groups:",
2167 (uintmax_t)(tok
->uid
),
2168 (uintmax_t)(tok
->gid
),
2174 for (i
=0; i
<tok
->ngroups
; i
++) {
2176 tmp
= talloc_asprintf_append_buffer(
2177 str
, " %ju", (uintmax_t)tok
->groups
[i
]);
2188 /****************************************************************************
2189 Check that a file matches a particular file type.
2190 ****************************************************************************/
2192 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
2196 /* Check the "may have" search bits. */
2197 if (((mode
& ~dirtype
) &
2198 (FILE_ATTRIBUTE_HIDDEN
|
2199 FILE_ATTRIBUTE_SYSTEM
|
2200 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
2204 /* Check the "must have" bits,
2205 which are the may have bits shifted eight */
2206 /* If must have bit is set, the file/dir can
2207 not be returned in search unless the matching
2208 file attribute is set */
2209 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
2210 FILE_ATTRIBUTE_ARCHIVE
|
2211 FILE_ATTRIBUTE_READONLY
|
2212 FILE_ATTRIBUTE_HIDDEN
|
2213 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
2215 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
2216 FILE_ATTRIBUTE_ARCHIVE
|
2217 FILE_ATTRIBUTE_READONLY
|
2218 FILE_ATTRIBUTE_HIDDEN
|
2219 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
2220 /* check if matching attribute present */