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"
40 #include "lib/util/string_wrappers.h"
42 #ifdef HAVE_SYS_PRCTL_H
43 #include <sys/prctl.h>
46 /* Max allowable allococation - 256mb - 0x10000000 */
47 #define MAX_ALLOC_SIZE (1024*1024*256)
49 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
50 /* rpc/xdr.h uses TRUE and FALSE */
59 #include "system/nis.h"
61 #ifdef WITH_NISPLUS_HOME
62 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
64 * The following lines are needed due to buggy include files
65 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
66 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
67 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
68 * an enum in /usr/include/rpcsvc/nis.h.
75 #if defined(GROUP_OBJ)
79 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
81 #include <rpcsvc/nis.h>
83 #endif /* WITH_NISPLUS_HOME */
84 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
86 static enum protocol_types Protocol = PROTOCOL_COREPLUS;
88 enum protocol_types get_Protocol(void)
93 void set_Protocol(enum protocol_types p)
98 static enum remote_arch_types ra_type = RA_UNKNOWN;
100 void gfree_all( void )
109 /*******************************************************************
110 Check if a file exists - call vfs_file_exist for samba files.
111 ********************************************************************/
113 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
114 bool fake_dir_create_times)
120 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
123 return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
126 /*******************************************************************
127 Check if a unix domain socket exists - call vfs_file_exist for samba files.
128 ********************************************************************/
130 bool socket_exist(const char *fname)
133 if (sys_stat(fname, &st, false) != 0)
136 return S_ISSOCK(st.st_ex_mode);
139 /*******************************************************************
140 Returns the size in bytes of the named given the stat struct.
141 ********************************************************************/
143 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
145 return sbuf->st_ex_size;
148 /****************************************************************************
149 Check two stats have identical dev and ino fields.
150 ****************************************************************************/
152 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
153 const SMB_STRUCT_STAT *sbuf2)
155 if (sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
156 sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
162 /****************************************************************************
163 Check if a stat struct is identical for use.
164 ****************************************************************************/
166 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
167 const SMB_STRUCT_STAT *sbuf2)
169 if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
170 sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
171 !check_same_dev_ino(sbuf1, sbuf2)) {
177 /*******************************************************************
178 Show a smb message structure.
179 ********************************************************************/
181 void show_msg(const char *buf)
189 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
191 (int)CVAL(buf,smb_com),
192 (int)CVAL(buf,smb_rcls),
193 (int)CVAL(buf,smb_reh),
194 (int)SVAL(buf,smb_err),
195 (int)CVAL(buf,smb_flg),
196 (int)SVAL(buf,smb_flg2)));
197 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
198 (int)SVAL(buf,smb_tid),
199 (int)SVAL(buf,smb_pid),
200 (int)SVAL(buf,smb_uid),
201 (int)SVAL(buf,smb_mid)));
202 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
204 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
205 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
206 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
208 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
210 DEBUGADD(5,("smb_bcc=%d\n",bcc));
218 dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
221 /*******************************************************************
222 Setup only the byte count for a smb message.
223 ********************************************************************/
225 int set_message_bcc(char *buf,int num_bytes)
227 int num_words = CVAL(buf,smb_wct);
228 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
229 _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
230 return (smb_size + num_words*2 + num_bytes);
233 /*******************************************************************
234 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
235 Return the bytes added
236 ********************************************************************/
238 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
240 size_t newlen = smb_len(*outbuf) + 4 + blob.length;
243 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
244 DEBUG(0, ("talloc failed\n"));
249 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
250 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
254 /*******************************************************************
255 Reduce a file name, removing .. elements.
256 ********************************************************************/
258 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
263 DEBUG(3,("dos_clean_name [%s]\n",s));
265 /* remove any double slashes */
266 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
271 /* Remove leading .\\ characters */
272 if(strncmp(str, ".\\", 2) == 0) {
273 trim_string(str, ".\\", NULL);
275 str = talloc_strdup(ctx, ".\\");
282 while ((p = strstr_m(str,"\\..\\")) != NULL) {
288 if ((p=strrchr_m(str,'\\')) != NULL) {
293 str = talloc_asprintf(ctx,
302 trim_string(str,NULL,"\\..");
303 return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
306 /*******************************************************************
307 Reduce a file name, removing .. elements.
308 ********************************************************************/
310 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
315 DEBUG(3,("unix_clean_name [%s]\n",s));
317 /* remove any double slashes */
318 str = talloc_all_string_sub(ctx, s, "//","/");
323 /* Remove leading ./ characters */
324 if(strncmp(str, "./", 2) == 0) {
325 trim_string(str, "./", NULL);
327 str = talloc_strdup(ctx, "./");
334 while ((p = strstr_m(str,"/../")) != NULL) {
340 if ((p=strrchr_m(str,'/')) != NULL) {
345 str = talloc_asprintf(ctx,
354 trim_string(str,NULL,"/..");
355 return talloc_all_string_sub(ctx, str, "/./", "/");
358 char *clean_name(TALLOC_CTX *ctx, const char *s)
360 char *str = dos_clean_name(ctx, s);
364 return unix_clean_name(ctx, str);
367 /*******************************************************************
368 Write data into an fd at a given offset. Ignore seek errors.
369 ********************************************************************/
371 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
376 if (pos == (off_t)-1) {
377 return write_data(fd, buffer, N);
379 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
381 ret = sys_pwrite(fd,buffer + total,N - total, pos);
382 if (ret == -1 && errno == ESPIPE) {
383 return write_data(fd, buffer + total,N - total);
386 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
395 return (ssize_t)total;
397 /* Use lseek and write_data. */
398 if (lseek(fd, pos, SEEK_SET) == -1) {
399 if (errno != ESPIPE) {
403 return write_data(fd, buffer, N);
407 static int reinit_after_fork_pipe[2] = { -1, -1 };
409 NTSTATUS init_before_fork(void)
413 ret = pipe(reinit_after_fork_pipe);
417 status = map_nt_error_from_unix_common(errno);
419 DEBUG(0, ("Error creating child_pipe: %s\n",
429 * Detect died parent by detecting EOF on the pipe
431 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
432 struct tevent_fd *fde,
438 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
440 * we have reached EOF on stdin, which means the
441 * parent has exited. Shutdown the server
444 (void)kill(getpid(), SIGTERM);
449 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
450 struct tevent_context *ev_ctx,
451 bool parent_longlived,
454 NTSTATUS status = NT_STATUS_OK;
458 * The main process thread should never
459 * allow per_thread_cwd_enable() to be
462 per_thread_cwd_disable();
464 if (reinit_after_fork_pipe[1] != -1) {
465 close(reinit_after_fork_pipe[1]);
466 reinit_after_fork_pipe[1] = -1;
469 /* tdb needs special fork handling */
470 if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
471 DEBUG(0,("tdb_reopen_all failed.\n"));
472 status = NT_STATUS_OPEN_FAILED;
476 if (ev_ctx != NULL) {
477 tevent_set_trace_callback(ev_ctx, NULL, NULL);
478 if (tevent_re_initialise(ev_ctx) != 0) {
479 smb_panic(__location__ ": Failed to re-initialise event context");
483 if (reinit_after_fork_pipe[0] != -1) {
484 struct tevent_fd *fde;
486 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
487 reinit_after_fork_pipe[0], TEVENT_FD_READ,
488 reinit_after_fork_pipe_handler, NULL);
490 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
496 * For clustering, we need to re-init our ctdbd connection after the
499 status = messaging_reinit(msg_ctx);
500 if (!NT_STATUS_IS_OK(status)) {
501 DEBUG(0,("messaging_reinit() failed: %s\n",
505 if (lp_clustering()) {
506 ret = ctdb_async_ctx_reinit(
507 NULL, messaging_tevent_context(msg_ctx));
509 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
511 return map_nt_error_from_unix(ret);
517 prctl_set_comment("%s", comment);
524 /****************************************************************************
525 (Hopefully) efficient array append.
526 ****************************************************************************/
528 void add_to_large_array(TALLOC_CTX *mem_ctx, size_t element_size,
529 void *element, void *_array, uint32_t *num_elements,
532 void **array = (void **)_array;
534 if (*array_size < 0) {
538 if (*array == NULL) {
539 if (*array_size == 0) {
543 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
547 *array = TALLOC(mem_ctx, element_size * (*array_size));
548 if (*array == NULL) {
553 if (*num_elements == *array_size) {
556 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
560 *array = TALLOC_REALLOC(mem_ctx, *array,
561 element_size * (*array_size));
563 if (*array == NULL) {
568 memcpy((char *)(*array) + element_size*(*num_elements),
569 element, element_size);
579 /****************************************************************************
580 Get my own domain name, or "" if we have none.
581 ****************************************************************************/
583 char *get_mydnsdomname(TALLOC_CTX *ctx)
588 domname = get_mydnsfullname();
593 p = strchr_m(domname, '.');
596 return talloc_strdup(ctx, p);
598 return talloc_strdup(ctx, "");
602 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
603 /******************************************************************
604 Remove any mount options such as -rsize=2048,wsize=2048 etc.
605 Based on a fix from <Thomas.Hepper@icem.de>.
606 Returns a malloc'ed string.
607 *******************************************************************/
609 static char *strip_mount_options(TALLOC_CTX *ctx, const char *str)
613 while(*p && !isspace(*p))
615 while(*p && isspace(*p))
618 return talloc_strdup(ctx, p);
624 /*******************************************************************
625 Patch from jkf@soton.ac.uk
626 Split Luke's automount_server into YP lookup and string splitter
627 so can easily implement automount_path().
628 Returns a malloc'ed string.
629 *******************************************************************/
631 #ifdef WITH_NISPLUS_HOME
632 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
634 const struct loadparm_substitution *lp_sub =
635 loadparm_s3_global_substitution();
638 char *nis_map = (char *)lp_homedir_map(talloc_tos(), lp_sub);
640 char buffer[NIS_MAXATTRVAL + 1];
645 snprintf(buffer, sizeof(buffer), "[key=%s],%s", user_name, nis_map);
646 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
648 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
649 if (result->status != NIS_SUCCESS) {
650 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
652 object = result->objects.objects_val;
653 if (object->zo_data.zo_type == ENTRY_OBJ) {
654 entry = &object->zo_data.objdata_u.en_data;
655 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
656 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
658 value = talloc_strdup(ctx,
659 entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
661 nis_freeresult(result);
664 value = talloc_string_sub(ctx,
671 nis_freeresult(result);
674 value = strip_mount_options(ctx, value);
675 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
680 #else /* WITH_NISPLUS_HOME */
682 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
684 const struct loadparm_substitution *lp_sub =
685 loadparm_s3_global_substitution();
688 int nis_error; /* returned by yp all functions */
689 char *nis_result; /* yp_match inits this */
690 int nis_result_len; /* and set this */
691 char *nis_domain; /* yp_get_default_domain inits this */
692 char *nis_map = lp_homedir_map(talloc_tos(), lp_sub);
694 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
695 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
699 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
701 if ((nis_error = yp_match(nis_domain, nis_map, user_name,
702 strlen(user_name), &nis_result,
703 &nis_result_len)) == 0) {
704 if (nis_result_len > 0 && nis_result[nis_result_len] == '\n') {
705 nis_result[nis_result_len] = '\0';
707 value = talloc_strdup(ctx, nis_result);
711 value = strip_mount_options(ctx, value);
712 } else if(nis_error == YPERR_KEY) {
713 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
714 user_name, nis_map));
715 DEBUG(3, ("using defaults for server and home directory\n"));
717 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
718 yperr_string(nis_error), user_name, nis_map));
722 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, value));
726 #endif /* WITH_NISPLUS_HOME */
729 bool process_exists(const struct server_id pid)
731 return serverid_exists(&pid);
734 /*******************************************************************
735 Convert a uid into a user name.
736 ********************************************************************/
738 const char *uidtoname(uid_t uid)
740 TALLOC_CTX *ctx = talloc_tos();
742 struct passwd *pass = NULL;
744 pass = getpwuid_alloc(ctx,uid);
746 name = talloc_strdup(ctx,pass->pw_name);
749 name = talloc_asprintf(ctx,
756 /*******************************************************************
757 Convert a gid into a group name.
758 ********************************************************************/
760 char *gidtoname(gid_t gid)
766 return talloc_strdup(talloc_tos(), grp->gr_name);
769 return talloc_asprintf(talloc_tos(),
775 /*******************************************************************
776 Convert a user name into a uid.
777 ********************************************************************/
779 uid_t nametouid(const char *name)
785 pass = Get_Pwnam_alloc(talloc_tos(), name);
792 u = (uid_t)strtol(name, &p, 0);
793 if ((p != name) && (*p == '\0'))
799 /*******************************************************************
800 Convert a name to a gid_t if possible. Return -1 if not a group.
801 ********************************************************************/
803 gid_t nametogid(const char *name)
809 g = (gid_t)strtol(name, &p, 0);
810 if ((p != name) && (*p == '\0'))
813 grp = getgrnam(name);
819 /*******************************************************************
820 Something really nasty happened - panic !
821 ********************************************************************/
823 void smb_panic_s3(const char *why)
825 const struct loadparm_substitution *lp_sub =
826 loadparm_s3_global_substitution();
830 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
832 * Make sure all children can attach a debugger.
834 prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
837 cmd = lp_panic_action(talloc_tos(), lp_sub);
839 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
840 result = system(cmd);
843 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
846 DEBUG(0, ("smb_panic(): action returned status %d\n",
847 WEXITSTATUS(result)));
853 /*******************************************************************
854 A readdir wrapper which just returns the file name.
855 ********************************************************************/
857 const char *readdirname(DIR *p)
865 ptr = (struct dirent *)readdir(p);
871 return talloc_strdup(talloc_tos(), dname);
874 /*******************************************************************
875 Utility function used to decide if the last component
876 of a path matches a (possibly wildcarded) entry in a namelist.
877 ********************************************************************/
879 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
881 const char *last_component;
883 /* if we have no list it's obviously not in the path */
884 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
888 DEBUG(8, ("is_in_path: %s\n", name));
890 /* Get the last component of the unix name. */
891 last_component = strrchr_m(name, '/');
892 if (!last_component) {
893 last_component = name;
895 last_component++; /* Go past '/' */
898 for(; namelist->name != NULL; namelist++) {
899 if(namelist->is_wild) {
900 if (mask_match(last_component, namelist->name, case_sensitive)) {
901 DEBUG(8,("is_in_path: mask match succeeded\n"));
905 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
906 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
907 DEBUG(8,("is_in_path: match succeeded\n"));
912 DEBUG(8,("is_in_path: match not found\n"));
916 /*******************************************************************
917 Strip a '/' separated list into an array of
918 name_compare_enties structures suitable for
919 passing to is_in_path(). We do this for
920 speed so we can pre-parse all the names in the list
921 and don't do it for each call to is_in_path().
922 We also check if the entry contains a wildcard to
923 remove a potentially expensive call to mask_match
925 ********************************************************************/
927 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
936 (*ppname_array) = NULL;
938 if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
941 namelist = talloc_strdup(talloc_tos(), namelist_in);
942 if (namelist == NULL) {
943 DEBUG(0,("set_namearray: talloc fail\n"));
948 namelist_end = &namelist[strlen(namelist)];
950 /* We need to make two passes over the string. The
951 first to count the number of elements, the second
955 while(nameptr <= namelist_end) {
956 if ( *nameptr == '/' ) {
957 /* cope with multiple (useless) /s) */
962 if ( *nameptr == '\0' )
965 /* find the next '/' or consume remaining */
966 name_end = strchr_m(nameptr, '/');
967 if (name_end == NULL) {
968 /* Point nameptr at the terminating '\0' */
969 nameptr += strlen(nameptr);
971 /* next segment please */
972 nameptr = name_end + 1;
977 if(num_entries == 0) {
978 talloc_free(namelist);
982 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
983 DEBUG(0,("set_namearray: malloc fail\n"));
984 talloc_free(namelist);
988 /* Now copy out the names */
991 while(nameptr <= namelist_end) {
992 if ( *nameptr == '/' ) {
993 /* cope with multiple (useless) /s) */
998 if ( *nameptr == '\0' )
1001 /* find the next '/' or consume remaining */
1002 name_end = strchr_m(nameptr, '/');
1003 if (name_end != NULL) {
1007 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1008 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1009 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1010 talloc_free(namelist);
1014 if (name_end == NULL) {
1015 /* Point nameptr at the terminating '\0' */
1016 nameptr += strlen(nameptr);
1018 /* next segment please */
1019 nameptr = name_end + 1;
1024 (*ppname_array)[i].name = NULL;
1026 talloc_free(namelist);
1031 #define DBGC_CLASS DBGC_LOCKING
1033 /****************************************************************************
1034 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1035 is dealt with in posix.c
1036 Returns True if we have information regarding this lock region (and returns
1037 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1038 ****************************************************************************/
1040 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
1045 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1046 fd,op,(double)*poffset,(double)*pcount,*ptype));
1048 lock.l_type = *ptype;
1049 lock.l_whence = SEEK_SET;
1050 lock.l_start = *poffset;
1051 lock.l_len = *pcount;
1054 ret = sys_fcntl_ptr(fd,op,&lock);
1058 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1059 (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
1064 *ptype = lock.l_type;
1065 *poffset = lock.l_start;
1066 *pcount = lock.l_len;
1069 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1070 fd, (int)lock.l_type, (unsigned int)lock.l_pid));
1074 #if defined(HAVE_OFD_LOCKS)
1075 int map_process_lock_to_ofd_lock(int op)
1095 #else /* HAVE_OFD_LOCKS */
1096 int map_process_lock_to_ofd_lock(int op)
1100 #endif /* HAVE_OFD_LOCKS */
1103 #define DBGC_CLASS DBGC_ALL
1105 /*******************************************************************
1106 Is the name specified one of my netbios names.
1107 Returns true if it is equal, false otherwise.
1108 ********************************************************************/
1110 bool is_myname(const char *s)
1115 for (n=0; my_netbios_names(n); n++) {
1116 const char *nbt_name = my_netbios_names(n);
1118 if (strncasecmp_m(nbt_name, s, MAX_NETBIOSNAME_LEN-1) == 0) {
1123 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1127 /*******************************************************************
1128 we distinguish between 2K and XP by the "Native Lan Manager" string
1129 WinXP => "Windows 2002 5.1"
1130 WinXP 64bit => "Windows XP 5.2"
1131 Win2k => "Windows 2000 5.0"
1132 NT4 => "Windows NT 4.0"
1133 Win9x => "Windows 4.0"
1134 Windows 2003 doesn't set the native lan manager string but
1135 they do set the domain to "Windows 2003 5.2" (probably a bug).
1136 ********************************************************************/
1138 void ra_lanman_string( const char *native_lanman )
1140 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1141 set_remote_arch( RA_WINXP );
1142 else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1143 set_remote_arch( RA_WINXP64 );
1144 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1145 set_remote_arch( RA_WIN2K3 );
1148 static const char *remote_arch_strings[] = {
1149 [RA_UNKNOWN] = "UNKNOWN",
1152 [RA_WIN95] = "Win95",
1153 [RA_WINNT] = "WinNT",
1154 [RA_WIN2K] = "Win2K",
1155 [RA_WINXP] = "WinXP",
1156 [RA_WIN2K3] = "Win2K3",
1157 [RA_VISTA] = "Vista",
1158 [RA_SAMBA] = "Samba",
1159 [RA_CIFSFS] = "CIFSFS",
1160 [RA_WINXP64] = "WinXP64",
1164 const char *get_remote_arch_str(void)
1166 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1168 * set_remote_arch() already checks this so ra_type
1169 * should be in the allowed range, but anyway, let's
1170 * do another bound check here.
1172 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1173 ra_type = RA_UNKNOWN;
1175 return remote_arch_strings[ra_type];
1178 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1182 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1183 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1190 /*******************************************************************
1191 Set the horrid remote_arch string based on an enum.
1192 ********************************************************************/
1194 void set_remote_arch(enum remote_arch_types type)
1196 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1198 * This protects against someone adding values to enum
1199 * remote_arch_types without updating
1200 * remote_arch_strings array.
1202 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1203 ra_type = RA_UNKNOWN;
1208 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1209 get_remote_arch_str()));
1212 /*******************************************************************
1213 Get the remote_arch type.
1214 ********************************************************************/
1216 enum remote_arch_types get_remote_arch(void)
1221 #define RA_CACHE_TTL 7*24*3600
1223 static bool remote_arch_cache_key(const struct GUID *client_guid,
1226 struct GUID_txt_buf guid_buf;
1227 const char *guid_string = NULL;
1229 guid_string = GUID_buf_string(client_guid, &guid_buf);
1230 if (guid_string == NULL) {
1234 fstr_sprintf(key, "RA/%s", guid_string);
1238 struct ra_parser_state {
1240 enum remote_arch_types ra;
1243 static void ra_parser(const struct gencache_timeout *t,
1247 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1248 const char *ra_str = NULL;
1250 if (gencache_timeout_expired(t)) {
1254 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1255 DBG_ERR("Remote arch cache key not a string\n");
1259 ra_str = (const char *)blob.data;
1260 DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1262 state->ra = get_remote_arch_from_str(ra_str);
1263 state->found = true;
1267 static bool remote_arch_cache_get(const struct GUID *client_guid)
1271 struct ra_parser_state state = (struct ra_parser_state) {
1276 ok = remote_arch_cache_key(client_guid, ra_key);
1281 ok = gencache_parse(ra_key, ra_parser, &state);
1282 if (!ok || !state.found) {
1286 if (state.ra == RA_UNKNOWN) {
1290 set_remote_arch(state.ra);
1294 static bool remote_arch_cache_set(const struct GUID *client_guid)
1298 const char *ra_str = NULL;
1300 if (get_remote_arch() == RA_UNKNOWN) {
1304 ok = remote_arch_cache_key(client_guid, ra_key);
1309 ra_str = get_remote_arch_str();
1310 if (ra_str == NULL) {
1314 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1322 bool remote_arch_cache_update(const struct GUID *client_guid)
1326 if (get_remote_arch() == RA_UNKNOWN) {
1329 ok = remote_arch_cache_get(client_guid);
1336 ok = remote_arch_cache_set(client_guid);
1342 bool remote_arch_cache_delete(const struct GUID *client_guid)
1347 ok = remote_arch_cache_key(client_guid, ra_key);
1353 ok = gencache_del(ra_key);
1363 const char *tab_depth(int level, int depth)
1365 if( CHECK_DEBUGLVL(level) ) {
1366 dbgtext("%*s", depth*4, "");
1371 /*****************************************************************************
1372 Provide a checksum on a string
1374 Input: s - the null-terminated character string for which the checksum
1377 Output: The checksum value calculated for s.
1378 *****************************************************************************/
1380 int str_checksum(const char *s)
1386 key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1387 .dsize = strlen(s) };
1389 return tdb_jenkins_hash(&key);
1392 /*****************************************************************
1393 Zero a memory area then free it. Used to catch bugs faster.
1394 *****************************************************************/
1396 void zero_free(void *p, size_t size)
1402 /*****************************************************************
1403 Set our open file limit to a requested max and return the limit.
1404 *****************************************************************/
1406 int set_maxfiles(int requested_max)
1408 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1410 int saved_current_limit;
1412 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1413 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1416 return requested_max;
1420 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1421 * account for the extra fd we need
1422 * as well as the log files and standard
1423 * handles etc. Save the limit we want to set in case
1424 * we are running on an OS that doesn't support this limit (AIX)
1425 * which always returns RLIM_INFINITY for rlp.rlim_max.
1428 /* Try raising the hard (max) limit to the requested amount. */
1430 #if defined(RLIM_INFINITY)
1431 if (rlp.rlim_max != RLIM_INFINITY) {
1432 int orig_max = rlp.rlim_max;
1434 if ( rlp.rlim_max < requested_max )
1435 rlp.rlim_max = requested_max;
1437 /* This failing is not an error - many systems (Linux) don't
1438 support our default request of 10,000 open files. JRA. */
1440 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1441 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1442 (int)rlp.rlim_max, strerror(errno) ));
1444 /* Set failed - restore original value from get. */
1445 rlp.rlim_max = orig_max;
1450 /* Now try setting the soft (current) limit. */
1452 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1454 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1455 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1456 (int)rlp.rlim_cur, strerror(errno) ));
1458 return saved_current_limit;
1461 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1462 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1465 return saved_current_limit;
1468 #if defined(RLIM_INFINITY)
1469 if(rlp.rlim_cur == RLIM_INFINITY)
1470 return saved_current_limit;
1473 if((int)rlp.rlim_cur > saved_current_limit)
1474 return saved_current_limit;
1476 return rlp.rlim_cur;
1477 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1479 * No way to know - just guess...
1481 return requested_max;
1485 /*****************************************************************
1486 malloc that aborts with smb_panic on fail or zero size.
1487 *****************************************************************/
1489 void *smb_xmalloc_array(size_t size, unsigned int count)
1493 smb_panic("smb_xmalloc_array: called with zero size");
1495 if (count >= MAX_ALLOC_SIZE/size) {
1496 smb_panic("smb_xmalloc_array: alloc size too large");
1498 if ((p = SMB_MALLOC(size*count)) == NULL) {
1499 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1500 (unsigned long)size, (unsigned long)count));
1501 smb_panic("smb_xmalloc_array: malloc failed");
1506 /*****************************************************************
1507 Get local hostname and cache result.
1508 *****************************************************************/
1510 char *myhostname(void)
1514 ret = get_myname(NULL);
1519 /*****************************************************************
1520 Get local hostname and cache result.
1521 *****************************************************************/
1523 char *myhostname_upper(void)
1527 char *name = get_myname(NULL);
1531 ret = strupper_talloc(NULL, name);
1537 /*******************************************************************
1538 Given a filename - get its directory name
1539 ********************************************************************/
1541 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1547 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1550 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1561 if (!(*parent = (char *)talloc_memdup(mem_ctx, dir, len+1))) {
1564 (*parent)[len] = '\0';
1572 /*******************************************************************
1573 Determine if a pattern contains any Microsoft wildcard characters.
1574 *******************************************************************/
1576 bool ms_has_wild(const char *s)
1580 while ((c = *s++)) {
1593 bool ms_has_wild_w(const smb_ucs2_t *s)
1596 if (!s) return False;
1597 while ((c = *s++)) {
1599 case UCS2_CHAR('*'):
1600 case UCS2_CHAR('?'):
1601 case UCS2_CHAR('<'):
1602 case UCS2_CHAR('>'):
1603 case UCS2_CHAR('"'):
1610 /*******************************************************************
1611 A wrapper that handles case sensitivity and the special handling
1613 *******************************************************************/
1615 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1617 if (ISDOTDOT(string))
1622 return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1625 /*******************************************************************
1626 A wrapper that handles case sensitivity and the special handling
1627 of the ".." name. Varient that is only called by old search code which requires
1628 pattern translation.
1629 *******************************************************************/
1631 bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
1633 if (ISDOTDOT(string))
1638 return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
1641 /*******************************************************************
1642 A wrapper that handles a list of patters and calls mask_match()
1643 on each. Returns True if any of the patterns match.
1644 *******************************************************************/
1646 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1648 while (listLen-- > 0) {
1649 if (mask_match(string, *list++, is_case_sensitive))
1655 /**********************************************************************
1656 Converts a name to a fully qualified domain name.
1657 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1658 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1659 canonical name of the host. getaddrinfo() may use a variety of sources
1660 including /etc/hosts to obtain the domainname. It expects aliases in
1661 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1662 ************************************************************************/
1664 bool name_to_fqdn(fstring fqdn, const char *name)
1667 struct addrinfo hints;
1668 struct addrinfo *result;
1671 /* Configure hints to obtain canonical name */
1673 memset(&hints, 0, sizeof(struct addrinfo));
1674 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1675 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1676 hints.ai_flags = AI_CANONNAME; /* Get host's FQDN */
1677 hints.ai_protocol = 0; /* Any protocol */
1679 s = getaddrinfo(name, NULL, &hints, &result);
1681 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s)));
1682 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
1683 fstrcpy(fqdn, name);
1686 full = result->ai_canonname;
1688 /* Find out if the FQDN is returned as an alias
1689 * to cope with /etc/hosts files where the first
1690 * name is not the FQDN but the short name.
1691 * getaddrinfo provides no easy way of handling aliases
1692 * in /etc/hosts. Users should make sure the FQDN
1693 * comes first in /etc/hosts. */
1694 if (full && (! strchr_m(full, '.'))) {
1695 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1696 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1697 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1698 DEBUGADD(1, (" prior to any aliases.\n"));
1700 if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1701 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1702 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1703 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1704 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1707 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1708 fstrcpy(fqdn, full);
1709 freeaddrinfo(result); /* No longer needed */
1713 uint32_t map_share_mode_to_deny_mode(uint32_t share_access, uint32_t private_options)
1715 switch (share_access & ~FILE_SHARE_DELETE) {
1716 case FILE_SHARE_NONE:
1718 case FILE_SHARE_READ:
1720 case FILE_SHARE_WRITE:
1722 case FILE_SHARE_READ|FILE_SHARE_WRITE:
1725 if (private_options & NTCREATEX_FLAG_DENY_DOS) {
1727 } else if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_FCB) {
1731 return (uint32_t)-1;
1734 struct server_id interpret_pid(const char *pid_string)
1736 return server_id_from_string(get_my_vnn(), pid_string);
1739 /****************************************************************
1740 Check if an offset into a buffer is safe.
1741 If this returns True it's safe to indirect into the byte at
1743 ****************************************************************/
1745 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1747 const char *end_base = buf_base + buf_len;
1748 char *end_ptr = ptr + off;
1750 if (!buf_base || !ptr) {
1754 if (end_base < buf_base || end_ptr < ptr) {
1755 return False; /* wrap. */
1758 if (end_ptr < end_base) {
1764 /****************************************************************
1765 Return a safe pointer into a buffer, or NULL.
1766 ****************************************************************/
1768 char *get_safe_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1770 return is_offset_safe(buf_base, buf_len, ptr, off) ?
1774 /****************************************************************
1775 Return a safe pointer into a string within a buffer, or NULL.
1776 ****************************************************************/
1778 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1780 if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1783 /* Check if a valid string exists at this offset. */
1784 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1790 /****************************************************************
1791 Return an SVAL at a pointer, or failval if beyond the end.
1792 ****************************************************************/
1794 int get_safe_SVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1797 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1800 if (!is_offset_safe(buf_base, buf_len, ptr, off+1)) {
1803 return SVAL(ptr,off);
1806 /****************************************************************
1807 Return an IVAL at a pointer, or failval if beyond the end.
1808 ****************************************************************/
1810 int get_safe_IVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1813 * Note we use off+3 here, not off+4 as IVAL accesses
1814 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1816 if (!is_offset_safe(buf_base, buf_len, ptr, off+3)) {
1819 return IVAL(ptr,off);
1822 /****************************************************************
1823 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1824 call (they take care of winbind separator and other winbind specific settings).
1825 ****************************************************************/
1827 bool split_domain_user(TALLOC_CTX *mem_ctx,
1828 const char *full_name,
1832 const char *p = NULL;
1834 p = strchr_m(full_name, '\\');
1837 *domain = talloc_strndup(mem_ctx, full_name,
1838 PTR_DIFF(p, full_name));
1839 if (*domain == NULL) {
1842 *user = talloc_strdup(mem_ctx, p+1);
1843 if (*user == NULL) {
1844 TALLOC_FREE(*domain);
1849 *user = talloc_strdup(mem_ctx, full_name);
1850 if (*user == NULL) {
1858 /****************************************************************
1859 strip off leading '\\' from a hostname
1860 ****************************************************************/
1862 const char *strip_hostname(const char *s)
1868 if (strlen_m(s) < 3) {
1872 if (s[0] == '\\') s++;
1873 if (s[0] == '\\') s++;
1878 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1880 if (!NT_STATUS_IS_OK(err1)) {
1884 if (!NT_STATUS_IS_OK(err2)) {
1891 int timeval_to_msec(struct timeval t)
1893 return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1896 /*******************************************************************
1897 Check a given DOS pathname is valid for a share.
1898 ********************************************************************/
1900 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1904 if (!dos_pathname) {
1908 ptr = talloc_strdup(ctx, dos_pathname);
1912 /* Convert any '\' paths to '/' */
1914 ptr = unix_clean_name(ctx, ptr);
1919 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1920 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1923 /* Only absolute paths allowed. */
1930 /*******************************************************************
1931 Return True if the filename is one of the special executable types.
1932 ********************************************************************/
1934 bool is_executable(const char *fname)
1936 if ((fname = strrchr_m(fname,'.'))) {
1937 if (strequal(fname,".com") ||
1938 strequal(fname,".dll") ||
1939 strequal(fname,".exe") ||
1940 strequal(fname,".sym")) {
1947 /****************************************************************************
1948 Open a file with a share mode - old openX method - map into NTCreate.
1949 ****************************************************************************/
1951 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1952 int deny_mode, int open_func,
1953 uint32_t *paccess_mask,
1954 uint32_t *pshare_mode,
1955 uint32_t *pcreate_disposition,
1956 uint32_t *pcreate_options,
1957 uint32_t *pprivate_flags)
1959 uint32_t access_mask;
1960 uint32_t share_mode;
1961 uint32_t create_disposition;
1962 uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1963 uint32_t private_flags = 0;
1965 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1966 "open_func = 0x%x\n",
1967 smb_base_fname, (unsigned int)deny_mode,
1968 (unsigned int)open_func ));
1970 /* Create the NT compatible access_mask. */
1971 switch (GET_OPENX_MODE(deny_mode)) {
1972 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1973 case DOS_OPEN_RDONLY:
1974 access_mask = FILE_GENERIC_READ;
1976 case DOS_OPEN_WRONLY:
1977 access_mask = FILE_GENERIC_WRITE;
1981 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1984 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1985 (unsigned int)GET_OPENX_MODE(deny_mode)));
1989 /* Create the NT compatible create_disposition. */
1990 switch (open_func) {
1991 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
1992 create_disposition = FILE_CREATE;
1995 case OPENX_FILE_EXISTS_OPEN:
1996 create_disposition = FILE_OPEN;
1999 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
2000 create_disposition = FILE_OPEN_IF;
2003 case OPENX_FILE_EXISTS_TRUNCATE:
2004 create_disposition = FILE_OVERWRITE;
2007 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
2008 create_disposition = FILE_OVERWRITE_IF;
2012 /* From samba4 - to be confirmed. */
2013 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
2014 create_disposition = FILE_CREATE;
2017 DEBUG(10,("map_open_params_to_ntcreate: bad "
2018 "open_func 0x%x\n", (unsigned int)open_func));
2022 /* Create the NT compatible share modes. */
2023 switch (GET_DENY_MODE(deny_mode)) {
2025 share_mode = FILE_SHARE_NONE;
2029 share_mode = FILE_SHARE_READ;
2033 share_mode = FILE_SHARE_WRITE;
2037 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2041 private_flags |= NTCREATEX_FLAG_DENY_DOS;
2042 if (is_executable(smb_base_fname)) {
2043 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2045 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
2046 share_mode = FILE_SHARE_READ;
2048 share_mode = FILE_SHARE_NONE;
2054 private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
2055 share_mode = FILE_SHARE_NONE;
2059 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2060 (unsigned int)GET_DENY_MODE(deny_mode) ));
2064 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2065 "share_mode = 0x%x, create_disposition = 0x%x, "
2066 "create_options = 0x%x private_flags = 0x%x\n",
2068 (unsigned int)access_mask,
2069 (unsigned int)share_mode,
2070 (unsigned int)create_disposition,
2071 (unsigned int)create_options,
2072 (unsigned int)private_flags));
2075 *paccess_mask = access_mask;
2078 *pshare_mode = share_mode;
2080 if (pcreate_disposition) {
2081 *pcreate_disposition = create_disposition;
2083 if (pcreate_options) {
2084 *pcreate_options = create_options;
2086 if (pprivate_flags) {
2087 *pprivate_flags = private_flags;
2094 /*************************************************************************
2095 Return a talloced copy of a struct security_unix_token. NULL on fail.
2096 *************************************************************************/
2098 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
2100 struct security_unix_token *cpy;
2102 cpy = talloc(ctx, struct security_unix_token);
2107 cpy->uid = tok->uid;
2108 cpy->gid = tok->gid;
2109 cpy->ngroups = tok->ngroups;
2111 /* Make this a talloc child of cpy. */
2112 cpy->groups = (gid_t *)talloc_memdup(
2113 cpy, tok->groups, tok->ngroups * sizeof(gid_t));
2124 /****************************************************************************
2126 ****************************************************************************/
2128 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
2130 struct security_unix_token *t = NULL;
2132 t = talloc_zero(mem_ctx, struct security_unix_token);
2138 * This is not needed, but lets make it explicit, not implicit.
2140 *t = (struct security_unix_token) {
2150 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
2155 str = talloc_asprintf(
2157 "uid=%ju, gid=%ju, %"PRIu32" groups:",
2158 (uintmax_t)(tok->uid),
2159 (uintmax_t)(tok->gid),
2165 for (i=0; i<tok->ngroups; i++) {
2167 tmp = talloc_asprintf_append_buffer(
2168 str, " %ju", (uintmax_t)tok->groups[i]);
2179 /****************************************************************************
2180 Check that a file matches a particular file type.
2181 ****************************************************************************/
2183 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
2187 /* Check the "may have" search bits. */
2188 if (((mode & ~dirtype) &
2189 (FILE_ATTRIBUTE_HIDDEN |
2190 FILE_ATTRIBUTE_SYSTEM |
2191 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
2195 /* Check the "must have" bits,
2196 which are the may have bits shifted eight */
2197 /* If must have bit is set, the file/dir can
2198 not be returned in search unless the matching
2199 file attribute is set */
2200 mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
2201 FILE_ATTRIBUTE_ARCHIVE|
2202 FILE_ATTRIBUTE_READONLY|
2203 FILE_ATTRIBUTE_HIDDEN|
2204 FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
2206 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
2207 FILE_ATTRIBUTE_ARCHIVE|
2208 FILE_ATTRIBUTE_READONLY|
2209 FILE_ATTRIBUTE_HIDDEN|
2210 FILE_ATTRIBUTE_SYSTEM))) == mask) {
2211 /* check if matching attribute present */