2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2007
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8 Copyright (C) James Peach 2006
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "system/passwd.h"
26 #include "system/filesys.h"
27 #include "lib/util/server_id.h"
29 #include "ctdbd_conn.h"
30 #include "../lib/util/util_pw.h"
32 #include "messages_dgm.h"
33 #include "libcli/security/security.h"
35 #include "lib/util/sys_rw.h"
36 #include "lib/util/sys_rw_data.h"
37 #include "lib/util/util_process.h"
39 #ifdef HAVE_SYS_PRCTL_H
40 #include <sys/prctl.h>
43 /* Max allowable allococation - 256mb - 0x10000000 */
44 #define MAX_ALLOC_SIZE (1024*1024*256)
46 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
47 #ifdef WITH_NISPLUS_HOME
48 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
50 * The following lines are needed due to buggy include files
51 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
52 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
53 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
54 * an enum in /usr/include/rpcsvc/nis.h.
61 #if defined(GROUP_OBJ)
65 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
67 #include <rpcsvc/nis.h>
69 #endif /* WITH_NISPLUS_HOME */
70 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
72 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
74 enum protocol_types
get_Protocol(void)
79 void set_Protocol(enum protocol_types p
)
84 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
86 void gfree_all( void )
95 /*******************************************************************
96 Check if a file exists - call vfs_file_exist for samba files.
97 ********************************************************************/
99 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
100 bool fake_dir_create_times
)
106 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
109 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
112 /*******************************************************************
113 Check if a unix domain socket exists - call vfs_file_exist for samba files.
114 ********************************************************************/
116 bool socket_exist(const char *fname
)
119 if (sys_stat(fname
, &st
, false) != 0)
122 return S_ISSOCK(st
.st_ex_mode
);
125 /*******************************************************************
126 Returns the size in bytes of the named given the stat struct.
127 ********************************************************************/
129 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
131 return sbuf
->st_ex_size
;
134 /****************************************************************************
135 Check two stats have identical dev and ino fields.
136 ****************************************************************************/
138 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
139 const SMB_STRUCT_STAT
*sbuf2
)
141 if (sbuf1
->st_ex_dev
!= sbuf2
->st_ex_dev
||
142 sbuf1
->st_ex_ino
!= sbuf2
->st_ex_ino
) {
148 /****************************************************************************
149 Check if a stat struct is identical for use.
150 ****************************************************************************/
152 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
153 const SMB_STRUCT_STAT
*sbuf2
)
155 if (sbuf1
->st_ex_uid
!= sbuf2
->st_ex_uid
||
156 sbuf1
->st_ex_gid
!= sbuf2
->st_ex_gid
||
157 !check_same_dev_ino(sbuf1
, sbuf2
)) {
163 /*******************************************************************
164 Show a smb message structure.
165 ********************************************************************/
167 void show_msg(const char *buf
)
175 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
177 (int)CVAL(buf
,smb_com
),
178 (int)CVAL(buf
,smb_rcls
),
179 (int)CVAL(buf
,smb_reh
),
180 (int)SVAL(buf
,smb_err
),
181 (int)CVAL(buf
,smb_flg
),
182 (int)SVAL(buf
,smb_flg2
)));
183 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
184 (int)SVAL(buf
,smb_tid
),
185 (int)SVAL(buf
,smb_pid
),
186 (int)SVAL(buf
,smb_uid
),
187 (int)SVAL(buf
,smb_mid
)));
188 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
190 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
191 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
192 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
194 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
196 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
204 dump_data(10, (const uint8_t *)smb_buf_const(buf
), bcc
);
207 /*******************************************************************
208 Setup only the byte count for a smb message.
209 ********************************************************************/
211 int set_message_bcc(char *buf
,int num_bytes
)
213 int num_words
= CVAL(buf
,smb_wct
);
214 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
215 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
216 return (smb_size
+ num_words
*2 + num_bytes
);
219 /*******************************************************************
220 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
221 Return the bytes added
222 ********************************************************************/
224 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
226 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
229 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
230 DEBUG(0, ("talloc failed\n"));
235 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
236 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
240 /*******************************************************************
241 Reduce a file name, removing .. elements.
242 ********************************************************************/
244 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
249 DEBUG(3,("dos_clean_name [%s]\n",s
));
251 /* remove any double slashes */
252 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
257 /* Remove leading .\\ characters */
258 if(strncmp(str
, ".\\", 2) == 0) {
259 trim_string(str
, ".\\", NULL
);
261 str
= talloc_strdup(ctx
, ".\\");
268 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
274 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
279 str
= talloc_asprintf(ctx
,
288 trim_string(str
,NULL
,"\\..");
289 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
292 /*******************************************************************
293 Reduce a file name, removing .. elements.
294 ********************************************************************/
296 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
301 DEBUG(3,("unix_clean_name [%s]\n",s
));
303 /* remove any double slashes */
304 str
= talloc_all_string_sub(ctx
, s
, "//","/");
309 /* Remove leading ./ characters */
310 if(strncmp(str
, "./", 2) == 0) {
311 trim_string(str
, "./", NULL
);
313 str
= talloc_strdup(ctx
, "./");
320 while ((p
= strstr_m(str
,"/../")) != NULL
) {
326 if ((p
=strrchr_m(str
,'/')) != NULL
) {
331 str
= talloc_asprintf(ctx
,
340 trim_string(str
,NULL
,"/..");
341 return talloc_all_string_sub(ctx
, str
, "/./", "/");
344 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
346 char *str
= dos_clean_name(ctx
, s
);
350 return unix_clean_name(ctx
, str
);
353 /*******************************************************************
354 Write data into an fd at a given offset. Ignore seek errors.
355 ********************************************************************/
357 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
362 if (pos
== (off_t
)-1) {
363 return write_data(fd
, buffer
, N
);
365 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
367 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
368 if (ret
== -1 && errno
== ESPIPE
) {
369 return write_data(fd
, buffer
+ total
,N
- total
);
372 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
381 return (ssize_t
)total
;
383 /* Use lseek and write_data. */
384 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
385 if (errno
!= ESPIPE
) {
389 return write_data(fd
, buffer
, N
);
393 static int reinit_after_fork_pipe
[2] = { -1, -1 };
395 NTSTATUS
init_before_fork(void)
399 ret
= pipe(reinit_after_fork_pipe
);
403 status
= map_nt_error_from_unix_common(errno
);
405 DEBUG(0, ("Error creating child_pipe: %s\n",
415 * Detect died parent by detecting EOF on the pipe
417 static void reinit_after_fork_pipe_handler(struct tevent_context
*ev
,
418 struct tevent_fd
*fde
,
424 if (sys_read(reinit_after_fork_pipe
[0], &c
, 1) != 1) {
426 * we have reached EOF on stdin, which means the
427 * parent has exited. Shutdown the server
429 (void)kill(getpid(), SIGTERM
);
434 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
435 struct tevent_context
*ev_ctx
,
436 bool parent_longlived
,
439 NTSTATUS status
= NT_STATUS_OK
;
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
;
453 if (ev_ctx
!= NULL
) {
454 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
455 if (tevent_re_initialise(ev_ctx
) != 0) {
456 smb_panic(__location__
": Failed to re-initialise event context");
460 if (reinit_after_fork_pipe
[0] != -1) {
461 struct tevent_fd
*fde
;
463 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
464 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
465 reinit_after_fork_pipe_handler
, NULL
);
467 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
473 * For clustering, we need to re-init our ctdbd connection after the
476 status
= messaging_reinit(msg_ctx
);
477 if (!NT_STATUS_IS_OK(status
)) {
478 DEBUG(0,("messaging_reinit() failed: %s\n",
484 prctl_set_comment(comment
);
491 /****************************************************************************
492 (Hopefully) efficient array append.
493 ****************************************************************************/
495 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
496 void *element
, void *_array
, uint32_t *num_elements
,
499 void **array
= (void **)_array
;
501 if (*array_size
< 0) {
505 if (*array
== NULL
) {
506 if (*array_size
== 0) {
510 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
514 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
515 if (*array
== NULL
) {
520 if (*num_elements
== *array_size
) {
523 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
527 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
528 element_size
* (*array_size
));
530 if (*array
== NULL
) {
535 memcpy((char *)(*array
) + element_size
*(*num_elements
),
536 element
, element_size
);
546 /****************************************************************************
547 Get my own domain name, or "" if we have none.
548 ****************************************************************************/
550 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
555 domname
= get_mydnsfullname();
560 p
= strchr_m(domname
, '.');
563 return talloc_strdup(ctx
, p
);
565 return talloc_strdup(ctx
, "");
569 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
570 /******************************************************************
571 Remove any mount options such as -rsize=2048,wsize=2048 etc.
572 Based on a fix from <Thomas.Hepper@icem.de>.
573 Returns a malloc'ed string.
574 *******************************************************************/
576 static char *strip_mount_options(TALLOC_CTX
*ctx
, const char *str
)
580 while(*p
&& !isspace(*p
))
582 while(*p
&& isspace(*p
))
585 return talloc_strdup(ctx
, p
);
591 /*******************************************************************
592 Patch from jkf@soton.ac.uk
593 Split Luke's automount_server into YP lookup and string splitter
594 so can easily implement automount_path().
595 Returns a malloc'ed string.
596 *******************************************************************/
598 #ifdef WITH_NISPLUS_HOME
599 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
603 char *nis_map
= (char *)lp_homedir_map();
605 char buffer
[NIS_MAXATTRVAL
+ 1];
610 snprintf(buffer
, sizeof(buffer
), "[key=%s],%s", user_name
, nis_map
);
611 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
613 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
)) {
614 if (result
->status
!= NIS_SUCCESS
) {
615 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
617 object
= result
->objects
.objects_val
;
618 if (object
->zo_data
.zo_type
== ENTRY_OBJ
) {
619 entry
= &object
->zo_data
.objdata_u
.en_data
;
620 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
621 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
623 value
= talloc_strdup(ctx
,
624 entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
626 nis_freeresult(result
);
629 value
= talloc_string_sub(ctx
,
636 nis_freeresult(result
);
639 value
= strip_mount_options(ctx
, value
);
640 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
645 #else /* WITH_NISPLUS_HOME */
647 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
651 int nis_error
; /* returned by yp all functions */
652 char *nis_result
; /* yp_match inits this */
653 int nis_result_len
; /* and set this */
654 char *nis_domain
; /* yp_get_default_domain inits this */
655 char *nis_map
= lp_homedir_map(talloc_tos());
657 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
658 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
662 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
664 if ((nis_error
= yp_match(nis_domain
, nis_map
, user_name
,
665 strlen(user_name
), &nis_result
,
666 &nis_result_len
)) == 0) {
667 if (nis_result_len
> 0 && nis_result
[nis_result_len
] == '\n') {
668 nis_result
[nis_result_len
] = '\0';
670 value
= talloc_strdup(ctx
, nis_result
);
674 value
= strip_mount_options(ctx
, value
);
675 } else if(nis_error
== YPERR_KEY
) {
676 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
677 user_name
, nis_map
));
678 DEBUG(3, ("using defaults for server and home directory\n"));
680 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
681 yperr_string(nis_error
), user_name
, nis_map
));
685 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, value
));
689 #endif /* WITH_NISPLUS_HOME */
692 bool process_exists(const struct server_id pid
)
694 return serverid_exists(&pid
);
697 /*******************************************************************
698 Convert a uid into a user name.
699 ********************************************************************/
701 const char *uidtoname(uid_t uid
)
703 TALLOC_CTX
*ctx
= talloc_tos();
705 struct passwd
*pass
= NULL
;
707 pass
= getpwuid_alloc(ctx
,uid
);
709 name
= talloc_strdup(ctx
,pass
->pw_name
);
712 name
= talloc_asprintf(ctx
,
719 /*******************************************************************
720 Convert a gid into a group name.
721 ********************************************************************/
723 char *gidtoname(gid_t gid
)
729 return talloc_strdup(talloc_tos(), grp
->gr_name
);
732 return talloc_asprintf(talloc_tos(),
738 /*******************************************************************
739 Convert a user name into a uid.
740 ********************************************************************/
742 uid_t
nametouid(const char *name
)
748 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
755 u
= (uid_t
)strtol(name
, &p
, 0);
756 if ((p
!= name
) && (*p
== '\0'))
762 /*******************************************************************
763 Convert a name to a gid_t if possible. Return -1 if not a group.
764 ********************************************************************/
766 gid_t
nametogid(const char *name
)
772 g
= (gid_t
)strtol(name
, &p
, 0);
773 if ((p
!= name
) && (*p
== '\0'))
776 grp
= getgrnam(name
);
782 /*******************************************************************
783 Something really nasty happened - panic !
784 ********************************************************************/
786 void smb_panic_s3(const char *why
)
791 DEBUG(0,("PANIC (pid %llu): %s\n",
792 (unsigned long long)getpid(), why
));
795 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
797 * Make sure all children can attach a debugger.
799 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
802 cmd
= lp_panic_action(talloc_tos());
804 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd
));
805 result
= system(cmd
);
808 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
811 DEBUG(0, ("smb_panic(): action returned status %d\n",
812 WEXITSTATUS(result
)));
818 /*******************************************************************
819 Print a backtrace of the stack to the debug log. This function
820 DELIBERATELY LEAKS MEMORY. The expectation is that you should
821 exit shortly after calling it.
822 ********************************************************************/
824 #ifdef HAVE_LIBUNWIND_H
825 #include <libunwind.h>
828 #ifdef HAVE_EXECINFO_H
829 #include <execinfo.h>
836 void log_stack_trace(void)
838 #ifdef HAVE_LIBUNWIND
839 /* Try to use libunwind before any other technique since on ia64
840 * libunwind correctly walks the stack in more circumstances than
848 unw_word_t ip
, sp
, off
;
850 procname
[sizeof(procname
) - 1] = '\0';
852 if (unw_getcontext(&uc
) != 0) {
853 goto libunwind_failed
;
856 if (unw_init_local(&cursor
, &uc
) != 0) {
857 goto libunwind_failed
;
860 DEBUG(0, ("BACKTRACE:\n"));
864 unw_get_reg(&cursor
, UNW_REG_IP
, &ip
);
865 unw_get_reg(&cursor
, UNW_REG_SP
, &sp
);
867 switch (unw_get_proc_name(&cursor
,
868 procname
, sizeof(procname
) - 1, &off
) ) {
872 /* Name truncated. */
873 DEBUGADD(0, (" #%u %s + %#llx [ip=%#llx] [sp=%#llx]\n",
874 i
, procname
, (long long)off
,
875 (long long)ip
, (long long) sp
));
878 /* case -UNW_ENOINFO: */
879 /* case -UNW_EUNSPEC: */
880 /* No symbol name found. */
881 DEBUGADD(0, (" #%u %s [ip=%#llx] [sp=%#llx]\n",
882 i
, "<unknown symbol>",
883 (long long)ip
, (long long) sp
));
886 } while (unw_step(&cursor
) > 0);
891 DEBUG(0, ("unable to produce a stack trace with libunwind\n"));
893 #elif HAVE_BACKTRACE_SYMBOLS
894 void *backtrace_stack
[BACKTRACE_STACK_SIZE
];
895 size_t backtrace_size
;
896 char **backtrace_strings
;
898 /* get the backtrace (stack frames) */
899 backtrace_size
= backtrace(backtrace_stack
,BACKTRACE_STACK_SIZE
);
900 backtrace_strings
= backtrace_symbols(backtrace_stack
, backtrace_size
);
902 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
903 (unsigned long)backtrace_size
));
905 if (backtrace_strings
) {
908 for (i
= 0; i
< backtrace_size
; i
++)
909 DEBUGADD(0, (" #%u %s\n", i
, backtrace_strings
[i
]));
911 /* Leak the backtrace_strings, rather than risk what free() might do */
916 /* The IRIX libexc library provides an API for unwinding the stack. See
917 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
918 * since we are about to abort anyway, it hardly matters.
921 #define NAMESIZE 32 /* Arbitrary */
923 __uint64_t addrs
[BACKTRACE_STACK_SIZE
];
924 char * names
[BACKTRACE_STACK_SIZE
];
925 char namebuf
[BACKTRACE_STACK_SIZE
* NAMESIZE
];
934 /* We need to be root so we can open our /proc entry to walk
935 * our stack. It also helps when we want to dump core.
939 for (i
= 0; i
< BACKTRACE_STACK_SIZE
; i
++) {
940 names
[i
] = namebuf
+ (i
* NAMESIZE
);
943 levels
= trace_back_stack(0, addrs
, names
,
944 BACKTRACE_STACK_SIZE
, NAMESIZE
- 1);
946 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels
));
947 for (i
= 0; i
< levels
; i
++) {
948 DEBUGADD(0, (" #%d 0x%llx %s\n", i
, addrs
[i
], names
[i
]));
953 DEBUG(0, ("unable to produce a stack trace on this platform\n"));
957 /*******************************************************************
958 A readdir wrapper which just returns the file name.
959 ********************************************************************/
961 const char *readdirname(DIR *p
)
969 ptr
= (struct dirent
*)readdir(p
);
980 #ifdef HAVE_BROKEN_READDIR_NAME
981 /* using /usr/ucb/cc is BAD */
985 return talloc_strdup(talloc_tos(), dname
);
988 /*******************************************************************
989 Utility function used to decide if the last component
990 of a path matches a (possibly wildcarded) entry in a namelist.
991 ********************************************************************/
993 bool is_in_path(const char *name
, name_compare_entry
*namelist
, bool case_sensitive
)
995 const char *last_component
;
997 /* if we have no list it's obviously not in the path */
998 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
))) {
1002 DEBUG(8, ("is_in_path: %s\n", name
));
1004 /* Get the last component of the unix name. */
1005 last_component
= strrchr_m(name
, '/');
1006 if (!last_component
) {
1007 last_component
= name
;
1009 last_component
++; /* Go past '/' */
1012 for(; namelist
->name
!= NULL
; namelist
++) {
1013 if(namelist
->is_wild
) {
1014 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
1015 DEBUG(8,("is_in_path: mask match succeeded\n"));
1019 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
1020 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
1021 DEBUG(8,("is_in_path: match succeeded\n"));
1026 DEBUG(8,("is_in_path: match not found\n"));
1030 /*******************************************************************
1031 Strip a '/' separated list into an array of
1032 name_compare_enties structures suitable for
1033 passing to is_in_path(). We do this for
1034 speed so we can pre-parse all the names in the list
1035 and don't do it for each call to is_in_path().
1036 We also check if the entry contains a wildcard to
1037 remove a potentially expensive call to mask_match
1039 ********************************************************************/
1041 void set_namearray(name_compare_entry
**ppname_array
, const char *namelist_in
)
1047 int num_entries
= 0;
1050 (*ppname_array
) = NULL
;
1052 if((namelist_in
== NULL
) || ((namelist_in
!= NULL
) && (*namelist_in
== '\0')))
1055 namelist
= talloc_strdup(talloc_tos(), namelist_in
);
1056 if (namelist
== NULL
) {
1057 DEBUG(0,("set_namearray: talloc fail\n"));
1062 namelist_end
= &namelist
[strlen(namelist
)];
1064 /* We need to make two passes over the string. The
1065 first to count the number of elements, the second
1069 while(nameptr
<= namelist_end
) {
1070 if ( *nameptr
== '/' ) {
1071 /* cope with multiple (useless) /s) */
1075 /* anything left? */
1076 if ( *nameptr
== '\0' )
1079 /* find the next '/' or consume remaining */
1080 name_end
= strchr_m(nameptr
, '/');
1081 if (name_end
== NULL
) {
1082 /* Point nameptr at the terminating '\0' */
1083 nameptr
+= strlen(nameptr
);
1085 /* next segment please */
1086 nameptr
= name_end
+ 1;
1091 if(num_entries
== 0) {
1092 talloc_free(namelist
);
1096 if(( (*ppname_array
) = SMB_MALLOC_ARRAY(name_compare_entry
, num_entries
+ 1)) == NULL
) {
1097 DEBUG(0,("set_namearray: malloc fail\n"));
1098 talloc_free(namelist
);
1102 /* Now copy out the names */
1105 while(nameptr
<= namelist_end
) {
1106 if ( *nameptr
== '/' ) {
1107 /* cope with multiple (useless) /s) */
1111 /* anything left? */
1112 if ( *nameptr
== '\0' )
1115 /* find the next '/' or consume remaining */
1116 name_end
= strchr_m(nameptr
, '/');
1117 if (name_end
!= NULL
) {
1121 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1122 if(((*ppname_array
)[i
].name
= SMB_STRDUP(nameptr
)) == NULL
) {
1123 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1124 talloc_free(namelist
);
1128 if (name_end
== NULL
) {
1129 /* Point nameptr at the terminating '\0' */
1130 nameptr
+= strlen(nameptr
);
1132 /* next segment please */
1133 nameptr
= name_end
+ 1;
1138 (*ppname_array
)[i
].name
= NULL
;
1140 talloc_free(namelist
);
1145 #define DBGC_CLASS DBGC_LOCKING
1147 /****************************************************************************
1148 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1149 is dealt with in posix.c
1150 Returns True if we have information regarding this lock region (and returns
1151 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1152 ****************************************************************************/
1154 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
1159 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1160 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
1162 lock
.l_type
= *ptype
;
1163 lock
.l_whence
= SEEK_SET
;
1164 lock
.l_start
= *poffset
;
1165 lock
.l_len
= *pcount
;
1168 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
1172 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1173 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
1178 *ptype
= lock
.l_type
;
1179 *poffset
= lock
.l_start
;
1180 *pcount
= lock
.l_len
;
1183 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1184 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
1188 #if defined(HAVE_OFD_LOCKS)
1189 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1205 *use_ofd_locks
= false;
1208 *use_ofd_locks
= true;
1211 #else /* HAVE_OFD_LOCKS */
1212 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1214 *use_ofd_locks
= false;
1217 #endif /* HAVE_OFD_LOCKS */
1220 #define DBGC_CLASS DBGC_ALL
1222 /*******************************************************************
1223 Is the name specified one of my netbios names.
1224 Returns true if it is equal, false otherwise.
1225 ********************************************************************/
1227 bool is_myname(const char *s
)
1232 for (n
=0; my_netbios_names(n
); n
++) {
1233 const char *nbt_name
= my_netbios_names(n
);
1235 if (strncasecmp_m(nbt_name
, s
, MAX_NETBIOSNAME_LEN
-1) == 0) {
1240 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1244 /*******************************************************************
1245 we distinguish between 2K and XP by the "Native Lan Manager" string
1246 WinXP => "Windows 2002 5.1"
1247 WinXP 64bit => "Windows XP 5.2"
1248 Win2k => "Windows 2000 5.0"
1249 NT4 => "Windows NT 4.0"
1250 Win9x => "Windows 4.0"
1251 Windows 2003 doesn't set the native lan manager string but
1252 they do set the domain to "Windows 2003 5.2" (probably a bug).
1253 ********************************************************************/
1255 void ra_lanman_string( const char *native_lanman
)
1257 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
1258 set_remote_arch( RA_WINXP
);
1259 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
1260 set_remote_arch( RA_WINXP64
);
1261 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
1262 set_remote_arch( RA_WIN2K3
);
1265 static const char *remote_arch_strings
[] = {
1266 [RA_UNKNOWN
] = "UNKNOWN",
1269 [RA_WIN95
] = "Win95",
1270 [RA_WINNT
] = "WinNT",
1271 [RA_WIN2K
] = "Win2K",
1272 [RA_WINXP
] = "WinXP",
1273 [RA_WIN2K3
] = "Win2K3",
1274 [RA_VISTA
] = "Vista",
1275 [RA_SAMBA
] = "Samba",
1276 [RA_CIFSFS
] = "CIFSFS",
1277 [RA_WINXP64
] = "WinXP64",
1281 const char *get_remote_arch_str(void)
1283 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1285 * set_remote_arch() already checks this so ra_type
1286 * should be in the allowed range, but anyway, let's
1287 * do another bound check here.
1289 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1290 ra_type
= RA_UNKNOWN
;
1292 return remote_arch_strings
[ra_type
];
1295 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
1299 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
1300 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
1307 /*******************************************************************
1308 Set the horrid remote_arch string based on an enum.
1309 ********************************************************************/
1311 void set_remote_arch(enum remote_arch_types type
)
1313 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1315 * This protects against someone adding values to enum
1316 * remote_arch_types without updating
1317 * remote_arch_strings array.
1319 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1320 ra_type
= RA_UNKNOWN
;
1325 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1326 get_remote_arch_str()));
1329 /*******************************************************************
1330 Get the remote_arch type.
1331 ********************************************************************/
1333 enum remote_arch_types
get_remote_arch(void)
1338 #define RA_CACHE_TTL 7*24*3600
1340 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1343 struct GUID_txt_buf guid_buf
;
1344 const char *guid_string
= NULL
;
1346 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1347 if (guid_string
== NULL
) {
1351 fstr_sprintf(key
, "RA/%s", guid_string
);
1355 struct ra_parser_state
{
1357 enum remote_arch_types ra
;
1360 static void ra_parser(time_t timeout
, DATA_BLOB blob
, void *priv_data
)
1362 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1363 const char *ra_str
= NULL
;
1365 if (timeout
<= time(NULL
)) {
1369 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1370 DBG_ERR("Remote arch cache key not a string\n");
1374 ra_str
= (const char *)blob
.data
;
1375 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1377 state
->ra
= get_remote_arch_from_str(ra_str
);
1378 state
->found
= true;
1382 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1386 struct ra_parser_state state
= (struct ra_parser_state
) {
1391 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1396 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1397 if (!ok
|| !state
.found
) {
1401 if (state
.ra
== RA_UNKNOWN
) {
1405 set_remote_arch(state
.ra
);
1409 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1413 const char *ra_str
= NULL
;
1415 if (get_remote_arch() == RA_UNKNOWN
) {
1419 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1424 ra_str
= get_remote_arch_str();
1425 if (ra_str
== NULL
) {
1429 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1437 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1441 if (get_remote_arch() == RA_UNKNOWN
) {
1444 ok
= remote_arch_cache_get(client_guid
);
1451 ok
= remote_arch_cache_set(client_guid
);
1457 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1462 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1468 ok
= gencache_del(ra_key
);
1478 const char *tab_depth(int level
, int depth
)
1480 if( CHECK_DEBUGLVL(level
) ) {
1481 dbgtext("%*s", depth
*4, "");
1486 /*****************************************************************************
1487 Provide a checksum on a string
1489 Input: s - the null-terminated character string for which the checksum
1492 Output: The checksum value calculated for s.
1493 *****************************************************************************/
1495 int str_checksum(const char *s
)
1501 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1502 .dsize
= strlen(s
) };
1504 return tdb_jenkins_hash(&key
);
1507 /*****************************************************************
1508 Zero a memory area then free it. Used to catch bugs faster.
1509 *****************************************************************/
1511 void zero_free(void *p
, size_t size
)
1517 /*****************************************************************
1518 Set our open file limit to a requested max and return the limit.
1519 *****************************************************************/
1521 int set_maxfiles(int requested_max
)
1523 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1525 int saved_current_limit
;
1527 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1528 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1531 return requested_max
;
1535 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1536 * account for the extra fd we need
1537 * as well as the log files and standard
1538 * handles etc. Save the limit we want to set in case
1539 * we are running on an OS that doesn't support this limit (AIX)
1540 * which always returns RLIM_INFINITY for rlp.rlim_max.
1543 /* Try raising the hard (max) limit to the requested amount. */
1545 #if defined(RLIM_INFINITY)
1546 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1547 int orig_max
= rlp
.rlim_max
;
1549 if ( rlp
.rlim_max
< requested_max
)
1550 rlp
.rlim_max
= requested_max
;
1552 /* This failing is not an error - many systems (Linux) don't
1553 support our default request of 10,000 open files. JRA. */
1555 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1556 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1557 (int)rlp
.rlim_max
, strerror(errno
) ));
1559 /* Set failed - restore original value from get. */
1560 rlp
.rlim_max
= orig_max
;
1565 /* Now try setting the soft (current) limit. */
1567 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1569 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1570 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1571 (int)rlp
.rlim_cur
, strerror(errno
) ));
1573 return saved_current_limit
;
1576 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1577 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1580 return saved_current_limit
;
1583 #if defined(RLIM_INFINITY)
1584 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1585 return saved_current_limit
;
1588 if((int)rlp
.rlim_cur
> saved_current_limit
)
1589 return saved_current_limit
;
1591 return rlp
.rlim_cur
;
1592 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1594 * No way to know - just guess...
1596 return requested_max
;
1600 /*****************************************************************
1601 malloc that aborts with smb_panic on fail or zero size.
1602 *****************************************************************/
1604 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1608 smb_panic("smb_xmalloc_array: called with zero size");
1610 if (count
>= MAX_ALLOC_SIZE
/size
) {
1611 smb_panic("smb_xmalloc_array: alloc size too large");
1613 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1614 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1615 (unsigned long)size
, (unsigned long)count
));
1616 smb_panic("smb_xmalloc_array: malloc failed");
1622 vasprintf that aborts on malloc fail
1625 int smb_xvasprintf(char **ptr
, const char *format
, va_list ap
)
1632 n
= vasprintf(ptr
, format
, ap2
);
1634 if (n
== -1 || ! *ptr
) {
1635 smb_panic("smb_xvasprintf: out of memory");
1640 /*****************************************************************
1641 Get local hostname and cache result.
1642 *****************************************************************/
1644 char *myhostname(void)
1648 ret
= get_myname(NULL
);
1653 /*****************************************************************
1654 Get local hostname and cache result.
1655 *****************************************************************/
1657 char *myhostname_upper(void)
1661 char *name
= get_myname(NULL
);
1665 ret
= strupper_talloc(NULL
, name
);
1671 /*******************************************************************
1672 Given a filename - get its directory name
1673 ********************************************************************/
1675 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1681 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1684 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1695 if (!(*parent
= (char *)talloc_memdup(mem_ctx
, dir
, len
+1))) {
1698 (*parent
)[len
] = '\0';
1706 /*******************************************************************
1707 Determine if a pattern contains any Microsoft wildcard characters.
1708 *******************************************************************/
1710 bool ms_has_wild(const char *s
)
1714 while ((c
= *s
++)) {
1727 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1730 if (!s
) return False
;
1731 while ((c
= *s
++)) {
1733 case UCS2_CHAR('*'):
1734 case UCS2_CHAR('?'):
1735 case UCS2_CHAR('<'):
1736 case UCS2_CHAR('>'):
1737 case UCS2_CHAR('"'):
1744 /*******************************************************************
1745 A wrapper that handles case sensitivity and the special handling
1747 *******************************************************************/
1749 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1751 if (ISDOTDOT(string
))
1756 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1759 /*******************************************************************
1760 A wrapper that handles case sensitivity and the special handling
1761 of the ".." name. Varient that is only called by old search code which requires
1762 pattern translation.
1763 *******************************************************************/
1765 bool mask_match_search(const char *string
, const char *pattern
, bool is_case_sensitive
)
1767 if (ISDOTDOT(string
))
1772 return ms_fnmatch(pattern
, string
, True
, is_case_sensitive
) == 0;
1775 /*******************************************************************
1776 A wrapper that handles a list of patters and calls mask_match()
1777 on each. Returns True if any of the patterns match.
1778 *******************************************************************/
1780 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1782 while (listLen
-- > 0) {
1783 if (mask_match(string
, *list
++, is_case_sensitive
))
1789 /**********************************************************************
1790 Converts a name to a fully qualified domain name.
1791 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1792 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1793 canonical name of the host. getaddrinfo() may use a variety of sources
1794 including /etc/hosts to obtain the domainname. It expects aliases in
1795 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1796 ************************************************************************/
1798 bool name_to_fqdn(fstring fqdn
, const char *name
)
1801 struct addrinfo hints
;
1802 struct addrinfo
*result
;
1805 /* Configure hints to obtain canonical name */
1807 memset(&hints
, 0, sizeof(struct addrinfo
));
1808 hints
.ai_family
= AF_UNSPEC
; /* Allow IPv4 or IPv6 */
1809 hints
.ai_socktype
= SOCK_DGRAM
; /* Datagram socket */
1810 hints
.ai_flags
= AI_CANONNAME
; /* Get host's FQDN */
1811 hints
.ai_protocol
= 0; /* Any protocol */
1813 s
= getaddrinfo(name
, NULL
, &hints
, &result
);
1815 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s
)));
1816 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name
));
1817 fstrcpy(fqdn
, name
);
1820 full
= result
->ai_canonname
;
1822 /* Find out if the FQDN is returned as an alias
1823 * to cope with /etc/hosts files where the first
1824 * name is not the FQDN but the short name.
1825 * getaddrinfo provides no easy way of handling aliases
1826 * in /etc/hosts. Users should make sure the FQDN
1827 * comes first in /etc/hosts. */
1828 if (full
&& (! strchr_m(full
, '.'))) {
1829 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1830 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1831 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1832 DEBUGADD(1, (" prior to any aliases.\n"));
1834 if (full
&& (strcasecmp_m(full
, "localhost.localdomain") == 0)) {
1835 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1836 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1837 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1838 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1841 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name
, full
));
1842 fstrcpy(fqdn
, full
);
1843 freeaddrinfo(result
); /* No longer needed */
1847 uint32_t map_share_mode_to_deny_mode(uint32_t share_access
, uint32_t private_options
)
1849 switch (share_access
& ~FILE_SHARE_DELETE
) {
1850 case FILE_SHARE_NONE
:
1852 case FILE_SHARE_READ
:
1854 case FILE_SHARE_WRITE
:
1856 case FILE_SHARE_READ
|FILE_SHARE_WRITE
:
1859 if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
) {
1861 } else if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
) {
1865 return (uint32_t)-1;
1868 struct server_id
interpret_pid(const char *pid_string
)
1870 return server_id_from_string(get_my_vnn(), pid_string
);
1873 /****************************************************************
1874 Check if an offset into a buffer is safe.
1875 If this returns True it's safe to indirect into the byte at
1877 ****************************************************************/
1879 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1881 const char *end_base
= buf_base
+ buf_len
;
1882 char *end_ptr
= ptr
+ off
;
1884 if (!buf_base
|| !ptr
) {
1888 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1889 return False
; /* wrap. */
1892 if (end_ptr
< end_base
) {
1898 /****************************************************************
1899 Return a safe pointer into a buffer, or NULL.
1900 ****************************************************************/
1902 char *get_safe_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1904 return is_offset_safe(buf_base
, buf_len
, ptr
, off
) ?
1908 /****************************************************************
1909 Return a safe pointer into a string within a buffer, or NULL.
1910 ****************************************************************/
1912 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1914 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1917 /* Check if a valid string exists at this offset. */
1918 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1924 /****************************************************************
1925 Return an SVAL at a pointer, or failval if beyond the end.
1926 ****************************************************************/
1928 int get_safe_SVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1931 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1934 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+1)) {
1937 return SVAL(ptr
,off
);
1940 /****************************************************************
1941 Return an IVAL at a pointer, or failval if beyond the end.
1942 ****************************************************************/
1944 int get_safe_IVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1947 * Note we use off+3 here, not off+4 as IVAL accesses
1948 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1950 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+3)) {
1953 return IVAL(ptr
,off
);
1956 /****************************************************************
1957 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1958 call (they take care of winbind separator and other winbind specific settings).
1959 ****************************************************************/
1961 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1962 const char *full_name
,
1966 const char *p
= NULL
;
1968 p
= strchr_m(full_name
, '\\');
1971 *domain
= talloc_strndup(mem_ctx
, full_name
,
1972 PTR_DIFF(p
, full_name
));
1973 if (*domain
== NULL
) {
1976 *user
= talloc_strdup(mem_ctx
, p
+1);
1977 if (*user
== NULL
) {
1978 TALLOC_FREE(*domain
);
1983 *user
= talloc_strdup(mem_ctx
, full_name
);
1984 if (*user
== NULL
) {
1992 /****************************************************************
1993 strip off leading '\\' from a hostname
1994 ****************************************************************/
1996 const char *strip_hostname(const char *s
)
2002 if (strlen_m(s
) < 3) {
2006 if (s
[0] == '\\') s
++;
2007 if (s
[0] == '\\') s
++;
2012 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
2014 if (!NT_STATUS_IS_OK(err1
)) {
2018 if (!NT_STATUS_IS_OK(err2
)) {
2025 int timeval_to_msec(struct timeval t
)
2027 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
2030 /*******************************************************************
2031 Check a given DOS pathname is valid for a share.
2032 ********************************************************************/
2034 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
2038 if (!dos_pathname
) {
2042 ptr
= talloc_strdup(ctx
, dos_pathname
);
2046 /* Convert any '\' paths to '/' */
2048 ptr
= unix_clean_name(ctx
, ptr
);
2053 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
2054 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
2057 /* Only absolute paths allowed. */
2064 /*******************************************************************
2065 Return True if the filename is one of the special executable types.
2066 ********************************************************************/
2068 bool is_executable(const char *fname
)
2070 if ((fname
= strrchr_m(fname
,'.'))) {
2071 if (strequal(fname
,".com") ||
2072 strequal(fname
,".dll") ||
2073 strequal(fname
,".exe") ||
2074 strequal(fname
,".sym")) {
2081 /****************************************************************************
2082 Open a file with a share mode - old openX method - map into NTCreate.
2083 ****************************************************************************/
2085 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
2086 int deny_mode
, int open_func
,
2087 uint32_t *paccess_mask
,
2088 uint32_t *pshare_mode
,
2089 uint32_t *pcreate_disposition
,
2090 uint32_t *pcreate_options
,
2091 uint32_t *pprivate_flags
)
2093 uint32_t access_mask
;
2094 uint32_t share_mode
;
2095 uint32_t create_disposition
;
2096 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
2097 uint32_t private_flags
= 0;
2099 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
2100 "open_func = 0x%x\n",
2101 smb_base_fname
, (unsigned int)deny_mode
,
2102 (unsigned int)open_func
));
2104 /* Create the NT compatible access_mask. */
2105 switch (GET_OPENX_MODE(deny_mode
)) {
2106 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
2107 case DOS_OPEN_RDONLY
:
2108 access_mask
= FILE_GENERIC_READ
;
2110 case DOS_OPEN_WRONLY
:
2111 access_mask
= FILE_GENERIC_WRITE
;
2115 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
2118 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
2119 (unsigned int)GET_OPENX_MODE(deny_mode
)));
2123 /* Create the NT compatible create_disposition. */
2124 switch (open_func
) {
2125 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2126 create_disposition
= FILE_CREATE
;
2129 case OPENX_FILE_EXISTS_OPEN
:
2130 create_disposition
= FILE_OPEN
;
2133 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2134 create_disposition
= FILE_OPEN_IF
;
2137 case OPENX_FILE_EXISTS_TRUNCATE
:
2138 create_disposition
= FILE_OVERWRITE
;
2141 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2142 create_disposition
= FILE_OVERWRITE_IF
;
2146 /* From samba4 - to be confirmed. */
2147 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
2148 create_disposition
= FILE_CREATE
;
2151 DEBUG(10,("map_open_params_to_ntcreate: bad "
2152 "open_func 0x%x\n", (unsigned int)open_func
));
2156 /* Create the NT compatible share modes. */
2157 switch (GET_DENY_MODE(deny_mode
)) {
2159 share_mode
= FILE_SHARE_NONE
;
2163 share_mode
= FILE_SHARE_READ
;
2167 share_mode
= FILE_SHARE_WRITE
;
2171 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2175 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
;
2176 if (is_executable(smb_base_fname
)) {
2177 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2179 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
2180 share_mode
= FILE_SHARE_READ
;
2182 share_mode
= FILE_SHARE_NONE
;
2188 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
;
2189 share_mode
= FILE_SHARE_NONE
;
2193 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2194 (unsigned int)GET_DENY_MODE(deny_mode
) ));
2198 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2199 "share_mode = 0x%x, create_disposition = 0x%x, "
2200 "create_options = 0x%x private_flags = 0x%x\n",
2202 (unsigned int)access_mask
,
2203 (unsigned int)share_mode
,
2204 (unsigned int)create_disposition
,
2205 (unsigned int)create_options
,
2206 (unsigned int)private_flags
));
2209 *paccess_mask
= access_mask
;
2212 *pshare_mode
= share_mode
;
2214 if (pcreate_disposition
) {
2215 *pcreate_disposition
= create_disposition
;
2217 if (pcreate_options
) {
2218 *pcreate_options
= create_options
;
2220 if (pprivate_flags
) {
2221 *pprivate_flags
= private_flags
;
2228 /*************************************************************************
2229 Return a talloced copy of a struct security_unix_token. NULL on fail.
2230 *************************************************************************/
2232 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
2234 struct security_unix_token
*cpy
;
2236 cpy
= talloc(ctx
, struct security_unix_token
);
2241 cpy
->uid
= tok
->uid
;
2242 cpy
->gid
= tok
->gid
;
2243 cpy
->ngroups
= tok
->ngroups
;
2245 /* Make this a talloc child of cpy. */
2246 cpy
->groups
= (gid_t
*)talloc_memdup(
2247 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
2258 /****************************************************************************
2259 Check that a file matches a particular file type.
2260 ****************************************************************************/
2262 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
2266 /* Check the "may have" search bits. */
2267 if (((mode
& ~dirtype
) &
2268 (FILE_ATTRIBUTE_HIDDEN
|
2269 FILE_ATTRIBUTE_SYSTEM
|
2270 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
2274 /* Check the "must have" bits,
2275 which are the may have bits shifted eight */
2276 /* If must have bit is set, the file/dir can
2277 not be returned in search unless the matching
2278 file attribute is set */
2279 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
2280 FILE_ATTRIBUTE_ARCHIVE
|
2281 FILE_ATTRIBUTE_READONLY
|
2282 FILE_ATTRIBUTE_HIDDEN
|
2283 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
2285 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
2286 FILE_ATTRIBUTE_ARCHIVE
|
2287 FILE_ATTRIBUTE_READONLY
|
2288 FILE_ATTRIBUTE_HIDDEN
|
2289 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
2290 /* check if matching attribute present */