smbd: Move mask_match_search() to smb1_reply.c
[Samba.git] / source3 / lib / util.c
blobfa01f419d657fb945abeeb3a654ef7d9ab7f9bc8
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 enum protocol_types get_Protocol(void)
59 return Protocol;
62 void set_Protocol(enum protocol_types p)
64 Protocol = p;
67 static enum remote_arch_types ra_type = RA_UNKNOWN;
69 void gfree_all( void )
71 gfree_loadparm();
72 gfree_charcnv();
73 gfree_interfaces();
74 gfree_debugsyms();
75 gfree_memcache();
79 /*******************************************************************
80 Check if a file exists - call vfs_file_exist for samba files.
81 ********************************************************************/
83 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
84 bool fake_dir_create_times)
86 SMB_STRUCT_STAT st;
87 if (!sbuf)
88 sbuf = &st;
90 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
91 return(False);
93 return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
96 /*******************************************************************
97 Check if a unix domain socket exists - call vfs_file_exist for samba files.
98 ********************************************************************/
100 bool socket_exist(const char *fname)
102 SMB_STRUCT_STAT st;
103 if (sys_stat(fname, &st, false) != 0)
104 return(False);
106 return S_ISSOCK(st.st_ex_mode);
109 /*******************************************************************
110 Returns the size in bytes of the named given the stat struct.
111 ********************************************************************/
113 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
115 return sbuf->st_ex_size;
118 /****************************************************************************
119 Check two stats have identical dev and ino fields.
120 ****************************************************************************/
122 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
123 const SMB_STRUCT_STAT *sbuf2)
125 return ((sbuf1->st_ex_dev == sbuf2->st_ex_dev) &&
126 (sbuf1->st_ex_ino == sbuf2->st_ex_ino));
129 /****************************************************************************
130 Check if a stat struct is identical for use.
131 ****************************************************************************/
133 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
134 const SMB_STRUCT_STAT *sbuf2)
136 return ((sbuf1->st_ex_uid == sbuf2->st_ex_uid) &&
137 (sbuf1->st_ex_gid == sbuf2->st_ex_gid) &&
138 check_same_dev_ino(sbuf1, sbuf2));
141 /*******************************************************************
142 Show a smb message structure.
143 ********************************************************************/
145 void show_msg(const char *buf)
147 int i;
148 int bcc=0;
150 if (!DEBUGLVL(5))
151 return;
153 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
154 smb_len(buf),
155 (int)CVAL(buf,smb_com),
156 (int)CVAL(buf,smb_rcls),
157 (int)CVAL(buf,smb_reh),
158 (int)SVAL(buf,smb_err),
159 (int)CVAL(buf,smb_flg),
160 (int)SVAL(buf,smb_flg2)));
161 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
162 (int)SVAL(buf,smb_tid),
163 (int)SVAL(buf,smb_pid),
164 (int)SVAL(buf,smb_uid),
165 (int)SVAL(buf,smb_mid)));
166 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
168 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
169 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
170 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
172 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
174 DEBUGADD(5,("smb_bcc=%d\n",bcc));
176 if (DEBUGLEVEL < 10)
177 return;
179 if (DEBUGLEVEL < 50)
180 bcc = MIN(bcc, 512);
182 dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
185 /*******************************************************************
186 Setup only the byte count for a smb message.
187 ********************************************************************/
189 int set_message_bcc(char *buf,int num_bytes)
191 int num_words = CVAL(buf,smb_wct);
192 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
193 _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
194 return (smb_size + num_words*2 + num_bytes);
197 /*******************************************************************
198 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
199 Return the bytes added
200 ********************************************************************/
202 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
204 size_t newlen = smb_len(*outbuf) + 4 + blob.length;
205 uint8_t *tmp;
207 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
208 DEBUG(0, ("talloc failed\n"));
209 return -1;
211 *outbuf = tmp;
213 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
214 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
215 return blob.length;
218 /*******************************************************************
219 Reduce a file name, removing .. elements.
220 ********************************************************************/
222 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
224 char *p = NULL;
225 char *str = NULL;
227 DEBUG(3,("dos_clean_name [%s]\n",s));
229 /* remove any double slashes */
230 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
231 if (!str) {
232 return NULL;
235 /* Remove leading .\\ characters */
236 if(strncmp(str, ".\\", 2) == 0) {
237 trim_string(str, ".\\", NULL);
238 if(*str == 0) {
239 str = talloc_strdup(ctx, ".\\");
240 if (!str) {
241 return NULL;
246 while ((p = strstr_m(str,"\\..\\")) != NULL) {
247 char *s1;
249 *p = 0;
250 s1 = p+3;
252 if ((p=strrchr_m(str,'\\')) != NULL) {
253 *p = 0;
254 } else {
255 *str = 0;
257 str = talloc_asprintf(ctx,
258 "%s%s",
259 str,
260 s1);
261 if (!str) {
262 return NULL;
266 trim_string(str,NULL,"\\..");
267 return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
270 /*******************************************************************
271 Reduce a file name, removing .. elements.
272 ********************************************************************/
274 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
276 char *p = NULL;
277 char *str = NULL;
279 DEBUG(3,("unix_clean_name [%s]\n",s));
281 /* remove any double slashes */
282 str = talloc_all_string_sub(ctx, s, "//","/");
283 if (!str) {
284 return NULL;
287 /* Remove leading ./ characters */
288 if(strncmp(str, "./", 2) == 0) {
289 trim_string(str, "./", NULL);
290 if(*str == 0) {
291 str = talloc_strdup(ctx, "./");
292 if (!str) {
293 return NULL;
298 while ((p = strstr_m(str,"/../")) != NULL) {
299 char *s1;
301 *p = 0;
302 s1 = p+3;
304 if ((p=strrchr_m(str,'/')) != NULL) {
305 *p = 0;
306 } else {
307 *str = 0;
309 str = talloc_asprintf(ctx,
310 "%s%s",
311 str,
312 s1);
313 if (!str) {
314 return NULL;
318 trim_string(str,NULL,"/..");
319 return talloc_all_string_sub(ctx, str, "/./", "/");
322 char *clean_name(TALLOC_CTX *ctx, const char *s)
324 char *str = dos_clean_name(ctx, s);
325 if (!str) {
326 return NULL;
328 return unix_clean_name(ctx, str);
331 /*******************************************************************
332 Write data into an fd at a given offset. Ignore seek errors.
333 ********************************************************************/
335 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
337 size_t total=0;
338 ssize_t ret;
340 if (pos == (off_t)-1) {
341 return write_data(fd, buffer, N);
343 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
344 while (total < N) {
345 ret = sys_pwrite(fd,buffer + total,N - total, pos);
346 if (ret == -1 && errno == ESPIPE) {
347 return write_data(fd, buffer + total,N - total);
349 if (ret == -1) {
350 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
351 return -1;
353 if (ret == 0) {
354 return total;
356 total += ret;
357 pos += ret;
359 return (ssize_t)total;
360 #else
361 /* Use lseek and write_data. */
362 if (lseek(fd, pos, SEEK_SET) == -1) {
363 if (errno != ESPIPE) {
364 return -1;
367 return write_data(fd, buffer, N);
368 #endif
371 static int reinit_after_fork_pipe[2] = { -1, -1 };
373 NTSTATUS init_before_fork(void)
375 int ret;
377 ret = pipe(reinit_after_fork_pipe);
378 if (ret == -1) {
379 NTSTATUS status;
381 status = map_nt_error_from_unix_common(errno);
383 DEBUG(0, ("Error creating child_pipe: %s\n",
384 nt_errstr(status)));
386 return status;
389 return NT_STATUS_OK;
393 * @brief Get a fd to watch for our parent process to exit
395 * Samba parent processes open a pipe that naturally closes when the
396 * parent exits. Child processes can watch the read end of the pipe
397 * for readability: Readability with 0 bytes to read means the parent
398 * has exited and the child process might also want to exit.
401 int parent_watch_fd(void)
403 return reinit_after_fork_pipe[0];
407 * Detect died parent by detecting EOF on the pipe
409 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
410 struct tevent_fd *fde,
411 uint16_t flags,
412 void *private_data)
414 char c;
416 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
418 * we have reached EOF on stdin, which means the
419 * parent has exited. Shutdown the server
421 TALLOC_FREE(fde);
422 (void)kill(getpid(), SIGTERM);
427 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
428 struct tevent_context *ev_ctx,
429 bool parent_longlived)
431 NTSTATUS status = NT_STATUS_OK;
432 int ret;
435 * The main process thread should never
436 * allow per_thread_cwd_enable() to be
437 * called.
439 per_thread_cwd_disable();
441 if (reinit_after_fork_pipe[1] != -1) {
442 close(reinit_after_fork_pipe[1]);
443 reinit_after_fork_pipe[1] = -1;
446 /* tdb needs special fork handling */
447 if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
448 DEBUG(0,("tdb_reopen_all failed.\n"));
449 status = NT_STATUS_OPEN_FAILED;
450 goto done;
453 if (ev_ctx != NULL) {
455 * The parent can have different private data for the callbacks,
456 * which are gone in the child. Reset the callbacks to be safe.
458 tevent_set_trace_callback(ev_ctx, NULL, NULL);
459 tevent_set_trace_fd_callback(ev_ctx, NULL, NULL);
460 tevent_set_trace_signal_callback(ev_ctx, NULL, NULL);
461 tevent_set_trace_timer_callback(ev_ctx, NULL, NULL);
462 tevent_set_trace_immediate_callback(ev_ctx, NULL, NULL);
463 tevent_set_trace_queue_callback(ev_ctx, NULL, NULL);
464 if (tevent_re_initialise(ev_ctx) != 0) {
465 smb_panic(__location__ ": Failed to re-initialise event context");
469 if (reinit_after_fork_pipe[0] != -1) {
470 struct tevent_fd *fde;
472 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
473 reinit_after_fork_pipe[0], TEVENT_FD_READ,
474 reinit_after_fork_pipe_handler, NULL);
475 if (fde == NULL) {
476 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
480 if (msg_ctx) {
482 * For clustering, we need to re-init our ctdbd connection after the
483 * fork
485 status = messaging_reinit(msg_ctx);
486 if (!NT_STATUS_IS_OK(status)) {
487 DEBUG(0,("messaging_reinit() failed: %s\n",
488 nt_errstr(status)));
491 if (lp_clustering()) {
492 ret = ctdb_async_ctx_reinit(
493 NULL, messaging_tevent_context(msg_ctx));
494 if (ret != 0) {
495 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
496 strerror(errno));
497 return map_nt_error_from_unix(ret);
502 done:
503 return status;
506 /****************************************************************************
507 (Hopefully) efficient array append.
508 ****************************************************************************/
510 void add_to_large_array(TALLOC_CTX *mem_ctx, size_t element_size,
511 void *element, void *_array, uint32_t *num_elements,
512 ssize_t *array_size)
514 void **array = (void **)_array;
516 if (*array_size < 0) {
517 return;
520 if (*array == NULL) {
521 if (*array_size == 0) {
522 *array_size = 128;
525 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
526 goto error;
529 *array = TALLOC(mem_ctx, element_size * (*array_size));
530 if (*array == NULL) {
531 goto error;
535 if (*num_elements == *array_size) {
536 *array_size *= 2;
538 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
539 goto error;
542 *array = TALLOC_REALLOC(mem_ctx, *array,
543 element_size * (*array_size));
545 if (*array == NULL) {
546 goto error;
550 memcpy((char *)(*array) + element_size*(*num_elements),
551 element, element_size);
552 *num_elements += 1;
554 return;
556 error:
557 *num_elements = 0;
558 *array_size = -1;
561 /****************************************************************************
562 Get my own domain name, or "" if we have none.
563 ****************************************************************************/
565 char *get_mydnsdomname(TALLOC_CTX *ctx)
567 const char *domname;
568 char *p;
570 domname = get_mydnsfullname();
571 if (!domname) {
572 return NULL;
575 p = strchr_m(domname, '.');
576 if (p) {
577 p++;
578 return talloc_strdup(ctx, p);
579 } else {
580 return talloc_strdup(ctx, "");
584 bool process_exists(const struct server_id pid)
586 return serverid_exists(&pid);
589 /*******************************************************************
590 Convert a uid into a user name.
591 ********************************************************************/
593 const char *uidtoname(uid_t uid)
595 TALLOC_CTX *ctx = talloc_tos();
596 char *name = NULL;
597 struct passwd *pass = NULL;
599 pass = getpwuid_alloc(ctx,uid);
600 if (pass) {
601 name = talloc_strdup(ctx,pass->pw_name);
602 TALLOC_FREE(pass);
603 } else {
604 name = talloc_asprintf(ctx,
605 "%ld",
606 (long int)uid);
608 return name;
611 /*******************************************************************
612 Convert a gid into a group name.
613 ********************************************************************/
615 char *gidtoname(gid_t gid)
617 struct group *grp;
619 grp = getgrgid(gid);
620 if (grp) {
621 return talloc_strdup(talloc_tos(), grp->gr_name);
623 else {
624 return talloc_asprintf(talloc_tos(),
625 "%d",
626 (int)gid);
630 /*******************************************************************
631 Convert a user name into a uid.
632 ********************************************************************/
634 uid_t nametouid(const char *name)
636 struct passwd *pass;
637 char *p;
638 uid_t u;
640 pass = Get_Pwnam_alloc(talloc_tos(), name);
641 if (pass) {
642 u = pass->pw_uid;
643 TALLOC_FREE(pass);
644 return u;
647 u = (uid_t)strtol(name, &p, 0);
648 if ((p != name) && (*p == '\0'))
649 return u;
651 return (uid_t)-1;
654 /*******************************************************************
655 Convert a name to a gid_t if possible. Return -1 if not a group.
656 ********************************************************************/
658 gid_t nametogid(const char *name)
660 struct group *grp;
661 char *p;
662 gid_t g;
664 g = (gid_t)strtol(name, &p, 0);
665 if ((p != name) && (*p == '\0'))
666 return g;
668 grp = getgrnam(name);
669 if (grp)
670 return(grp->gr_gid);
671 return (gid_t)-1;
674 /*******************************************************************
675 Something really nasty happened - panic !
676 ********************************************************************/
678 void smb_panic_s3(const char *why)
680 const struct loadparm_substitution *lp_sub =
681 loadparm_s3_global_substitution();
682 char *cmd;
683 int result;
685 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
687 * Make sure all children can attach a debugger.
689 prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
690 #endif
692 cmd = lp_panic_action(talloc_tos(), lp_sub);
693 if (cmd && *cmd) {
694 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
695 result = system(cmd);
697 if (result == -1)
698 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
699 strerror(errno)));
700 else
701 DEBUG(0, ("smb_panic(): action returned status %d\n",
702 WEXITSTATUS(result)));
705 dump_core();
708 /*******************************************************************
709 A readdir wrapper which just returns the file name.
710 ********************************************************************/
712 const char *readdirname(DIR *p)
714 struct dirent *ptr;
715 char *dname;
717 if (!p)
718 return(NULL);
720 ptr = (struct dirent *)readdir(p);
721 if (!ptr)
722 return(NULL);
724 dname = ptr->d_name;
726 return talloc_strdup(talloc_tos(), dname);
729 /*******************************************************************
730 Utility function used to decide if the last component
731 of a path matches a (possibly wildcarded) entry in a namelist.
732 ********************************************************************/
734 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
736 const char *last_component;
738 /* if we have no list it's obviously not in the path */
739 if ((namelist == NULL) || (namelist[0].name == NULL)) {
740 return False;
743 /* Do not reject path components if namelist is set to '.*' */
744 if (ISDOT(name) || ISDOTDOT(name)) {
745 return false;
748 DEBUG(8, ("is_in_path: %s\n", name));
750 /* Get the last component of the unix name. */
751 last_component = strrchr_m(name, '/');
752 if (!last_component) {
753 last_component = name;
754 } else {
755 last_component++; /* Go past '/' */
758 for(; namelist->name != NULL; namelist++) {
759 if(namelist->is_wild) {
760 if (mask_match(last_component, namelist->name, case_sensitive)) {
761 DEBUG(8,("is_in_path: mask match succeeded\n"));
762 return True;
764 } else {
765 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
766 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
767 DEBUG(8,("is_in_path: match succeeded\n"));
768 return True;
772 DEBUG(8,("is_in_path: match not found\n"));
773 return False;
776 /*******************************************************************
777 Strip a '/' separated list into an array of
778 name_compare_enties structures suitable for
779 passing to is_in_path(). We do this for
780 speed so we can pre-parse all the names in the list
781 and don't do it for each call to is_in_path().
782 We also check if the entry contains a wildcard to
783 remove a potentially expensive call to mask_match
784 if possible.
785 ********************************************************************/
787 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
789 char *name_end;
790 char *namelist;
791 char *namelist_end;
792 char *nameptr;
793 int num_entries = 0;
794 int i;
796 (*ppname_array) = NULL;
798 if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
799 return;
801 namelist = talloc_strdup(talloc_tos(), namelist_in);
802 if (namelist == NULL) {
803 DEBUG(0,("set_namearray: talloc fail\n"));
804 return;
806 nameptr = namelist;
808 namelist_end = &namelist[strlen(namelist)];
810 /* We need to make two passes over the string. The
811 first to count the number of elements, the second
812 to split it.
815 while(nameptr <= namelist_end) {
816 if ( *nameptr == '/' ) {
817 /* cope with multiple (useless) /s) */
818 nameptr++;
819 continue;
821 /* anything left? */
822 if ( *nameptr == '\0' )
823 break;
825 /* find the next '/' or consume remaining */
826 name_end = strchr_m(nameptr, '/');
827 if (name_end == NULL) {
828 /* Point nameptr at the terminating '\0' */
829 nameptr += strlen(nameptr);
830 } else {
831 /* next segment please */
832 nameptr = name_end + 1;
834 num_entries++;
837 if(num_entries == 0) {
838 talloc_free(namelist);
839 return;
842 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
843 DEBUG(0,("set_namearray: malloc fail\n"));
844 talloc_free(namelist);
845 return;
848 /* Now copy out the names */
849 nameptr = namelist;
850 i = 0;
851 while(nameptr <= namelist_end) {
852 if ( *nameptr == '/' ) {
853 /* cope with multiple (useless) /s) */
854 nameptr++;
855 continue;
857 /* anything left? */
858 if ( *nameptr == '\0' )
859 break;
861 /* find the next '/' or consume remaining */
862 name_end = strchr_m(nameptr, '/');
863 if (name_end != NULL) {
864 *name_end = '\0';
867 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
868 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
869 DEBUG(0,("set_namearray: malloc fail (1)\n"));
870 talloc_free(namelist);
871 return;
874 if (name_end == NULL) {
875 /* Point nameptr at the terminating '\0' */
876 nameptr += strlen(nameptr);
877 } else {
878 /* next segment please */
879 nameptr = name_end + 1;
881 i++;
884 (*ppname_array)[i].name = NULL;
886 talloc_free(namelist);
887 return;
890 #undef DBGC_CLASS
891 #define DBGC_CLASS DBGC_LOCKING
893 /****************************************************************************
894 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
895 is dealt with in posix.c
896 Returns True if we have information regarding this lock region (and returns
897 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
898 ****************************************************************************/
900 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
902 struct flock lock;
903 int ret;
905 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
906 fd,op,(double)*poffset,(double)*pcount,*ptype));
908 lock.l_type = *ptype;
909 lock.l_whence = SEEK_SET;
910 lock.l_start = *poffset;
911 lock.l_len = *pcount;
912 lock.l_pid = 0;
914 ret = sys_fcntl_ptr(fd,op,&lock);
916 if (ret == -1) {
917 int saved_errno = errno;
918 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
919 (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
920 errno = saved_errno;
921 return False;
924 *ptype = lock.l_type;
925 *poffset = lock.l_start;
926 *pcount = lock.l_len;
927 *ppid = lock.l_pid;
929 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
930 fd, (int)lock.l_type, (unsigned int)lock.l_pid));
931 return True;
934 #if defined(HAVE_OFD_LOCKS)
935 int map_process_lock_to_ofd_lock(int op)
937 switch (op) {
938 case F_GETLK:
939 case F_OFD_GETLK:
940 op = F_OFD_GETLK;
941 break;
942 case F_SETLK:
943 case F_OFD_SETLK:
944 op = F_OFD_SETLK;
945 break;
946 case F_SETLKW:
947 case F_OFD_SETLKW:
948 op = F_OFD_SETLKW;
949 break;
950 default:
951 return -1;
953 return op;
955 #else /* HAVE_OFD_LOCKS */
956 int map_process_lock_to_ofd_lock(int op)
958 return op;
960 #endif /* HAVE_OFD_LOCKS */
962 #undef DBGC_CLASS
963 #define DBGC_CLASS DBGC_ALL
965 /*******************************************************************
966 Is the name specified one of my netbios names.
967 Returns true if it is equal, false otherwise.
968 ********************************************************************/
970 static bool nb_name_equal(const char *s1, const char *s2)
972 int cmp = strncasecmp_m(s1, s2, MAX_NETBIOSNAME_LEN-1);
973 return (cmp == 0);
976 bool is_myname(const char *s)
978 const char **aliases = NULL;
979 bool ok = false;
981 ok = nb_name_equal(lp_netbios_name(), s);
982 if (ok) {
983 goto done;
986 aliases = lp_netbios_aliases();
987 if (aliases == NULL) {
988 goto done;
991 while (*aliases != NULL) {
992 ok = nb_name_equal(*aliases, s);
993 if (ok) {
994 goto done;
996 aliases += 1;
999 done:
1000 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s, (int)ok);
1001 return ok;
1004 /*******************************************************************
1005 we distinguish between 2K and XP by the "Native Lan Manager" string
1006 WinXP => "Windows 2002 5.1"
1007 WinXP 64bit => "Windows XP 5.2"
1008 Win2k => "Windows 2000 5.0"
1009 NT4 => "Windows NT 4.0"
1010 Win9x => "Windows 4.0"
1011 Windows 2003 doesn't set the native lan manager string but
1012 they do set the domain to "Windows 2003 5.2" (probably a bug).
1013 ********************************************************************/
1015 void ra_lanman_string( const char *native_lanman )
1017 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1018 set_remote_arch( RA_WINXP );
1019 else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1020 set_remote_arch( RA_WINXP64 );
1021 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1022 set_remote_arch( RA_WIN2K3 );
1025 static const char *remote_arch_strings[] = {
1026 [RA_UNKNOWN] = "UNKNOWN",
1027 [RA_WFWG] = "WfWg",
1028 [RA_OS2] = "OS2",
1029 [RA_WIN95] = "Win95",
1030 [RA_WINNT] = "WinNT",
1031 [RA_WIN2K] = "Win2K",
1032 [RA_WINXP] = "WinXP",
1033 [RA_WIN2K3] = "Win2K3",
1034 [RA_VISTA] = "Vista",
1035 [RA_SAMBA] = "Samba",
1036 [RA_CIFSFS] = "CIFSFS",
1037 [RA_WINXP64] = "WinXP64",
1038 [RA_OSX] = "OSX",
1041 const char *get_remote_arch_str(void)
1043 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1045 * set_remote_arch() already checks this so ra_type
1046 * should be in the allowed range, but anyway, let's
1047 * do another bound check here.
1049 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1050 ra_type = RA_UNKNOWN;
1052 return remote_arch_strings[ra_type];
1055 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1057 int i;
1059 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1060 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1061 return i;
1064 return RA_UNKNOWN;
1067 /*******************************************************************
1068 Set the horrid remote_arch string based on an enum.
1069 ********************************************************************/
1071 void set_remote_arch(enum remote_arch_types type)
1073 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1075 * This protects against someone adding values to enum
1076 * remote_arch_types without updating
1077 * remote_arch_strings array.
1079 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1080 ra_type = RA_UNKNOWN;
1081 return;
1084 ra_type = type;
1085 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1086 get_remote_arch_str()));
1089 /*******************************************************************
1090 Get the remote_arch type.
1091 ********************************************************************/
1093 enum remote_arch_types get_remote_arch(void)
1095 return ra_type;
1098 #define RA_CACHE_TTL 7*24*3600
1100 static bool remote_arch_cache_key(const struct GUID *client_guid,
1101 fstring key)
1103 struct GUID_txt_buf guid_buf;
1104 const char *guid_string = NULL;
1106 guid_string = GUID_buf_string(client_guid, &guid_buf);
1107 if (guid_string == NULL) {
1108 return false;
1111 fstr_sprintf(key, "RA/%s", guid_string);
1112 return true;
1115 struct ra_parser_state {
1116 bool found;
1117 enum remote_arch_types ra;
1120 static void ra_parser(const struct gencache_timeout *t,
1121 DATA_BLOB blob,
1122 void *priv_data)
1124 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1125 const char *ra_str = NULL;
1127 if (gencache_timeout_expired(t)) {
1128 return;
1131 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1132 DBG_ERR("Remote arch cache key not a string\n");
1133 return;
1136 ra_str = (const char *)blob.data;
1137 DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1139 state->ra = get_remote_arch_from_str(ra_str);
1140 state->found = true;
1141 return;
1144 static bool remote_arch_cache_get(const struct GUID *client_guid)
1146 bool ok;
1147 fstring ra_key;
1148 struct ra_parser_state state = (struct ra_parser_state) {
1149 .found = false,
1150 .ra = RA_UNKNOWN,
1153 ok = remote_arch_cache_key(client_guid, ra_key);
1154 if (!ok) {
1155 return false;
1158 ok = gencache_parse(ra_key, ra_parser, &state);
1159 if (!ok || !state.found) {
1160 return true;
1163 if (state.ra == RA_UNKNOWN) {
1164 return true;
1167 set_remote_arch(state.ra);
1168 return true;
1171 static bool remote_arch_cache_set(const struct GUID *client_guid)
1173 bool ok;
1174 fstring ra_key;
1175 const char *ra_str = NULL;
1177 if (get_remote_arch() == RA_UNKNOWN) {
1178 return true;
1181 ok = remote_arch_cache_key(client_guid, ra_key);
1182 if (!ok) {
1183 return false;
1186 ra_str = get_remote_arch_str();
1187 if (ra_str == NULL) {
1188 return false;
1191 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1192 if (!ok) {
1193 return false;
1196 return true;
1199 bool remote_arch_cache_update(const struct GUID *client_guid)
1201 bool ok;
1203 if (get_remote_arch() == RA_UNKNOWN) {
1205 become_root();
1206 ok = remote_arch_cache_get(client_guid);
1207 unbecome_root();
1209 return ok;
1212 become_root();
1213 ok = remote_arch_cache_set(client_guid);
1214 unbecome_root();
1216 return ok;
1219 bool remote_arch_cache_delete(const struct GUID *client_guid)
1221 bool ok;
1222 fstring ra_key;
1224 ok = remote_arch_cache_key(client_guid, ra_key);
1225 if (!ok) {
1226 return false;
1229 become_root();
1230 ok = gencache_del(ra_key);
1231 unbecome_root();
1233 if (!ok) {
1234 return false;
1237 return true;
1241 /*****************************************************************************
1242 Provide a checksum on a string
1244 Input: s - the null-terminated character string for which the checksum
1245 will be calculated.
1247 Output: The checksum value calculated for s.
1248 *****************************************************************************/
1250 int str_checksum(const char *s)
1252 TDB_DATA key;
1253 if (s == NULL)
1254 return 0;
1256 key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1257 .dsize = strlen(s) };
1259 return tdb_jenkins_hash(&key);
1262 /*****************************************************************
1263 Zero a memory area then free it. Used to catch bugs faster.
1264 *****************************************************************/
1266 void zero_free(void *p, size_t size)
1268 memset(p, 0, size);
1269 SAFE_FREE(p);
1272 /*****************************************************************
1273 Set our open file limit to a requested max and return the limit.
1274 *****************************************************************/
1276 int set_maxfiles(int requested_max)
1278 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1279 struct rlimit rlp;
1280 int saved_current_limit;
1282 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1283 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1284 strerror(errno) ));
1285 /* just guess... */
1286 return requested_max;
1290 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1291 * account for the extra fd we need
1292 * as well as the log files and standard
1293 * handles etc. Save the limit we want to set in case
1294 * we are running on an OS that doesn't support this limit (AIX)
1295 * which always returns RLIM_INFINITY for rlp.rlim_max.
1298 /* Try raising the hard (max) limit to the requested amount. */
1300 #if defined(RLIM_INFINITY)
1301 if (rlp.rlim_max != RLIM_INFINITY) {
1302 int orig_max = rlp.rlim_max;
1304 if ( rlp.rlim_max < requested_max )
1305 rlp.rlim_max = requested_max;
1307 /* This failing is not an error - many systems (Linux) don't
1308 support our default request of 10,000 open files. JRA. */
1310 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1311 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1312 (int)rlp.rlim_max, strerror(errno) ));
1314 /* Set failed - restore original value from get. */
1315 rlp.rlim_max = orig_max;
1318 #endif
1320 /* Now try setting the soft (current) limit. */
1322 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1324 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1325 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1326 (int)rlp.rlim_cur, strerror(errno) ));
1327 /* just guess... */
1328 return saved_current_limit;
1331 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1332 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1333 strerror(errno) ));
1334 /* just guess... */
1335 return saved_current_limit;
1338 #if defined(RLIM_INFINITY)
1339 if(rlp.rlim_cur == RLIM_INFINITY)
1340 return saved_current_limit;
1341 #endif
1343 if((int)rlp.rlim_cur > saved_current_limit)
1344 return saved_current_limit;
1346 return rlp.rlim_cur;
1347 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1349 * No way to know - just guess...
1351 return requested_max;
1352 #endif
1355 /*****************************************************************
1356 malloc that aborts with smb_panic on fail or zero size.
1357 *****************************************************************/
1359 void *smb_xmalloc_array(size_t size, unsigned int count)
1361 void *p;
1362 if (size == 0) {
1363 smb_panic("smb_xmalloc_array: called with zero size");
1365 if (count >= MAX_ALLOC_SIZE/size) {
1366 smb_panic("smb_xmalloc_array: alloc size too large");
1368 if ((p = SMB_MALLOC(size*count)) == NULL) {
1369 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1370 (unsigned long)size, (unsigned long)count));
1371 smb_panic("smb_xmalloc_array: malloc failed");
1373 return p;
1376 /*****************************************************************
1377 Get local hostname and cache result.
1378 *****************************************************************/
1380 char *myhostname(void)
1382 static char *ret;
1383 if (ret == NULL) {
1384 ret = get_myname(NULL);
1386 return ret;
1389 /*****************************************************************
1390 Get local hostname and cache result.
1391 *****************************************************************/
1393 char *myhostname_upper(void)
1395 static char *ret;
1396 if (ret == NULL) {
1397 char *name = get_myname(NULL);
1398 if (name == NULL) {
1399 return NULL;
1401 ret = strupper_talloc(NULL, name);
1402 talloc_free(name);
1404 return ret;
1407 /*******************************************************************
1408 Given a filename - get its directory name
1409 ********************************************************************/
1411 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1412 const char **name)
1414 char *p;
1415 ptrdiff_t len;
1417 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1419 if (p == NULL) {
1420 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1421 return False;
1423 if (name) {
1424 *name = dir;
1426 return True;
1429 len = p-dir;
1431 *parent = talloc_strndup(mem_ctx, dir, len);
1432 if (*parent == NULL) {
1433 return False;
1436 if (name) {
1437 *name = p+1;
1439 return True;
1442 /*******************************************************************
1443 Determine if a pattern contains any Microsoft wildcard characters.
1444 *******************************************************************/
1446 bool ms_has_wild(const char *s)
1448 const char *found = strpbrk(s, "*?<>\"");
1449 return (found != NULL);
1452 bool ms_has_wild_w(const smb_ucs2_t *s)
1454 smb_ucs2_t c;
1455 if (!s) return False;
1456 while ((c = *s++)) {
1457 switch (c) {
1458 case UCS2_CHAR('*'):
1459 case UCS2_CHAR('?'):
1460 case UCS2_CHAR('<'):
1461 case UCS2_CHAR('>'):
1462 case UCS2_CHAR('"'):
1463 return True;
1466 return False;
1469 /*******************************************************************
1470 A wrapper that handles case sensitivity and the special handling
1471 of the ".." name.
1472 *******************************************************************/
1474 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1476 if (ISDOTDOT(string))
1477 string = ".";
1478 if (ISDOT(pattern))
1479 return False;
1481 return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1484 /*******************************************************************
1485 A wrapper that handles a list of patterns and calls mask_match()
1486 on each. Returns True if any of the patterns match.
1487 *******************************************************************/
1489 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1491 while (listLen-- > 0) {
1492 if (mask_match(string, *list++, is_case_sensitive))
1493 return True;
1495 return False;
1498 /**********************************************************************
1499 Converts a name to a fully qualified domain name.
1500 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1501 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1502 canonical name of the host. getaddrinfo() may use a variety of sources
1503 including /etc/hosts to obtain the domainname. It expects aliases in
1504 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1505 ************************************************************************/
1507 bool name_to_fqdn(fstring fqdn, const char *name)
1509 char *full = NULL;
1510 struct addrinfo hints;
1511 struct addrinfo *result;
1512 int s;
1514 /* Configure hints to obtain canonical name */
1516 memset(&hints, 0, sizeof(struct addrinfo));
1517 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1518 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1519 hints.ai_flags = AI_CANONNAME; /* Get host's FQDN */
1520 hints.ai_protocol = 0; /* Any protocol */
1522 s = getaddrinfo(name, NULL, &hints, &result);
1523 if (s != 0) {
1524 DBG_WARNING("getaddrinfo lookup for %s failed: %s\n",
1525 name,
1526 gai_strerror(s));
1527 fstrcpy(fqdn, name);
1528 return false;
1530 full = result->ai_canonname;
1532 /* Find out if the FQDN is returned as an alias
1533 * to cope with /etc/hosts files where the first
1534 * name is not the FQDN but the short name.
1535 * getaddrinfo provides no easy way of handling aliases
1536 * in /etc/hosts. Users should make sure the FQDN
1537 * comes first in /etc/hosts. */
1538 if (full && (! strchr_m(full, '.'))) {
1539 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1540 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1541 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1542 DEBUGADD(1, (" prior to any aliases.\n"));
1544 if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1545 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1546 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1547 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1548 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1551 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1552 fstrcpy(fqdn, full);
1553 freeaddrinfo(result); /* No longer needed */
1554 return true;
1557 struct server_id interpret_pid(const char *pid_string)
1559 return server_id_from_string(get_my_vnn(), pid_string);
1562 /****************************************************************
1563 Check if an offset into a buffer is safe.
1564 If this returns True it's safe to indirect into the byte at
1565 pointer ptr+off.
1566 ****************************************************************/
1568 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1570 const char *end_base = buf_base + buf_len;
1571 char *end_ptr = ptr + off;
1573 if (!buf_base || !ptr) {
1574 return False;
1577 if (end_base < buf_base || end_ptr < ptr) {
1578 return False; /* wrap. */
1581 if (end_ptr < end_base) {
1582 return True;
1584 return False;
1587 /****************************************************************
1588 Return a safe pointer into a string within a buffer, or NULL.
1589 ****************************************************************/
1591 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1593 if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1594 return NULL;
1596 /* Check if a valid string exists at this offset. */
1597 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1598 return NULL;
1600 return ptr + off;
1604 /****************************************************************
1605 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1606 call (they take care of winbind separator and other winbind specific settings).
1607 ****************************************************************/
1609 bool split_domain_user(TALLOC_CTX *mem_ctx,
1610 const char *full_name,
1611 char **domain,
1612 char **user)
1614 const char *p = NULL;
1616 p = strchr_m(full_name, '\\');
1618 if (p != NULL) {
1619 *domain = talloc_strndup(mem_ctx, full_name,
1620 PTR_DIFF(p, full_name));
1621 if (*domain == NULL) {
1622 return false;
1624 *user = talloc_strdup(mem_ctx, p+1);
1625 if (*user == NULL) {
1626 TALLOC_FREE(*domain);
1627 return false;
1629 } else {
1630 *domain = NULL;
1631 *user = talloc_strdup(mem_ctx, full_name);
1632 if (*user == NULL) {
1633 return false;
1637 return true;
1640 /****************************************************************
1641 strip off leading '\\' from a hostname
1642 ****************************************************************/
1644 const char *strip_hostname(const char *s)
1646 if (!s) {
1647 return NULL;
1650 if (strlen_m(s) < 3) {
1651 return s;
1654 if (s[0] == '\\') s++;
1655 if (s[0] == '\\') s++;
1657 return s;
1660 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1662 if (!NT_STATUS_IS_OK(err1)) {
1663 *result = err1;
1664 return true;
1666 if (!NT_STATUS_IS_OK(err2)) {
1667 *result = err2;
1668 return true;
1670 return false;
1673 int timeval_to_msec(struct timeval t)
1675 return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1678 /*******************************************************************
1679 Check a given DOS pathname is valid for a share.
1680 ********************************************************************/
1682 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1684 char *ptr = NULL;
1686 if (!dos_pathname) {
1687 return NULL;
1690 ptr = talloc_strdup(ctx, dos_pathname);
1691 if (!ptr) {
1692 return NULL;
1694 /* Convert any '\' paths to '/' */
1695 unix_format(ptr);
1696 ptr = unix_clean_name(ctx, ptr);
1697 if (!ptr) {
1698 return NULL;
1701 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1702 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1703 ptr += 2;
1705 /* Only absolute paths allowed. */
1706 if (*ptr != '/')
1707 return NULL;
1709 return ptr;
1712 /*******************************************************************
1713 Return True if the filename is one of the special executable types.
1714 ********************************************************************/
1716 bool is_executable(const char *fname)
1718 if ((fname = strrchr_m(fname,'.'))) {
1719 if (strequal(fname,".com") ||
1720 strequal(fname,".dll") ||
1721 strequal(fname,".exe") ||
1722 strequal(fname,".sym")) {
1723 return True;
1726 return False;
1729 /****************************************************************************
1730 Open a file with a share mode - old openX method - map into NTCreate.
1731 ****************************************************************************/
1733 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1734 int deny_mode, int open_func,
1735 uint32_t *paccess_mask,
1736 uint32_t *pshare_mode,
1737 uint32_t *pcreate_disposition,
1738 uint32_t *pcreate_options,
1739 uint32_t *pprivate_flags)
1741 uint32_t access_mask;
1742 uint32_t share_mode;
1743 uint32_t create_disposition;
1744 uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1745 uint32_t private_flags = 0;
1747 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1748 "open_func = 0x%x\n",
1749 smb_base_fname, (unsigned int)deny_mode,
1750 (unsigned int)open_func ));
1752 /* Create the NT compatible access_mask. */
1753 switch (GET_OPENX_MODE(deny_mode)) {
1754 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1755 case DOS_OPEN_RDONLY:
1756 access_mask = FILE_GENERIC_READ;
1757 break;
1758 case DOS_OPEN_WRONLY:
1759 access_mask = FILE_GENERIC_WRITE;
1760 break;
1761 case DOS_OPEN_RDWR:
1762 case DOS_OPEN_FCB:
1763 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1764 break;
1765 default:
1766 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1767 (unsigned int)GET_OPENX_MODE(deny_mode)));
1768 return False;
1771 /* Create the NT compatible create_disposition. */
1772 switch (open_func) {
1773 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
1774 create_disposition = FILE_CREATE;
1775 break;
1777 case OPENX_FILE_EXISTS_OPEN:
1778 create_disposition = FILE_OPEN;
1779 break;
1781 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
1782 create_disposition = FILE_OPEN_IF;
1783 break;
1785 case OPENX_FILE_EXISTS_TRUNCATE:
1786 create_disposition = FILE_OVERWRITE;
1787 break;
1789 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1790 create_disposition = FILE_OVERWRITE_IF;
1791 break;
1793 default:
1794 /* From samba4 - to be confirmed. */
1795 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1796 create_disposition = FILE_CREATE;
1797 break;
1799 DEBUG(10,("map_open_params_to_ntcreate: bad "
1800 "open_func 0x%x\n", (unsigned int)open_func));
1801 return False;
1804 /* Create the NT compatible share modes. */
1805 switch (GET_DENY_MODE(deny_mode)) {
1806 case DENY_ALL:
1807 share_mode = FILE_SHARE_NONE;
1808 break;
1810 case DENY_WRITE:
1811 share_mode = FILE_SHARE_READ;
1812 break;
1814 case DENY_READ:
1815 share_mode = FILE_SHARE_WRITE;
1816 break;
1818 case DENY_NONE:
1819 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1820 break;
1822 case DENY_DOS:
1823 private_flags |= NTCREATEX_FLAG_DENY_DOS;
1824 if (is_executable(smb_base_fname)) {
1825 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1826 } else {
1827 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1828 share_mode = FILE_SHARE_READ;
1829 } else {
1830 share_mode = FILE_SHARE_NONE;
1833 break;
1835 case DENY_FCB:
1836 private_flags |= NTCREATEX_FLAG_DENY_FCB;
1837 share_mode = FILE_SHARE_NONE;
1838 break;
1840 default:
1841 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1842 (unsigned int)GET_DENY_MODE(deny_mode) ));
1843 return False;
1846 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1847 "share_mode = 0x%x, create_disposition = 0x%x, "
1848 "create_options = 0x%x private_flags = 0x%x\n",
1849 smb_base_fname,
1850 (unsigned int)access_mask,
1851 (unsigned int)share_mode,
1852 (unsigned int)create_disposition,
1853 (unsigned int)create_options,
1854 (unsigned int)private_flags));
1856 if (paccess_mask) {
1857 *paccess_mask = access_mask;
1859 if (pshare_mode) {
1860 *pshare_mode = share_mode;
1862 if (pcreate_disposition) {
1863 *pcreate_disposition = create_disposition;
1865 if (pcreate_options) {
1866 *pcreate_options = create_options;
1868 if (pprivate_flags) {
1869 *pprivate_flags = private_flags;
1872 return True;
1876 /*************************************************************************
1877 Return a talloced copy of a struct security_unix_token. NULL on fail.
1878 *************************************************************************/
1880 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
1882 struct security_unix_token *cpy;
1884 cpy = talloc(ctx, struct security_unix_token);
1885 if (!cpy) {
1886 return NULL;
1889 cpy->uid = tok->uid;
1890 cpy->gid = tok->gid;
1891 cpy->ngroups = tok->ngroups;
1892 if (tok->ngroups) {
1893 /* Make this a talloc child of cpy. */
1894 cpy->groups = (gid_t *)talloc_memdup(
1895 cpy, tok->groups, tok->ngroups * sizeof(gid_t));
1896 if (!cpy->groups) {
1897 TALLOC_FREE(cpy);
1898 return NULL;
1900 } else {
1901 cpy->groups = NULL;
1903 return cpy;
1906 /****************************************************************************
1907 Return a root token
1908 ****************************************************************************/
1910 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
1912 struct security_unix_token *t = NULL;
1914 t = talloc_zero(mem_ctx, struct security_unix_token);
1915 if (t == NULL) {
1916 return NULL;
1920 * This is not needed, but lets make it explicit, not implicit.
1922 *t = (struct security_unix_token) {
1923 .uid = 0,
1924 .gid = 0,
1925 .ngroups = 0,
1926 .groups = NULL
1929 return t;
1932 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
1934 char *str;
1935 uint32_t i;
1937 str = talloc_asprintf(
1938 mem_ctx,
1939 "uid=%ju, gid=%ju, %"PRIu32" groups:",
1940 (uintmax_t)(tok->uid),
1941 (uintmax_t)(tok->gid),
1942 tok->ngroups);
1944 for (i=0; i<tok->ngroups; i++) {
1945 talloc_asprintf_addbuf(
1946 &str, " %ju", (uintmax_t)tok->groups[i]);
1949 return str;
1952 /****************************************************************************
1953 Check that a file matches a particular file type.
1954 ****************************************************************************/
1956 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
1958 uint32_t mask;
1960 /* Check the "may have" search bits. */
1961 if (((mode & ~dirtype) &
1962 (FILE_ATTRIBUTE_HIDDEN |
1963 FILE_ATTRIBUTE_SYSTEM |
1964 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
1965 return false;
1968 /* Check the "must have" bits,
1969 which are the may have bits shifted eight */
1970 /* If must have bit is set, the file/dir can
1971 not be returned in search unless the matching
1972 file attribute is set */
1973 mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
1974 FILE_ATTRIBUTE_ARCHIVE|
1975 FILE_ATTRIBUTE_READONLY|
1976 FILE_ATTRIBUTE_HIDDEN|
1977 FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
1978 if(mask) {
1979 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
1980 FILE_ATTRIBUTE_ARCHIVE|
1981 FILE_ATTRIBUTE_READONLY|
1982 FILE_ATTRIBUTE_HIDDEN|
1983 FILE_ATTRIBUTE_SYSTEM))) == mask) {
1984 /* check if matching attribute present */
1985 return true;
1986 } else {
1987 return false;
1991 return true;