s3:registry: Initialize struct security_ace ace[]
[samba4-gss.git] / source3 / lib / util.c
blob0deda2394f431c75197c45dcc5f99451263355e2
1 /*
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/>.
24 /**
25 * @brief Small functions that don't fit anywhere else
26 * @file util.c
29 #include "includes.h"
30 #include "system/passwd.h"
31 #include "system/filesys.h"
32 #include "lib/util/server_id.h"
33 #include "lib/util/memcache.h"
34 #include "util_tdb.h"
35 #include "ctdbd_conn.h"
36 #include "../lib/util/util_pw.h"
37 #include "messages.h"
38 #include "lib/messaging/messages_dgm.h"
39 #include "libcli/security/security.h"
40 #include "serverid.h"
41 #include "lib/util/sys_rw.h"
42 #include "lib/util/sys_rw_data.h"
43 #include "lib/util/util_process.h"
44 #include "lib/dbwrap/dbwrap_ctdb.h"
45 #include "lib/gencache.h"
46 #include "lib/util/string_wrappers.h"
48 #ifdef HAVE_SYS_PRCTL_H
49 #include <sys/prctl.h>
50 #endif
52 /* Max allowable allococation - 256mb - 0x10000000 */
53 #define MAX_ALLOC_SIZE (1024*1024*256)
55 static enum protocol_types Protocol = PROTOCOL_COREPLUS;
57 void set_Protocol(enum protocol_types p)
59 Protocol = p;
62 static enum remote_arch_types ra_type = RA_UNKNOWN;
64 void gfree_all( void )
66 gfree_loadparm();
67 gfree_charcnv();
68 gfree_interfaces();
69 gfree_debugsyms();
70 gfree_memcache();
74 /*******************************************************************
75 Check if a file exists - call vfs_file_exist for samba files.
76 ********************************************************************/
78 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
79 bool fake_dir_create_times)
81 SMB_STRUCT_STAT st;
82 if (!sbuf)
83 sbuf = &st;
85 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
86 return(False);
88 return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
91 /*******************************************************************
92 Check if a unix domain socket exists - call vfs_file_exist for samba files.
93 ********************************************************************/
95 bool socket_exist(const char *fname)
97 SMB_STRUCT_STAT st;
98 if (sys_stat(fname, &st, false) != 0)
99 return(False);
101 return S_ISSOCK(st.st_ex_mode);
104 /*******************************************************************
105 Returns the size in bytes of the named given the stat struct.
106 ********************************************************************/
108 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
110 return sbuf->st_ex_size;
113 /****************************************************************************
114 Check two stats have identical dev and ino fields.
115 ****************************************************************************/
117 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
118 const SMB_STRUCT_STAT *sbuf2)
120 return ((sbuf1->st_ex_dev == sbuf2->st_ex_dev) &&
121 (sbuf1->st_ex_ino == sbuf2->st_ex_ino));
124 /****************************************************************************
125 Check if a stat struct is identical for use.
126 ****************************************************************************/
128 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
129 const SMB_STRUCT_STAT *sbuf2)
131 return ((sbuf1->st_ex_uid == sbuf2->st_ex_uid) &&
132 (sbuf1->st_ex_gid == sbuf2->st_ex_gid) &&
133 check_same_dev_ino(sbuf1, sbuf2));
136 /*******************************************************************
137 Show a smb message structure.
138 ********************************************************************/
140 void show_msg(const char *buf)
142 int i;
143 int bcc=0;
145 if (!DEBUGLVL(5))
146 return;
148 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
149 smb_len(buf),
150 (int)CVAL(buf,smb_com),
151 (int)CVAL(buf,smb_rcls),
152 (int)CVAL(buf,smb_reh),
153 (int)SVAL(buf,smb_err),
154 (int)CVAL(buf,smb_flg),
155 (int)SVAL(buf,smb_flg2)));
156 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
157 (int)SVAL(buf,smb_tid),
158 (int)SVAL(buf,smb_pid),
159 (int)SVAL(buf,smb_uid),
160 (int)SVAL(buf,smb_mid)));
161 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
163 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
164 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
165 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
167 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
169 DEBUGADD(5,("smb_bcc=%d\n",bcc));
171 if (DEBUGLEVEL < 10)
172 return;
174 if (DEBUGLEVEL < 50)
175 bcc = MIN(bcc, 512);
177 dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
180 /*******************************************************************
181 Setup only the byte count for a smb message.
182 ********************************************************************/
184 int set_message_bcc(char *buf,int num_bytes)
186 int num_words = CVAL(buf,smb_wct);
187 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
188 _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
189 return (smb_size + num_words*2 + num_bytes);
192 /*******************************************************************
193 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
194 Return the bytes added
195 ********************************************************************/
197 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
199 size_t newlen = smb_len(*outbuf) + 4 + blob.length;
200 uint8_t *tmp;
202 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
203 DEBUG(0, ("talloc failed\n"));
204 return -1;
206 *outbuf = tmp;
208 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
209 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
210 return blob.length;
213 /*******************************************************************
214 Reduce a file name, removing .. elements.
215 ********************************************************************/
217 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
219 char *p = NULL;
220 char *str = NULL;
222 DEBUG(3,("dos_clean_name [%s]\n",s));
224 /* remove any double slashes */
225 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
226 if (!str) {
227 return NULL;
230 /* Remove leading .\\ characters */
231 if(strncmp(str, ".\\", 2) == 0) {
232 trim_string(str, ".\\", NULL);
233 if(*str == 0) {
234 str = talloc_strdup(ctx, ".\\");
235 if (!str) {
236 return NULL;
241 while ((p = strstr_m(str,"\\..\\")) != NULL) {
242 char *s1;
244 *p = 0;
245 s1 = p+3;
247 if ((p=strrchr_m(str,'\\')) != NULL) {
248 *p = 0;
249 } else {
250 *str = 0;
252 str = talloc_asprintf(ctx,
253 "%s%s",
254 str,
255 s1);
256 if (!str) {
257 return NULL;
261 trim_string(str,NULL,"\\..");
262 return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
265 /*******************************************************************
266 Reduce a file name, removing .. elements.
267 ********************************************************************/
269 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
271 char *p = NULL;
272 char *str = NULL;
274 DEBUG(3,("unix_clean_name [%s]\n",s));
276 /* remove any double slashes */
277 str = talloc_all_string_sub(ctx, s, "//","/");
278 if (!str) {
279 return NULL;
282 /* Remove leading ./ characters */
283 if(strncmp(str, "./", 2) == 0) {
284 trim_string(str, "./", NULL);
285 if(*str == 0) {
286 str = talloc_strdup(ctx, "./");
287 if (!str) {
288 return NULL;
293 while ((p = strstr_m(str,"/../")) != NULL) {
294 char *s1;
296 *p = 0;
297 s1 = p+3;
299 if ((p=strrchr_m(str,'/')) != NULL) {
300 *p = 0;
301 } else {
302 *str = 0;
304 str = talloc_asprintf(ctx,
305 "%s%s",
306 str,
307 s1);
308 if (!str) {
309 return NULL;
313 trim_string(str,NULL,"/..");
314 return talloc_all_string_sub(ctx, str, "/./", "/");
317 char *clean_name(TALLOC_CTX *ctx, const char *s)
319 char *str = dos_clean_name(ctx, s);
320 if (!str) {
321 return NULL;
323 return unix_clean_name(ctx, str);
326 /*******************************************************************
327 Write data into an fd at a given offset. Ignore seek errors.
328 ********************************************************************/
330 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
332 size_t total=0;
333 ssize_t ret;
335 if (pos == (off_t)-1) {
336 return write_data(fd, buffer, N);
338 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
339 while (total < N) {
340 ret = sys_pwrite(fd,buffer + total,N - total, pos);
341 if (ret == -1 && errno == ESPIPE) {
342 return write_data(fd, buffer + total,N - total);
344 if (ret == -1) {
345 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
346 return -1;
348 if (ret == 0) {
349 return total;
351 total += ret;
352 pos += ret;
354 return (ssize_t)total;
355 #else
356 /* Use lseek and write_data. */
357 if (lseek(fd, pos, SEEK_SET) == -1) {
358 if (errno != ESPIPE) {
359 return -1;
362 return write_data(fd, buffer, N);
363 #endif
366 static int reinit_after_fork_pipe[2] = { -1, -1 };
368 NTSTATUS init_before_fork(void)
370 int ret;
372 ret = pipe(reinit_after_fork_pipe);
373 if (ret == -1) {
374 NTSTATUS status;
376 status = map_nt_error_from_unix_common(errno);
378 DEBUG(0, ("Error creating child_pipe: %s\n",
379 nt_errstr(status)));
381 return status;
384 return NT_STATUS_OK;
388 * @brief Get a fd to watch for our parent process to exit
390 * Samba parent processes open a pipe that naturally closes when the
391 * parent exits. Child processes can watch the read end of the pipe
392 * for readability: Readability with 0 bytes to read means the parent
393 * has exited and the child process might also want to exit.
396 int parent_watch_fd(void)
398 return reinit_after_fork_pipe[0];
402 * Detect died parent by detecting EOF on the pipe
404 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
405 struct tevent_fd *fde,
406 uint16_t flags,
407 void *private_data)
409 char c;
411 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
413 * we have reached EOF on stdin, which means the
414 * parent has exited. Shutdown the server
416 TALLOC_FREE(fde);
417 (void)kill(getpid(), SIGTERM);
422 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
423 struct tevent_context *ev_ctx,
424 bool parent_longlived)
426 NTSTATUS status = NT_STATUS_OK;
427 int ret;
430 * The main process thread should never
431 * allow per_thread_cwd_enable() to be
432 * called.
434 per_thread_cwd_disable();
436 if (reinit_after_fork_pipe[1] != -1) {
437 close(reinit_after_fork_pipe[1]);
438 reinit_after_fork_pipe[1] = -1;
441 /* tdb needs special fork handling */
442 if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
443 DEBUG(0,("tdb_reopen_all failed.\n"));
444 status = NT_STATUS_OPEN_FAILED;
445 goto done;
448 if (ev_ctx != NULL) {
450 * The parent can have different private data for the callbacks,
451 * which are gone in the child. Reset the callbacks to be safe.
453 tevent_set_trace_callback(ev_ctx, NULL, NULL);
454 tevent_set_trace_fd_callback(ev_ctx, NULL, NULL);
455 tevent_set_trace_signal_callback(ev_ctx, NULL, NULL);
456 tevent_set_trace_timer_callback(ev_ctx, NULL, NULL);
457 tevent_set_trace_immediate_callback(ev_ctx, NULL, NULL);
458 tevent_set_trace_queue_callback(ev_ctx, NULL, NULL);
459 if (tevent_re_initialise(ev_ctx) != 0) {
460 smb_panic(__location__ ": Failed to re-initialise event context");
464 if (reinit_after_fork_pipe[0] != -1) {
465 struct tevent_fd *fde;
467 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
468 reinit_after_fork_pipe[0], TEVENT_FD_READ,
469 reinit_after_fork_pipe_handler, NULL);
470 if (fde == NULL) {
471 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
475 if (msg_ctx) {
477 * For clustering, we need to re-init our ctdbd connection after the
478 * fork
480 status = messaging_reinit(msg_ctx);
481 if (!NT_STATUS_IS_OK(status)) {
482 DEBUG(0,("messaging_reinit() failed: %s\n",
483 nt_errstr(status)));
486 if (lp_clustering()) {
487 ret = ctdb_async_ctx_reinit(
488 NULL, messaging_tevent_context(msg_ctx));
489 if (ret != 0) {
490 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
491 strerror(errno));
492 return map_nt_error_from_unix(ret);
497 done:
498 return status;
501 /****************************************************************************
502 (Hopefully) efficient array append.
503 ****************************************************************************/
505 void add_to_large_array(TALLOC_CTX *mem_ctx, size_t element_size,
506 void *element, void *_array, uint32_t *num_elements,
507 ssize_t *array_size)
509 void **array = (void **)_array;
511 if (*array_size < 0) {
512 return;
515 if (*array == NULL) {
516 if (*array_size == 0) {
517 *array_size = 128;
520 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
521 goto error;
524 *array = TALLOC(mem_ctx, element_size * (*array_size));
525 if (*array == NULL) {
526 goto error;
530 if (*num_elements == *array_size) {
531 *array_size *= 2;
533 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
534 goto error;
537 *array = TALLOC_REALLOC(mem_ctx, *array,
538 element_size * (*array_size));
540 if (*array == NULL) {
541 goto error;
545 memcpy((char *)(*array) + element_size*(*num_elements),
546 element, element_size);
547 *num_elements += 1;
549 return;
551 error:
552 *num_elements = 0;
553 *array_size = -1;
556 /****************************************************************************
557 Get my own domain name, or "" if we have none.
558 ****************************************************************************/
560 char *get_mydnsdomname(TALLOC_CTX *ctx)
562 const char *domname;
563 char *p;
565 domname = get_mydnsfullname();
566 if (!domname) {
567 return NULL;
570 p = strchr_m(domname, '.');
571 if (p) {
572 p++;
573 return talloc_strdup(ctx, p);
574 } else {
575 return talloc_strdup(ctx, "");
579 bool process_exists(const struct server_id pid)
581 return serverid_exists(&pid);
584 /*******************************************************************
585 Convert a uid into a user name.
586 ********************************************************************/
588 const char *uidtoname(uid_t uid)
590 TALLOC_CTX *ctx = talloc_tos();
591 char *name = NULL;
592 struct passwd *pass = NULL;
594 pass = getpwuid_alloc(ctx,uid);
595 if (pass) {
596 name = talloc_strdup(ctx,pass->pw_name);
597 TALLOC_FREE(pass);
598 } else {
599 name = talloc_asprintf(ctx,
600 "%ld",
601 (long int)uid);
603 return name;
606 /*******************************************************************
607 Convert a gid into a group name.
608 ********************************************************************/
610 char *gidtoname(gid_t gid)
612 struct group *grp;
614 grp = getgrgid(gid);
615 if (grp) {
616 return talloc_strdup(talloc_tos(), grp->gr_name);
618 else {
619 return talloc_asprintf(talloc_tos(),
620 "%d",
621 (int)gid);
625 /*******************************************************************
626 Convert a user name into a uid.
627 ********************************************************************/
629 uid_t nametouid(const char *name)
631 struct passwd *pass;
632 char *p;
633 uid_t u;
635 pass = Get_Pwnam_alloc(talloc_tos(), name);
636 if (pass) {
637 u = pass->pw_uid;
638 TALLOC_FREE(pass);
639 return u;
642 u = (uid_t)strtol(name, &p, 0);
643 if ((p != name) && (*p == '\0'))
644 return u;
646 return (uid_t)-1;
649 /*******************************************************************
650 Convert a name to a gid_t if possible. Return -1 if not a group.
651 ********************************************************************/
653 gid_t nametogid(const char *name)
655 struct group *grp;
656 char *p;
657 gid_t g;
659 g = (gid_t)strtol(name, &p, 0);
660 if ((p != name) && (*p == '\0'))
661 return g;
663 grp = getgrnam(name);
664 if (grp)
665 return(grp->gr_gid);
666 return (gid_t)-1;
669 /*******************************************************************
670 Something really nasty happened - panic !
671 ********************************************************************/
673 static void call_panic_action(const char *why, bool as_root)
675 const struct loadparm_substitution *lp_sub =
676 loadparm_s3_global_substitution();
677 char *cmd;
678 int result;
680 cmd = lp_panic_action(talloc_tos(), lp_sub);
681 if (cmd == NULL || cmd[0] == '\0') {
682 return;
685 DBG_ERR("Calling panic action [%s]\n", cmd);
687 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
689 * Make sure all children can attach a debugger.
691 prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
692 #endif
694 if (as_root) {
695 become_root();
698 result = system(cmd);
700 if (as_root) {
701 unbecome_root();
704 if (result == -1)
705 DBG_ERR("fork failed in panic action: %s\n",
706 strerror(errno));
707 else
708 DBG_ERR("action returned status %d\n",
709 WEXITSTATUS(result));
712 void smb_panic_s3(const char *why)
714 call_panic_action(why, false);
715 dump_core();
718 void log_panic_action(const char *msg)
720 DBG_ERR("%s", msg);
721 call_panic_action(msg, true);
724 /*******************************************************************
725 A readdir wrapper which just returns the file name.
726 ********************************************************************/
728 const char *readdirname(DIR *p)
730 struct dirent *ptr;
731 char *dname;
733 if (!p)
734 return(NULL);
736 ptr = (struct dirent *)readdir(p);
737 if (!ptr)
738 return(NULL);
740 dname = ptr->d_name;
742 return talloc_strdup(talloc_tos(), dname);
745 /*******************************************************************
746 Utility function used to decide if the last component
747 of a path matches a (possibly wildcarded) entry in a namelist.
748 ********************************************************************/
750 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
752 const char *last_component;
754 /* if we have no list it's obviously not in the path */
755 if ((namelist == NULL) || (namelist[0].name == NULL)) {
756 return False;
759 /* Do not reject path components if namelist is set to '.*' */
760 if (ISDOT(name) || ISDOTDOT(name)) {
761 return false;
764 DEBUG(8, ("is_in_path: %s\n", name));
766 /* Get the last component of the unix name. */
767 last_component = strrchr_m(name, '/');
768 if (!last_component) {
769 last_component = name;
770 } else {
771 last_component++; /* Go past '/' */
774 for(; namelist->name != NULL; namelist++) {
775 if(namelist->is_wild) {
776 if (mask_match(last_component, namelist->name, case_sensitive)) {
777 DEBUG(8,("is_in_path: mask match succeeded\n"));
778 return True;
780 } else {
781 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
782 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
783 DEBUG(8,("is_in_path: match succeeded\n"));
784 return True;
788 DEBUG(8,("is_in_path: match not found\n"));
789 return False;
792 /*******************************************************************
793 Strip a '/' separated list into an array of
794 name_compare_enties structures suitable for
795 passing to is_in_path(). We do this for
796 speed so we can pre-parse all the names in the list
797 and don't do it for each call to is_in_path().
798 We also check if the entry contains a wildcard to
799 remove a potentially expensive call to mask_match
800 if possible.
801 ********************************************************************/
803 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
805 char *name_end;
806 char *namelist;
807 char *namelist_end;
808 char *nameptr;
809 int num_entries = 0;
810 int i;
812 (*ppname_array) = NULL;
814 if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
815 return;
817 namelist = talloc_strdup(talloc_tos(), namelist_in);
818 if (namelist == NULL) {
819 DEBUG(0,("set_namearray: talloc fail\n"));
820 return;
822 nameptr = namelist;
824 namelist_end = &namelist[strlen(namelist)];
826 /* We need to make two passes over the string. The
827 first to count the number of elements, the second
828 to split it.
831 while(nameptr <= namelist_end) {
832 if ( *nameptr == '/' ) {
833 /* cope with multiple (useless) /s) */
834 nameptr++;
835 continue;
837 /* anything left? */
838 if ( *nameptr == '\0' )
839 break;
841 /* find the next '/' or consume remaining */
842 name_end = strchr_m(nameptr, '/');
843 if (name_end == NULL) {
844 /* Point nameptr at the terminating '\0' */
845 nameptr += strlen(nameptr);
846 } else {
847 /* next segment please */
848 nameptr = name_end + 1;
850 num_entries++;
853 if(num_entries == 0) {
854 talloc_free(namelist);
855 return;
858 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
859 DEBUG(0,("set_namearray: malloc fail\n"));
860 talloc_free(namelist);
861 return;
864 /* Now copy out the names */
865 nameptr = namelist;
866 i = 0;
867 while(nameptr <= namelist_end) {
868 if ( *nameptr == '/' ) {
869 /* cope with multiple (useless) /s) */
870 nameptr++;
871 continue;
873 /* anything left? */
874 if ( *nameptr == '\0' )
875 break;
877 /* find the next '/' or consume remaining */
878 name_end = strchr_m(nameptr, '/');
879 if (name_end != NULL) {
880 *name_end = '\0';
883 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
884 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
885 DEBUG(0,("set_namearray: malloc fail (1)\n"));
886 talloc_free(namelist);
887 return;
890 if (name_end == NULL) {
891 /* Point nameptr at the terminating '\0' */
892 nameptr += strlen(nameptr);
893 } else {
894 /* next segment please */
895 nameptr = name_end + 1;
897 i++;
900 (*ppname_array)[i].name = NULL;
902 talloc_free(namelist);
903 return;
906 #undef DBGC_CLASS
907 #define DBGC_CLASS DBGC_LOCKING
909 /****************************************************************************
910 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
911 is dealt with in posix.c
912 Returns True if we have information regarding this lock region (and returns
913 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
914 ****************************************************************************/
916 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
918 struct flock lock;
919 int ret;
921 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
922 fd,op,(double)*poffset,(double)*pcount,*ptype));
924 lock.l_type = *ptype;
925 lock.l_whence = SEEK_SET;
926 lock.l_start = *poffset;
927 lock.l_len = *pcount;
928 lock.l_pid = 0;
930 ret = sys_fcntl_ptr(fd,op,&lock);
932 if (ret == -1) {
933 int saved_errno = errno;
934 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
935 (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
936 errno = saved_errno;
937 return False;
940 *ptype = lock.l_type;
941 *poffset = lock.l_start;
942 *pcount = lock.l_len;
943 *ppid = lock.l_pid;
945 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
946 fd, (int)lock.l_type, (unsigned int)lock.l_pid));
947 return True;
950 #if defined(HAVE_OFD_LOCKS)
951 int map_process_lock_to_ofd_lock(int op)
953 switch (op) {
954 case F_GETLK:
955 case F_OFD_GETLK:
956 op = F_OFD_GETLK;
957 break;
958 case F_SETLK:
959 case F_OFD_SETLK:
960 op = F_OFD_SETLK;
961 break;
962 case F_SETLKW:
963 case F_OFD_SETLKW:
964 op = F_OFD_SETLKW;
965 break;
966 default:
967 return -1;
969 return op;
971 #else /* HAVE_OFD_LOCKS */
972 int map_process_lock_to_ofd_lock(int op)
974 return op;
976 #endif /* HAVE_OFD_LOCKS */
978 #undef DBGC_CLASS
979 #define DBGC_CLASS DBGC_ALL
981 /*******************************************************************
982 Is the name specified one of my netbios names.
983 Returns true if it is equal, false otherwise.
984 ********************************************************************/
986 static bool nb_name_equal(const char *s1, const char *s2)
988 int cmp = strncasecmp_m(s1, s2, MAX_NETBIOSNAME_LEN-1);
989 return (cmp == 0);
992 bool is_myname(const char *s)
994 const char **aliases = NULL;
995 bool ok = false;
997 ok = nb_name_equal(lp_netbios_name(), s);
998 if (ok) {
999 goto done;
1002 aliases = lp_netbios_aliases();
1003 if (aliases == NULL) {
1004 goto done;
1007 while (*aliases != NULL) {
1008 ok = nb_name_equal(*aliases, s);
1009 if (ok) {
1010 goto done;
1012 aliases += 1;
1015 done:
1016 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s, (int)ok);
1017 return ok;
1020 /*******************************************************************
1021 we distinguish between 2K and XP by the "Native Lan Manager" string
1022 WinXP => "Windows 2002 5.1"
1023 WinXP 64bit => "Windows XP 5.2"
1024 Win2k => "Windows 2000 5.0"
1025 NT4 => "Windows NT 4.0"
1026 Win9x => "Windows 4.0"
1027 Windows 2003 doesn't set the native lan manager string but
1028 they do set the domain to "Windows 2003 5.2" (probably a bug).
1029 ********************************************************************/
1031 void ra_lanman_string( const char *native_lanman )
1033 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1034 set_remote_arch( RA_WINXP );
1035 else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1036 set_remote_arch( RA_WINXP64 );
1037 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1038 set_remote_arch( RA_WIN2K3 );
1041 static const char *remote_arch_strings[] = {
1042 [RA_UNKNOWN] = "UNKNOWN",
1043 [RA_WFWG] = "WfWg",
1044 [RA_OS2] = "OS2",
1045 [RA_WIN95] = "Win95",
1046 [RA_WINNT] = "WinNT",
1047 [RA_WIN2K] = "Win2K",
1048 [RA_WINXP] = "WinXP",
1049 [RA_WIN2K3] = "Win2K3",
1050 [RA_VISTA] = "Vista",
1051 [RA_SAMBA] = "Samba",
1052 [RA_CIFSFS] = "CIFSFS",
1053 [RA_WINXP64] = "WinXP64",
1054 [RA_OSX] = "OSX",
1057 const char *get_remote_arch_str(void)
1059 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1061 * set_remote_arch() already checks this so ra_type
1062 * should be in the allowed range, but anyway, let's
1063 * do another bound check here.
1065 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1066 ra_type = RA_UNKNOWN;
1068 return remote_arch_strings[ra_type];
1071 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1073 size_t i;
1075 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1076 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1077 return i;
1080 return RA_UNKNOWN;
1083 /*******************************************************************
1084 Set the horrid remote_arch string based on an enum.
1085 ********************************************************************/
1087 void set_remote_arch(enum remote_arch_types type)
1089 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1091 * This protects against someone adding values to enum
1092 * remote_arch_types without updating
1093 * remote_arch_strings array.
1095 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1096 ra_type = RA_UNKNOWN;
1097 return;
1100 ra_type = type;
1101 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1102 get_remote_arch_str()));
1105 /*******************************************************************
1106 Get the remote_arch type.
1107 ********************************************************************/
1109 enum remote_arch_types get_remote_arch(void)
1111 return ra_type;
1114 #define RA_CACHE_TTL 7*24*3600
1116 static bool remote_arch_cache_key(const struct GUID *client_guid,
1117 fstring key)
1119 struct GUID_txt_buf guid_buf;
1120 const char *guid_string = NULL;
1122 guid_string = GUID_buf_string(client_guid, &guid_buf);
1123 if (guid_string == NULL) {
1124 return false;
1127 fstr_sprintf(key, "RA/%s", guid_string);
1128 return true;
1131 struct ra_parser_state {
1132 bool found;
1133 enum remote_arch_types ra;
1136 static void ra_parser(const struct gencache_timeout *t,
1137 DATA_BLOB blob,
1138 void *priv_data)
1140 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1141 const char *ra_str = NULL;
1143 if (gencache_timeout_expired(t)) {
1144 return;
1147 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1148 DBG_ERR("Remote arch cache key not a string\n");
1149 return;
1152 ra_str = (const char *)blob.data;
1153 DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1155 state->ra = get_remote_arch_from_str(ra_str);
1156 state->found = true;
1157 return;
1160 static bool remote_arch_cache_get(const struct GUID *client_guid)
1162 bool ok;
1163 fstring ra_key;
1164 struct ra_parser_state state = (struct ra_parser_state) {
1165 .found = false,
1166 .ra = RA_UNKNOWN,
1169 ok = remote_arch_cache_key(client_guid, ra_key);
1170 if (!ok) {
1171 return false;
1174 ok = gencache_parse(ra_key, ra_parser, &state);
1175 if (!ok || !state.found) {
1176 return true;
1179 if (state.ra == RA_UNKNOWN) {
1180 return true;
1183 set_remote_arch(state.ra);
1184 return true;
1187 static bool remote_arch_cache_set(const struct GUID *client_guid)
1189 bool ok;
1190 fstring ra_key;
1191 const char *ra_str = NULL;
1193 if (get_remote_arch() == RA_UNKNOWN) {
1194 return true;
1197 ok = remote_arch_cache_key(client_guid, ra_key);
1198 if (!ok) {
1199 return false;
1202 ra_str = get_remote_arch_str();
1203 if (ra_str == NULL) {
1204 return false;
1207 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1208 if (!ok) {
1209 return false;
1212 return true;
1215 bool remote_arch_cache_update(const struct GUID *client_guid)
1217 bool ok;
1219 if (get_remote_arch() == RA_UNKNOWN) {
1221 become_root();
1222 ok = remote_arch_cache_get(client_guid);
1223 unbecome_root();
1225 return ok;
1228 become_root();
1229 ok = remote_arch_cache_set(client_guid);
1230 unbecome_root();
1232 return ok;
1235 bool remote_arch_cache_delete(const struct GUID *client_guid)
1237 bool ok;
1238 fstring ra_key;
1240 ok = remote_arch_cache_key(client_guid, ra_key);
1241 if (!ok) {
1242 return false;
1245 become_root();
1246 ok = gencache_del(ra_key);
1247 unbecome_root();
1249 if (!ok) {
1250 return false;
1253 return true;
1257 /*****************************************************************************
1258 Provide a checksum on a string
1260 Input: s - the null-terminated character string for which the checksum
1261 will be calculated.
1263 Output: The checksum value calculated for s.
1264 *****************************************************************************/
1266 int str_checksum(const char *s)
1268 TDB_DATA key;
1269 if (s == NULL)
1270 return 0;
1272 key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1273 .dsize = strlen(s) };
1275 return tdb_jenkins_hash(&key);
1278 /*****************************************************************
1279 Zero a memory area then free it. Used to catch bugs faster.
1280 *****************************************************************/
1282 void zero_free(void *p, size_t size)
1284 memset(p, 0, size);
1285 SAFE_FREE(p);
1288 /*****************************************************************
1289 Set our open file limit to a requested max and return the limit.
1290 *****************************************************************/
1292 int set_maxfiles(int requested_max)
1294 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1295 struct rlimit rlp;
1296 int saved_current_limit;
1298 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1299 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1300 strerror(errno) ));
1301 /* just guess... */
1302 return requested_max;
1306 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1307 * account for the extra fd we need
1308 * as well as the log files and standard
1309 * handles etc. Save the limit we want to set in case
1310 * we are running on an OS that doesn't support this limit (AIX)
1311 * which always returns RLIM_INFINITY for rlp.rlim_max.
1314 /* Try raising the hard (max) limit to the requested amount. */
1316 #if defined(RLIM_INFINITY)
1317 if (rlp.rlim_max != RLIM_INFINITY) {
1318 int orig_max = rlp.rlim_max;
1320 if ( rlp.rlim_max < requested_max )
1321 rlp.rlim_max = requested_max;
1323 /* This failing is not an error - many systems (Linux) don't
1324 support our default request of 10,000 open files. JRA. */
1326 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1327 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1328 (int)rlp.rlim_max, strerror(errno) ));
1330 /* Set failed - restore original value from get. */
1331 rlp.rlim_max = orig_max;
1334 #endif
1336 /* Now try setting the soft (current) limit. */
1338 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1340 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1341 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1342 (int)rlp.rlim_cur, strerror(errno) ));
1343 /* just guess... */
1344 return saved_current_limit;
1347 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1348 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1349 strerror(errno) ));
1350 /* just guess... */
1351 return saved_current_limit;
1354 #if defined(RLIM_INFINITY)
1355 if(rlp.rlim_cur == RLIM_INFINITY)
1356 return saved_current_limit;
1357 #endif
1359 if((int)rlp.rlim_cur > saved_current_limit)
1360 return saved_current_limit;
1362 return rlp.rlim_cur;
1363 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1365 * No way to know - just guess...
1367 return requested_max;
1368 #endif
1371 /*****************************************************************
1372 malloc that aborts with smb_panic on fail or zero size.
1373 *****************************************************************/
1375 void *smb_xmalloc_array(size_t size, unsigned int count)
1377 void *p;
1378 if (size == 0) {
1379 smb_panic("smb_xmalloc_array: called with zero size");
1381 if (count >= MAX_ALLOC_SIZE/size) {
1382 smb_panic("smb_xmalloc_array: alloc size too large");
1384 if ((p = SMB_MALLOC(size*count)) == NULL) {
1385 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1386 (unsigned long)size, (unsigned long)count));
1387 smb_panic("smb_xmalloc_array: malloc failed");
1389 return p;
1392 /*****************************************************************
1393 Get local hostname and cache result.
1394 *****************************************************************/
1396 char *myhostname(void)
1398 static char *ret;
1399 if (ret == NULL) {
1400 ret = get_myname(NULL);
1402 return ret;
1405 /*****************************************************************
1406 Get local hostname and cache result.
1407 *****************************************************************/
1409 char *myhostname_upper(void)
1411 static char *ret;
1412 if (ret == NULL) {
1413 char *name = get_myname(NULL);
1414 if (name == NULL) {
1415 return NULL;
1417 ret = strupper_talloc(NULL, name);
1418 talloc_free(name);
1420 return ret;
1423 /*******************************************************************
1424 Given a filename - get its directory name
1425 ********************************************************************/
1427 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1428 const char **name)
1430 char *p;
1431 ptrdiff_t len;
1433 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1435 if (p == NULL) {
1436 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1437 return False;
1439 if (name) {
1440 *name = dir;
1442 return True;
1445 len = p-dir;
1447 *parent = talloc_strndup(mem_ctx, dir, len);
1448 if (*parent == NULL) {
1449 return False;
1452 if (name) {
1453 *name = p+1;
1455 return True;
1458 /*******************************************************************
1459 Determine if a pattern contains any Microsoft wildcard characters.
1460 *******************************************************************/
1462 bool ms_has_wild(const char *s)
1464 const char *found = strpbrk(s, "*?<>\"");
1465 return (found != NULL);
1468 bool ms_has_wild_w(const smb_ucs2_t *s)
1470 smb_ucs2_t c;
1471 if (!s) return False;
1472 while ((c = *s++)) {
1473 switch (c) {
1474 case UCS2_CHAR('*'):
1475 case UCS2_CHAR('?'):
1476 case UCS2_CHAR('<'):
1477 case UCS2_CHAR('>'):
1478 case UCS2_CHAR('"'):
1479 return True;
1482 return False;
1485 /*******************************************************************
1486 A wrapper that handles case sensitivity and the special handling
1487 of the ".." name.
1488 *******************************************************************/
1490 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1492 if (ISDOTDOT(string))
1493 string = ".";
1494 if (ISDOT(pattern))
1495 return False;
1497 return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1500 /*******************************************************************
1501 A wrapper that handles a list of patterns and calls mask_match()
1502 on each. Returns True if any of the patterns match.
1503 *******************************************************************/
1505 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1507 while (listLen-- > 0) {
1508 if (mask_match(string, *list++, is_case_sensitive))
1509 return True;
1511 return False;
1514 struct server_id interpret_pid(const char *pid_string)
1516 return server_id_from_string(get_my_vnn(), pid_string);
1519 /****************************************************************
1520 Check if an offset into a buffer is safe.
1521 If this returns True it's safe to indirect into the byte at
1522 pointer ptr+off.
1523 ****************************************************************/
1525 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1527 const char *end_base = buf_base + buf_len;
1528 char *end_ptr = ptr + off;
1530 if (!buf_base || !ptr) {
1531 return False;
1534 if (end_base < buf_base || end_ptr < ptr) {
1535 return False; /* wrap. */
1538 if (end_ptr < end_base) {
1539 return True;
1541 return False;
1544 /****************************************************************
1545 Return a safe pointer into a string within a buffer, or NULL.
1546 ****************************************************************/
1548 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1550 if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1551 return NULL;
1553 /* Check if a valid string exists at this offset. */
1554 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1555 return NULL;
1557 return ptr + off;
1561 /****************************************************************
1562 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1563 call (they take care of winbind separator and other winbind specific settings).
1564 ****************************************************************/
1566 bool split_domain_user(TALLOC_CTX *mem_ctx,
1567 const char *full_name,
1568 char **domain,
1569 char **user)
1571 const char *p = NULL;
1573 p = strchr_m(full_name, '\\');
1575 if (p != NULL) {
1576 *domain = talloc_strndup(mem_ctx, full_name,
1577 PTR_DIFF(p, full_name));
1578 if (*domain == NULL) {
1579 return false;
1581 *user = talloc_strdup(mem_ctx, p+1);
1582 if (*user == NULL) {
1583 TALLOC_FREE(*domain);
1584 return false;
1586 } else {
1587 *domain = NULL;
1588 *user = talloc_strdup(mem_ctx, full_name);
1589 if (*user == NULL) {
1590 return false;
1594 return true;
1597 /****************************************************************
1598 strip off leading '\\' from a hostname
1599 ****************************************************************/
1601 const char *strip_hostname(const char *s)
1603 if (!s) {
1604 return NULL;
1607 if (strlen_m(s) < 3) {
1608 return s;
1611 if (s[0] == '\\') s++;
1612 if (s[0] == '\\') s++;
1614 return s;
1617 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1619 if (!NT_STATUS_IS_OK(err1)) {
1620 *result = err1;
1621 return true;
1623 if (!NT_STATUS_IS_OK(err2)) {
1624 *result = err2;
1625 return true;
1627 return false;
1630 int timeval_to_msec(struct timeval t)
1632 return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1635 /*******************************************************************
1636 Check a given DOS pathname is valid for a share.
1637 ********************************************************************/
1639 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1641 char *ptr = NULL;
1643 if (!dos_pathname) {
1644 return NULL;
1647 ptr = talloc_strdup(ctx, dos_pathname);
1648 if (!ptr) {
1649 return NULL;
1651 /* Convert any '\' paths to '/' */
1652 unix_format(ptr);
1653 ptr = unix_clean_name(ctx, ptr);
1654 if (!ptr) {
1655 return NULL;
1658 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1659 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1660 ptr += 2;
1662 /* Only absolute paths allowed. */
1663 if (*ptr != '/')
1664 return NULL;
1666 return ptr;
1669 /*******************************************************************
1670 Return True if the filename is one of the special executable types.
1671 ********************************************************************/
1673 bool is_executable(const char *fname)
1675 if ((fname = strrchr_m(fname,'.'))) {
1676 if (strequal(fname,".com") ||
1677 strequal(fname,".dll") ||
1678 strequal(fname,".exe") ||
1679 strequal(fname,".sym")) {
1680 return True;
1683 return False;
1686 /****************************************************************************
1687 Open a file with a share mode - old openX method - map into NTCreate.
1688 ****************************************************************************/
1690 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1691 int deny_mode, int open_func,
1692 uint32_t *paccess_mask,
1693 uint32_t *pshare_mode,
1694 uint32_t *pcreate_disposition,
1695 uint32_t *pcreate_options,
1696 uint32_t *pprivate_flags)
1698 uint32_t access_mask;
1699 uint32_t share_mode;
1700 uint32_t create_disposition;
1701 uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1702 uint32_t private_flags = 0;
1704 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1705 "open_func = 0x%x\n",
1706 smb_base_fname, (unsigned int)deny_mode,
1707 (unsigned int)open_func ));
1709 /* Create the NT compatible access_mask. */
1710 switch (GET_OPENX_MODE(deny_mode)) {
1711 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1712 case DOS_OPEN_RDONLY:
1713 access_mask = FILE_GENERIC_READ;
1714 break;
1715 case DOS_OPEN_WRONLY:
1716 access_mask = FILE_GENERIC_WRITE;
1717 break;
1718 case DOS_OPEN_RDWR:
1719 case DOS_OPEN_FCB:
1720 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1721 break;
1722 default:
1723 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1724 (unsigned int)GET_OPENX_MODE(deny_mode)));
1725 return False;
1728 /* Create the NT compatible create_disposition. */
1729 switch (open_func) {
1730 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
1731 create_disposition = FILE_CREATE;
1732 break;
1734 case OPENX_FILE_EXISTS_OPEN:
1735 create_disposition = FILE_OPEN;
1736 break;
1738 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
1739 create_disposition = FILE_OPEN_IF;
1740 break;
1742 case OPENX_FILE_EXISTS_TRUNCATE:
1743 create_disposition = FILE_OVERWRITE;
1744 break;
1746 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1747 create_disposition = FILE_OVERWRITE_IF;
1748 break;
1750 default:
1751 /* From samba4 - to be confirmed. */
1752 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1753 create_disposition = FILE_CREATE;
1754 break;
1756 DEBUG(10,("map_open_params_to_ntcreate: bad "
1757 "open_func 0x%x\n", (unsigned int)open_func));
1758 return False;
1761 /* Create the NT compatible share modes. */
1762 switch (GET_DENY_MODE(deny_mode)) {
1763 case DENY_ALL:
1764 share_mode = FILE_SHARE_NONE;
1765 break;
1767 case DENY_WRITE:
1768 share_mode = FILE_SHARE_READ;
1769 break;
1771 case DENY_READ:
1772 share_mode = FILE_SHARE_WRITE;
1773 break;
1775 case DENY_NONE:
1776 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1777 break;
1779 case DENY_DOS:
1780 private_flags |= NTCREATEX_FLAG_DENY_DOS;
1781 if (is_executable(smb_base_fname)) {
1782 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1783 } else {
1784 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1785 share_mode = FILE_SHARE_READ;
1786 } else {
1787 share_mode = FILE_SHARE_NONE;
1790 break;
1792 case DENY_FCB:
1793 private_flags |= NTCREATEX_FLAG_DENY_FCB;
1794 share_mode = FILE_SHARE_NONE;
1795 break;
1797 default:
1798 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1799 (unsigned int)GET_DENY_MODE(deny_mode) ));
1800 return False;
1803 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1804 "share_mode = 0x%x, create_disposition = 0x%x, "
1805 "create_options = 0x%x private_flags = 0x%x\n",
1806 smb_base_fname,
1807 (unsigned int)access_mask,
1808 (unsigned int)share_mode,
1809 (unsigned int)create_disposition,
1810 (unsigned int)create_options,
1811 (unsigned int)private_flags));
1813 if (paccess_mask) {
1814 *paccess_mask = access_mask;
1816 if (pshare_mode) {
1817 *pshare_mode = share_mode;
1819 if (pcreate_disposition) {
1820 *pcreate_disposition = create_disposition;
1822 if (pcreate_options) {
1823 *pcreate_options = create_options;
1825 if (pprivate_flags) {
1826 *pprivate_flags = private_flags;
1829 return True;
1833 /*************************************************************************
1834 Return a talloced copy of a struct security_unix_token. NULL on fail.
1835 *************************************************************************/
1837 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
1839 struct security_unix_token *cpy;
1841 cpy = talloc(ctx, struct security_unix_token);
1842 if (!cpy) {
1843 return NULL;
1846 *cpy = (struct security_unix_token){
1847 .uid = tok->uid,
1848 .gid = tok->gid,
1849 .ngroups = tok->ngroups,
1852 if (tok->ngroups) {
1853 /* Make this a talloc child of cpy. */
1854 cpy->groups = (gid_t *)talloc_memdup(
1855 cpy, tok->groups, tok->ngroups * sizeof(gid_t));
1856 if (!cpy->groups) {
1857 TALLOC_FREE(cpy);
1858 return NULL;
1861 return cpy;
1864 /****************************************************************************
1865 Return a root token
1866 ****************************************************************************/
1868 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
1870 struct security_unix_token *t = NULL;
1872 t = talloc_zero(mem_ctx, struct security_unix_token);
1873 if (t == NULL) {
1874 return NULL;
1878 * This is not needed, but lets make it explicit, not implicit.
1880 *t = (struct security_unix_token) {
1881 .uid = 0,
1882 .gid = 0,
1883 .ngroups = 0,
1884 .groups = NULL
1887 return t;
1890 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
1892 char *str;
1893 uint32_t i;
1895 str = talloc_asprintf(
1896 mem_ctx,
1897 "uid=%ju, gid=%ju, %"PRIu32" groups:",
1898 (uintmax_t)(tok->uid),
1899 (uintmax_t)(tok->gid),
1900 tok->ngroups);
1902 for (i=0; i<tok->ngroups; i++) {
1903 talloc_asprintf_addbuf(
1904 &str, " %ju", (uintmax_t)tok->groups[i]);
1907 return str;
1910 /****************************************************************************
1911 Check that a file matches a particular file type.
1912 ****************************************************************************/
1914 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
1916 uint32_t mask;
1918 /* Check the "may have" search bits. */
1919 if (((mode & ~dirtype) &
1920 (FILE_ATTRIBUTE_HIDDEN |
1921 FILE_ATTRIBUTE_SYSTEM |
1922 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
1923 return false;
1926 /* Check the "must have" bits,
1927 which are the may have bits shifted eight */
1928 /* If must have bit is set, the file/dir can
1929 not be returned in search unless the matching
1930 file attribute is set */
1931 mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
1932 FILE_ATTRIBUTE_ARCHIVE|
1933 FILE_ATTRIBUTE_READONLY|
1934 FILE_ATTRIBUTE_HIDDEN|
1935 FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
1936 if(mask) {
1937 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
1938 FILE_ATTRIBUTE_ARCHIVE|
1939 FILE_ATTRIBUTE_READONLY|
1940 FILE_ATTRIBUTE_HIDDEN|
1941 FILE_ATTRIBUTE_SYSTEM))) == mask) {
1942 /* check if matching attribute present */
1943 return true;
1944 } else {
1945 return false;
1949 return true;