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"
38 #include "lib/dbwrap/dbwrap_ctdb.h"
40 #ifdef HAVE_SYS_PRCTL_H
41 #include <sys/prctl.h>
44 /* Max allowable allococation - 256mb - 0x10000000 */
45 #define MAX_ALLOC_SIZE (1024*1024*256)
47 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
48 /* rpc/xdr.h uses TRUE and FALSE */
57 #include "system/nis.h"
59 #ifdef WITH_NISPLUS_HOME
60 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
62 * The following lines are needed due to buggy include files
63 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
64 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
65 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
66 * an enum in /usr/include/rpcsvc/nis.h.
73 #if defined(GROUP_OBJ)
77 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
79 #include <rpcsvc/nis.h>
81 #endif /* WITH_NISPLUS_HOME */
82 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
84 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
86 enum protocol_types
get_Protocol(void)
91 void set_Protocol(enum protocol_types p
)
96 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
98 void gfree_all( void )
107 /*******************************************************************
108 Check if a file exists - call vfs_file_exist for samba files.
109 ********************************************************************/
111 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
112 bool fake_dir_create_times
)
118 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
121 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
124 /*******************************************************************
125 Check if a unix domain socket exists - call vfs_file_exist for samba files.
126 ********************************************************************/
128 bool socket_exist(const char *fname
)
131 if (sys_stat(fname
, &st
, false) != 0)
134 return S_ISSOCK(st
.st_ex_mode
);
137 /*******************************************************************
138 Returns the size in bytes of the named given the stat struct.
139 ********************************************************************/
141 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
143 return sbuf
->st_ex_size
;
146 /****************************************************************************
147 Check two stats have identical dev and ino fields.
148 ****************************************************************************/
150 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
151 const SMB_STRUCT_STAT
*sbuf2
)
153 if (sbuf1
->st_ex_dev
!= sbuf2
->st_ex_dev
||
154 sbuf1
->st_ex_ino
!= sbuf2
->st_ex_ino
) {
160 /****************************************************************************
161 Check if a stat struct is identical for use.
162 ****************************************************************************/
164 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
165 const SMB_STRUCT_STAT
*sbuf2
)
167 if (sbuf1
->st_ex_uid
!= sbuf2
->st_ex_uid
||
168 sbuf1
->st_ex_gid
!= sbuf2
->st_ex_gid
||
169 !check_same_dev_ino(sbuf1
, sbuf2
)) {
175 /*******************************************************************
176 Show a smb message structure.
177 ********************************************************************/
179 void show_msg(const char *buf
)
187 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
189 (int)CVAL(buf
,smb_com
),
190 (int)CVAL(buf
,smb_rcls
),
191 (int)CVAL(buf
,smb_reh
),
192 (int)SVAL(buf
,smb_err
),
193 (int)CVAL(buf
,smb_flg
),
194 (int)SVAL(buf
,smb_flg2
)));
195 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
196 (int)SVAL(buf
,smb_tid
),
197 (int)SVAL(buf
,smb_pid
),
198 (int)SVAL(buf
,smb_uid
),
199 (int)SVAL(buf
,smb_mid
)));
200 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
202 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
203 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
204 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
206 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
208 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
216 dump_data(10, (const uint8_t *)smb_buf_const(buf
), bcc
);
219 /*******************************************************************
220 Setup only the byte count for a smb message.
221 ********************************************************************/
223 int set_message_bcc(char *buf
,int num_bytes
)
225 int num_words
= CVAL(buf
,smb_wct
);
226 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
227 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
228 return (smb_size
+ num_words
*2 + num_bytes
);
231 /*******************************************************************
232 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
233 Return the bytes added
234 ********************************************************************/
236 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
238 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
241 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
242 DEBUG(0, ("talloc failed\n"));
247 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
248 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
252 /*******************************************************************
253 Reduce a file name, removing .. elements.
254 ********************************************************************/
256 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
261 DEBUG(3,("dos_clean_name [%s]\n",s
));
263 /* remove any double slashes */
264 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
269 /* Remove leading .\\ characters */
270 if(strncmp(str
, ".\\", 2) == 0) {
271 trim_string(str
, ".\\", NULL
);
273 str
= talloc_strdup(ctx
, ".\\");
280 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
286 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
291 str
= talloc_asprintf(ctx
,
300 trim_string(str
,NULL
,"\\..");
301 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
304 /*******************************************************************
305 Reduce a file name, removing .. elements.
306 ********************************************************************/
308 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
313 DEBUG(3,("unix_clean_name [%s]\n",s
));
315 /* remove any double slashes */
316 str
= talloc_all_string_sub(ctx
, s
, "//","/");
321 /* Remove leading ./ characters */
322 if(strncmp(str
, "./", 2) == 0) {
323 trim_string(str
, "./", NULL
);
325 str
= talloc_strdup(ctx
, "./");
332 while ((p
= strstr_m(str
,"/../")) != NULL
) {
338 if ((p
=strrchr_m(str
,'/')) != NULL
) {
343 str
= talloc_asprintf(ctx
,
352 trim_string(str
,NULL
,"/..");
353 return talloc_all_string_sub(ctx
, str
, "/./", "/");
356 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
358 char *str
= dos_clean_name(ctx
, s
);
362 return unix_clean_name(ctx
, str
);
365 /*******************************************************************
366 Write data into an fd at a given offset. Ignore seek errors.
367 ********************************************************************/
369 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
374 if (pos
== (off_t
)-1) {
375 return write_data(fd
, buffer
, N
);
377 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
379 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
380 if (ret
== -1 && errno
== ESPIPE
) {
381 return write_data(fd
, buffer
+ total
,N
- total
);
384 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
393 return (ssize_t
)total
;
395 /* Use lseek and write_data. */
396 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
397 if (errno
!= ESPIPE
) {
401 return write_data(fd
, buffer
, N
);
405 static int reinit_after_fork_pipe
[2] = { -1, -1 };
407 NTSTATUS
init_before_fork(void)
411 ret
= pipe(reinit_after_fork_pipe
);
415 status
= map_nt_error_from_unix_common(errno
);
417 DEBUG(0, ("Error creating child_pipe: %s\n",
427 * Detect died parent by detecting EOF on the pipe
429 static void reinit_after_fork_pipe_handler(struct tevent_context
*ev
,
430 struct tevent_fd
*fde
,
436 if (sys_read(reinit_after_fork_pipe
[0], &c
, 1) != 1) {
438 * we have reached EOF on stdin, which means the
439 * parent has exited. Shutdown the server
441 (void)kill(getpid(), SIGTERM
);
446 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
447 struct tevent_context
*ev_ctx
,
448 bool parent_longlived
,
451 NTSTATUS status
= NT_STATUS_OK
;
454 if (reinit_after_fork_pipe
[1] != -1) {
455 close(reinit_after_fork_pipe
[1]);
456 reinit_after_fork_pipe
[1] = -1;
459 /* tdb needs special fork handling */
460 if (tdb_reopen_all(parent_longlived
? 1 : 0) != 0) {
461 DEBUG(0,("tdb_reopen_all failed.\n"));
462 status
= NT_STATUS_OPEN_FAILED
;
466 if (ev_ctx
!= NULL
) {
467 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
468 if (tevent_re_initialise(ev_ctx
) != 0) {
469 smb_panic(__location__
": Failed to re-initialise event context");
473 if (reinit_after_fork_pipe
[0] != -1) {
474 struct tevent_fd
*fde
;
476 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
477 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
478 reinit_after_fork_pipe_handler
, NULL
);
480 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
486 * For clustering, we need to re-init our ctdbd connection after the
489 status
= messaging_reinit(msg_ctx
);
490 if (!NT_STATUS_IS_OK(status
)) {
491 DEBUG(0,("messaging_reinit() failed: %s\n",
495 if (lp_clustering()) {
496 ret
= ctdb_async_ctx_reinit(
497 NULL
, messaging_tevent_context(msg_ctx
));
499 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
501 return map_nt_error_from_unix(ret
);
507 prctl_set_comment(comment
);
514 /****************************************************************************
515 (Hopefully) efficient array append.
516 ****************************************************************************/
518 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
519 void *element
, void *_array
, uint32_t *num_elements
,
522 void **array
= (void **)_array
;
524 if (*array_size
< 0) {
528 if (*array
== NULL
) {
529 if (*array_size
== 0) {
533 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
537 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
538 if (*array
== NULL
) {
543 if (*num_elements
== *array_size
) {
546 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
550 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
551 element_size
* (*array_size
));
553 if (*array
== NULL
) {
558 memcpy((char *)(*array
) + element_size
*(*num_elements
),
559 element
, element_size
);
569 /****************************************************************************
570 Get my own domain name, or "" if we have none.
571 ****************************************************************************/
573 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
578 domname
= get_mydnsfullname();
583 p
= strchr_m(domname
, '.');
586 return talloc_strdup(ctx
, p
);
588 return talloc_strdup(ctx
, "");
592 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
593 /******************************************************************
594 Remove any mount options such as -rsize=2048,wsize=2048 etc.
595 Based on a fix from <Thomas.Hepper@icem.de>.
596 Returns a malloc'ed string.
597 *******************************************************************/
599 static char *strip_mount_options(TALLOC_CTX
*ctx
, const char *str
)
603 while(*p
&& !isspace(*p
))
605 while(*p
&& isspace(*p
))
608 return talloc_strdup(ctx
, p
);
614 /*******************************************************************
615 Patch from jkf@soton.ac.uk
616 Split Luke's automount_server into YP lookup and string splitter
617 so can easily implement automount_path().
618 Returns a malloc'ed string.
619 *******************************************************************/
621 #ifdef WITH_NISPLUS_HOME
622 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
626 char *nis_map
= (char *)lp_homedir_map();
628 char buffer
[NIS_MAXATTRVAL
+ 1];
633 snprintf(buffer
, sizeof(buffer
), "[key=%s],%s", user_name
, nis_map
);
634 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
636 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
)) {
637 if (result
->status
!= NIS_SUCCESS
) {
638 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
640 object
= result
->objects
.objects_val
;
641 if (object
->zo_data
.zo_type
== ENTRY_OBJ
) {
642 entry
= &object
->zo_data
.objdata_u
.en_data
;
643 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
644 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
646 value
= talloc_strdup(ctx
,
647 entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
649 nis_freeresult(result
);
652 value
= talloc_string_sub(ctx
,
659 nis_freeresult(result
);
662 value
= strip_mount_options(ctx
, value
);
663 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
668 #else /* WITH_NISPLUS_HOME */
670 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
674 int nis_error
; /* returned by yp all functions */
675 char *nis_result
; /* yp_match inits this */
676 int nis_result_len
; /* and set this */
677 char *nis_domain
; /* yp_get_default_domain inits this */
678 char *nis_map
= lp_homedir_map(talloc_tos());
680 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
681 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
685 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
687 if ((nis_error
= yp_match(nis_domain
, nis_map
, user_name
,
688 strlen(user_name
), &nis_result
,
689 &nis_result_len
)) == 0) {
690 if (nis_result_len
> 0 && nis_result
[nis_result_len
] == '\n') {
691 nis_result
[nis_result_len
] = '\0';
693 value
= talloc_strdup(ctx
, nis_result
);
697 value
= strip_mount_options(ctx
, value
);
698 } else if(nis_error
== YPERR_KEY
) {
699 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
700 user_name
, nis_map
));
701 DEBUG(3, ("using defaults for server and home directory\n"));
703 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
704 yperr_string(nis_error
), user_name
, nis_map
));
708 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, value
));
712 #endif /* WITH_NISPLUS_HOME */
715 bool process_exists(const struct server_id pid
)
717 return serverid_exists(&pid
);
720 /*******************************************************************
721 Convert a uid into a user name.
722 ********************************************************************/
724 const char *uidtoname(uid_t uid
)
726 TALLOC_CTX
*ctx
= talloc_tos();
728 struct passwd
*pass
= NULL
;
730 pass
= getpwuid_alloc(ctx
,uid
);
732 name
= talloc_strdup(ctx
,pass
->pw_name
);
735 name
= talloc_asprintf(ctx
,
742 /*******************************************************************
743 Convert a gid into a group name.
744 ********************************************************************/
746 char *gidtoname(gid_t gid
)
752 return talloc_strdup(talloc_tos(), grp
->gr_name
);
755 return talloc_asprintf(talloc_tos(),
761 /*******************************************************************
762 Convert a user name into a uid.
763 ********************************************************************/
765 uid_t
nametouid(const char *name
)
771 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
778 u
= (uid_t
)strtol(name
, &p
, 0);
779 if ((p
!= name
) && (*p
== '\0'))
785 /*******************************************************************
786 Convert a name to a gid_t if possible. Return -1 if not a group.
787 ********************************************************************/
789 gid_t
nametogid(const char *name
)
795 g
= (gid_t
)strtol(name
, &p
, 0);
796 if ((p
!= name
) && (*p
== '\0'))
799 grp
= getgrnam(name
);
805 /*******************************************************************
806 Something really nasty happened - panic !
807 ********************************************************************/
809 void smb_panic_s3(const char *why
)
814 DEBUG(0,("PANIC (pid %llu): %s\n",
815 (unsigned long long)getpid(), why
));
818 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
820 * Make sure all children can attach a debugger.
822 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
825 cmd
= lp_panic_action(talloc_tos());
827 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd
));
828 result
= system(cmd
);
831 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
834 DEBUG(0, ("smb_panic(): action returned status %d\n",
835 WEXITSTATUS(result
)));
841 /*******************************************************************
842 Print a backtrace of the stack to the debug log. This function
843 DELIBERATELY LEAKS MEMORY. The expectation is that you should
844 exit shortly after calling it.
845 ********************************************************************/
847 #ifdef HAVE_LIBUNWIND_H
848 #include <libunwind.h>
851 #ifdef HAVE_EXECINFO_H
852 #include <execinfo.h>
859 void log_stack_trace(void)
861 #ifdef HAVE_LIBUNWIND
862 /* Try to use libunwind before any other technique since on ia64
863 * libunwind correctly walks the stack in more circumstances than
871 unw_word_t ip
, sp
, off
;
873 procname
[sizeof(procname
) - 1] = '\0';
875 if (unw_getcontext(&uc
) != 0) {
876 goto libunwind_failed
;
879 if (unw_init_local(&cursor
, &uc
) != 0) {
880 goto libunwind_failed
;
883 DEBUG(0, ("BACKTRACE:\n"));
887 unw_get_reg(&cursor
, UNW_REG_IP
, &ip
);
888 unw_get_reg(&cursor
, UNW_REG_SP
, &sp
);
890 switch (unw_get_proc_name(&cursor
,
891 procname
, sizeof(procname
) - 1, &off
) ) {
895 /* Name truncated. */
896 DEBUGADD(0, (" #%u %s + %#llx [ip=%#llx] [sp=%#llx]\n",
897 i
, procname
, (long long)off
,
898 (long long)ip
, (long long) sp
));
901 /* case -UNW_ENOINFO: */
902 /* case -UNW_EUNSPEC: */
903 /* No symbol name found. */
904 DEBUGADD(0, (" #%u %s [ip=%#llx] [sp=%#llx]\n",
905 i
, "<unknown symbol>",
906 (long long)ip
, (long long) sp
));
909 } while (unw_step(&cursor
) > 0);
914 DEBUG(0, ("unable to produce a stack trace with libunwind\n"));
916 #elif HAVE_BACKTRACE_SYMBOLS
917 void *backtrace_stack
[BACKTRACE_STACK_SIZE
];
918 size_t backtrace_size
;
919 char **backtrace_strings
;
921 /* get the backtrace (stack frames) */
922 backtrace_size
= backtrace(backtrace_stack
,BACKTRACE_STACK_SIZE
);
923 backtrace_strings
= backtrace_symbols(backtrace_stack
, backtrace_size
);
925 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
926 (unsigned long)backtrace_size
));
928 if (backtrace_strings
) {
931 for (i
= 0; i
< backtrace_size
; i
++)
932 DEBUGADD(0, (" #%u %s\n", i
, backtrace_strings
[i
]));
934 /* Leak the backtrace_strings, rather than risk what free() might do */
939 /* The IRIX libexc library provides an API for unwinding the stack. See
940 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
941 * since we are about to abort anyway, it hardly matters.
944 #define NAMESIZE 32 /* Arbitrary */
946 __uint64_t addrs
[BACKTRACE_STACK_SIZE
];
947 char * names
[BACKTRACE_STACK_SIZE
];
948 char namebuf
[BACKTRACE_STACK_SIZE
* NAMESIZE
];
957 /* We need to be root so we can open our /proc entry to walk
958 * our stack. It also helps when we want to dump core.
962 for (i
= 0; i
< BACKTRACE_STACK_SIZE
; i
++) {
963 names
[i
] = namebuf
+ (i
* NAMESIZE
);
966 levels
= trace_back_stack(0, addrs
, names
,
967 BACKTRACE_STACK_SIZE
, NAMESIZE
- 1);
969 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels
));
970 for (i
= 0; i
< levels
; i
++) {
971 DEBUGADD(0, (" #%d 0x%llx %s\n", i
, addrs
[i
], names
[i
]));
976 DEBUG(0, ("unable to produce a stack trace on this platform\n"));
980 /*******************************************************************
981 A readdir wrapper which just returns the file name.
982 ********************************************************************/
984 const char *readdirname(DIR *p
)
992 ptr
= (struct dirent
*)readdir(p
);
1003 #ifdef HAVE_BROKEN_READDIR_NAME
1004 /* using /usr/ucb/cc is BAD */
1008 return talloc_strdup(talloc_tos(), dname
);
1011 /*******************************************************************
1012 Utility function used to decide if the last component
1013 of a path matches a (possibly wildcarded) entry in a namelist.
1014 ********************************************************************/
1016 bool is_in_path(const char *name
, name_compare_entry
*namelist
, bool case_sensitive
)
1018 const char *last_component
;
1020 /* if we have no list it's obviously not in the path */
1021 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
))) {
1025 DEBUG(8, ("is_in_path: %s\n", name
));
1027 /* Get the last component of the unix name. */
1028 last_component
= strrchr_m(name
, '/');
1029 if (!last_component
) {
1030 last_component
= name
;
1032 last_component
++; /* Go past '/' */
1035 for(; namelist
->name
!= NULL
; namelist
++) {
1036 if(namelist
->is_wild
) {
1037 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
1038 DEBUG(8,("is_in_path: mask match succeeded\n"));
1042 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
1043 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
1044 DEBUG(8,("is_in_path: match succeeded\n"));
1049 DEBUG(8,("is_in_path: match not found\n"));
1053 /*******************************************************************
1054 Strip a '/' separated list into an array of
1055 name_compare_enties structures suitable for
1056 passing to is_in_path(). We do this for
1057 speed so we can pre-parse all the names in the list
1058 and don't do it for each call to is_in_path().
1059 We also check if the entry contains a wildcard to
1060 remove a potentially expensive call to mask_match
1062 ********************************************************************/
1064 void set_namearray(name_compare_entry
**ppname_array
, const char *namelist_in
)
1070 int num_entries
= 0;
1073 (*ppname_array
) = NULL
;
1075 if((namelist_in
== NULL
) || ((namelist_in
!= NULL
) && (*namelist_in
== '\0')))
1078 namelist
= talloc_strdup(talloc_tos(), namelist_in
);
1079 if (namelist
== NULL
) {
1080 DEBUG(0,("set_namearray: talloc fail\n"));
1085 namelist_end
= &namelist
[strlen(namelist
)];
1087 /* We need to make two passes over the string. The
1088 first to count the number of elements, the second
1092 while(nameptr
<= namelist_end
) {
1093 if ( *nameptr
== '/' ) {
1094 /* cope with multiple (useless) /s) */
1098 /* anything left? */
1099 if ( *nameptr
== '\0' )
1102 /* find the next '/' or consume remaining */
1103 name_end
= strchr_m(nameptr
, '/');
1104 if (name_end
== NULL
) {
1105 /* Point nameptr at the terminating '\0' */
1106 nameptr
+= strlen(nameptr
);
1108 /* next segment please */
1109 nameptr
= name_end
+ 1;
1114 if(num_entries
== 0) {
1115 talloc_free(namelist
);
1119 if(( (*ppname_array
) = SMB_MALLOC_ARRAY(name_compare_entry
, num_entries
+ 1)) == NULL
) {
1120 DEBUG(0,("set_namearray: malloc fail\n"));
1121 talloc_free(namelist
);
1125 /* Now copy out the names */
1128 while(nameptr
<= namelist_end
) {
1129 if ( *nameptr
== '/' ) {
1130 /* cope with multiple (useless) /s) */
1134 /* anything left? */
1135 if ( *nameptr
== '\0' )
1138 /* find the next '/' or consume remaining */
1139 name_end
= strchr_m(nameptr
, '/');
1140 if (name_end
!= NULL
) {
1144 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1145 if(((*ppname_array
)[i
].name
= SMB_STRDUP(nameptr
)) == NULL
) {
1146 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1147 talloc_free(namelist
);
1151 if (name_end
== NULL
) {
1152 /* Point nameptr at the terminating '\0' */
1153 nameptr
+= strlen(nameptr
);
1155 /* next segment please */
1156 nameptr
= name_end
+ 1;
1161 (*ppname_array
)[i
].name
= NULL
;
1163 talloc_free(namelist
);
1168 #define DBGC_CLASS DBGC_LOCKING
1170 /****************************************************************************
1171 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1172 is dealt with in posix.c
1173 Returns True if we have information regarding this lock region (and returns
1174 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1175 ****************************************************************************/
1177 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
1182 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1183 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
1185 lock
.l_type
= *ptype
;
1186 lock
.l_whence
= SEEK_SET
;
1187 lock
.l_start
= *poffset
;
1188 lock
.l_len
= *pcount
;
1191 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
1195 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1196 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
1201 *ptype
= lock
.l_type
;
1202 *poffset
= lock
.l_start
;
1203 *pcount
= lock
.l_len
;
1206 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1207 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
1211 #if defined(HAVE_OFD_LOCKS)
1212 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1228 *use_ofd_locks
= false;
1231 *use_ofd_locks
= true;
1234 #else /* HAVE_OFD_LOCKS */
1235 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1237 *use_ofd_locks
= false;
1240 #endif /* HAVE_OFD_LOCKS */
1243 #define DBGC_CLASS DBGC_ALL
1245 /*******************************************************************
1246 Is the name specified one of my netbios names.
1247 Returns true if it is equal, false otherwise.
1248 ********************************************************************/
1250 bool is_myname(const char *s
)
1255 for (n
=0; my_netbios_names(n
); n
++) {
1256 const char *nbt_name
= my_netbios_names(n
);
1258 if (strncasecmp_m(nbt_name
, s
, MAX_NETBIOSNAME_LEN
-1) == 0) {
1263 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1267 /*******************************************************************
1268 we distinguish between 2K and XP by the "Native Lan Manager" string
1269 WinXP => "Windows 2002 5.1"
1270 WinXP 64bit => "Windows XP 5.2"
1271 Win2k => "Windows 2000 5.0"
1272 NT4 => "Windows NT 4.0"
1273 Win9x => "Windows 4.0"
1274 Windows 2003 doesn't set the native lan manager string but
1275 they do set the domain to "Windows 2003 5.2" (probably a bug).
1276 ********************************************************************/
1278 void ra_lanman_string( const char *native_lanman
)
1280 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
1281 set_remote_arch( RA_WINXP
);
1282 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
1283 set_remote_arch( RA_WINXP64
);
1284 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
1285 set_remote_arch( RA_WIN2K3
);
1288 static const char *remote_arch_strings
[] = {
1289 [RA_UNKNOWN
] = "UNKNOWN",
1292 [RA_WIN95
] = "Win95",
1293 [RA_WINNT
] = "WinNT",
1294 [RA_WIN2K
] = "Win2K",
1295 [RA_WINXP
] = "WinXP",
1296 [RA_WIN2K3
] = "Win2K3",
1297 [RA_VISTA
] = "Vista",
1298 [RA_SAMBA
] = "Samba",
1299 [RA_CIFSFS
] = "CIFSFS",
1300 [RA_WINXP64
] = "WinXP64",
1304 const char *get_remote_arch_str(void)
1306 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1308 * set_remote_arch() already checks this so ra_type
1309 * should be in the allowed range, but anyway, let's
1310 * do another bound check here.
1312 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1313 ra_type
= RA_UNKNOWN
;
1315 return remote_arch_strings
[ra_type
];
1318 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
1322 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
1323 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
1330 /*******************************************************************
1331 Set the horrid remote_arch string based on an enum.
1332 ********************************************************************/
1334 void set_remote_arch(enum remote_arch_types type
)
1336 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1338 * This protects against someone adding values to enum
1339 * remote_arch_types without updating
1340 * remote_arch_strings array.
1342 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1343 ra_type
= RA_UNKNOWN
;
1348 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1349 get_remote_arch_str()));
1352 /*******************************************************************
1353 Get the remote_arch type.
1354 ********************************************************************/
1356 enum remote_arch_types
get_remote_arch(void)
1361 #define RA_CACHE_TTL 7*24*3600
1363 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1366 struct GUID_txt_buf guid_buf
;
1367 const char *guid_string
= NULL
;
1369 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1370 if (guid_string
== NULL
) {
1374 fstr_sprintf(key
, "RA/%s", guid_string
);
1378 struct ra_parser_state
{
1380 enum remote_arch_types ra
;
1383 static void ra_parser(time_t timeout
, DATA_BLOB blob
, void *priv_data
)
1385 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1386 const char *ra_str
= NULL
;
1388 if (timeout
<= time(NULL
)) {
1392 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1393 DBG_ERR("Remote arch cache key not a string\n");
1397 ra_str
= (const char *)blob
.data
;
1398 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1400 state
->ra
= get_remote_arch_from_str(ra_str
);
1401 state
->found
= true;
1405 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1409 struct ra_parser_state state
= (struct ra_parser_state
) {
1414 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1419 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1420 if (!ok
|| !state
.found
) {
1424 if (state
.ra
== RA_UNKNOWN
) {
1428 set_remote_arch(state
.ra
);
1432 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1436 const char *ra_str
= NULL
;
1438 if (get_remote_arch() == RA_UNKNOWN
) {
1442 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1447 ra_str
= get_remote_arch_str();
1448 if (ra_str
== NULL
) {
1452 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1460 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1464 if (get_remote_arch() == RA_UNKNOWN
) {
1467 ok
= remote_arch_cache_get(client_guid
);
1474 ok
= remote_arch_cache_set(client_guid
);
1480 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1485 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1491 ok
= gencache_del(ra_key
);
1501 const char *tab_depth(int level
, int depth
)
1503 if( CHECK_DEBUGLVL(level
) ) {
1504 dbgtext("%*s", depth
*4, "");
1509 /*****************************************************************************
1510 Provide a checksum on a string
1512 Input: s - the null-terminated character string for which the checksum
1515 Output: The checksum value calculated for s.
1516 *****************************************************************************/
1518 int str_checksum(const char *s
)
1524 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1525 .dsize
= strlen(s
) };
1527 return tdb_jenkins_hash(&key
);
1530 /*****************************************************************
1531 Zero a memory area then free it. Used to catch bugs faster.
1532 *****************************************************************/
1534 void zero_free(void *p
, size_t size
)
1540 /*****************************************************************
1541 Set our open file limit to a requested max and return the limit.
1542 *****************************************************************/
1544 int set_maxfiles(int requested_max
)
1546 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1548 int saved_current_limit
;
1550 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1551 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1554 return requested_max
;
1558 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1559 * account for the extra fd we need
1560 * as well as the log files and standard
1561 * handles etc. Save the limit we want to set in case
1562 * we are running on an OS that doesn't support this limit (AIX)
1563 * which always returns RLIM_INFINITY for rlp.rlim_max.
1566 /* Try raising the hard (max) limit to the requested amount. */
1568 #if defined(RLIM_INFINITY)
1569 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1570 int orig_max
= rlp
.rlim_max
;
1572 if ( rlp
.rlim_max
< requested_max
)
1573 rlp
.rlim_max
= requested_max
;
1575 /* This failing is not an error - many systems (Linux) don't
1576 support our default request of 10,000 open files. JRA. */
1578 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1579 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1580 (int)rlp
.rlim_max
, strerror(errno
) ));
1582 /* Set failed - restore original value from get. */
1583 rlp
.rlim_max
= orig_max
;
1588 /* Now try setting the soft (current) limit. */
1590 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1592 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1593 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1594 (int)rlp
.rlim_cur
, strerror(errno
) ));
1596 return saved_current_limit
;
1599 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1600 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1603 return saved_current_limit
;
1606 #if defined(RLIM_INFINITY)
1607 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1608 return saved_current_limit
;
1611 if((int)rlp
.rlim_cur
> saved_current_limit
)
1612 return saved_current_limit
;
1614 return rlp
.rlim_cur
;
1615 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1617 * No way to know - just guess...
1619 return requested_max
;
1623 /*****************************************************************
1624 malloc that aborts with smb_panic on fail or zero size.
1625 *****************************************************************/
1627 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1631 smb_panic("smb_xmalloc_array: called with zero size");
1633 if (count
>= MAX_ALLOC_SIZE
/size
) {
1634 smb_panic("smb_xmalloc_array: alloc size too large");
1636 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1637 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1638 (unsigned long)size
, (unsigned long)count
));
1639 smb_panic("smb_xmalloc_array: malloc failed");
1645 vasprintf that aborts on malloc fail
1648 int smb_xvasprintf(char **ptr
, const char *format
, va_list ap
)
1655 n
= vasprintf(ptr
, format
, ap2
);
1657 if (n
== -1 || ! *ptr
) {
1658 smb_panic("smb_xvasprintf: out of memory");
1663 /*****************************************************************
1664 Get local hostname and cache result.
1665 *****************************************************************/
1667 char *myhostname(void)
1671 ret
= get_myname(NULL
);
1676 /*****************************************************************
1677 Get local hostname and cache result.
1678 *****************************************************************/
1680 char *myhostname_upper(void)
1684 char *name
= get_myname(NULL
);
1688 ret
= strupper_talloc(NULL
, name
);
1694 /*******************************************************************
1695 Given a filename - get its directory name
1696 ********************************************************************/
1698 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1704 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1707 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1718 if (!(*parent
= (char *)talloc_memdup(mem_ctx
, dir
, len
+1))) {
1721 (*parent
)[len
] = '\0';
1729 /*******************************************************************
1730 Determine if a pattern contains any Microsoft wildcard characters.
1731 *******************************************************************/
1733 bool ms_has_wild(const char *s
)
1737 while ((c
= *s
++)) {
1750 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1753 if (!s
) return False
;
1754 while ((c
= *s
++)) {
1756 case UCS2_CHAR('*'):
1757 case UCS2_CHAR('?'):
1758 case UCS2_CHAR('<'):
1759 case UCS2_CHAR('>'):
1760 case UCS2_CHAR('"'):
1767 /*******************************************************************
1768 A wrapper that handles case sensitivity and the special handling
1770 *******************************************************************/
1772 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1774 if (ISDOTDOT(string
))
1779 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1782 /*******************************************************************
1783 A wrapper that handles case sensitivity and the special handling
1784 of the ".." name. Varient that is only called by old search code which requires
1785 pattern translation.
1786 *******************************************************************/
1788 bool mask_match_search(const char *string
, const char *pattern
, bool is_case_sensitive
)
1790 if (ISDOTDOT(string
))
1795 return ms_fnmatch(pattern
, string
, True
, is_case_sensitive
) == 0;
1798 /*******************************************************************
1799 A wrapper that handles a list of patters and calls mask_match()
1800 on each. Returns True if any of the patterns match.
1801 *******************************************************************/
1803 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1805 while (listLen
-- > 0) {
1806 if (mask_match(string
, *list
++, is_case_sensitive
))
1812 /**********************************************************************
1813 Converts a name to a fully qualified domain name.
1814 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1815 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1816 canonical name of the host. getaddrinfo() may use a variety of sources
1817 including /etc/hosts to obtain the domainname. It expects aliases in
1818 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1819 ************************************************************************/
1821 bool name_to_fqdn(fstring fqdn
, const char *name
)
1824 struct addrinfo hints
;
1825 struct addrinfo
*result
;
1828 /* Configure hints to obtain canonical name */
1830 memset(&hints
, 0, sizeof(struct addrinfo
));
1831 hints
.ai_family
= AF_UNSPEC
; /* Allow IPv4 or IPv6 */
1832 hints
.ai_socktype
= SOCK_DGRAM
; /* Datagram socket */
1833 hints
.ai_flags
= AI_CANONNAME
; /* Get host's FQDN */
1834 hints
.ai_protocol
= 0; /* Any protocol */
1836 s
= getaddrinfo(name
, NULL
, &hints
, &result
);
1838 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s
)));
1839 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name
));
1840 fstrcpy(fqdn
, name
);
1843 full
= result
->ai_canonname
;
1845 /* Find out if the FQDN is returned as an alias
1846 * to cope with /etc/hosts files where the first
1847 * name is not the FQDN but the short name.
1848 * getaddrinfo provides no easy way of handling aliases
1849 * in /etc/hosts. Users should make sure the FQDN
1850 * comes first in /etc/hosts. */
1851 if (full
&& (! strchr_m(full
, '.'))) {
1852 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1853 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1854 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1855 DEBUGADD(1, (" prior to any aliases.\n"));
1857 if (full
&& (strcasecmp_m(full
, "localhost.localdomain") == 0)) {
1858 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1859 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1860 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1861 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1864 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name
, full
));
1865 fstrcpy(fqdn
, full
);
1866 freeaddrinfo(result
); /* No longer needed */
1870 uint32_t map_share_mode_to_deny_mode(uint32_t share_access
, uint32_t private_options
)
1872 switch (share_access
& ~FILE_SHARE_DELETE
) {
1873 case FILE_SHARE_NONE
:
1875 case FILE_SHARE_READ
:
1877 case FILE_SHARE_WRITE
:
1879 case FILE_SHARE_READ
|FILE_SHARE_WRITE
:
1882 if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
) {
1884 } else if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
) {
1888 return (uint32_t)-1;
1891 struct server_id
interpret_pid(const char *pid_string
)
1893 return server_id_from_string(get_my_vnn(), pid_string
);
1896 /****************************************************************
1897 Check if an offset into a buffer is safe.
1898 If this returns True it's safe to indirect into the byte at
1900 ****************************************************************/
1902 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1904 const char *end_base
= buf_base
+ buf_len
;
1905 char *end_ptr
= ptr
+ off
;
1907 if (!buf_base
|| !ptr
) {
1911 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1912 return False
; /* wrap. */
1915 if (end_ptr
< end_base
) {
1921 /****************************************************************
1922 Return a safe pointer into a buffer, or NULL.
1923 ****************************************************************/
1925 char *get_safe_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1927 return is_offset_safe(buf_base
, buf_len
, ptr
, off
) ?
1931 /****************************************************************
1932 Return a safe pointer into a string within a buffer, or NULL.
1933 ****************************************************************/
1935 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1937 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1940 /* Check if a valid string exists at this offset. */
1941 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1947 /****************************************************************
1948 Return an SVAL at a pointer, or failval if beyond the end.
1949 ****************************************************************/
1951 int get_safe_SVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1954 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1957 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+1)) {
1960 return SVAL(ptr
,off
);
1963 /****************************************************************
1964 Return an IVAL at a pointer, or failval if beyond the end.
1965 ****************************************************************/
1967 int get_safe_IVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1970 * Note we use off+3 here, not off+4 as IVAL accesses
1971 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1973 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+3)) {
1976 return IVAL(ptr
,off
);
1979 /****************************************************************
1980 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1981 call (they take care of winbind separator and other winbind specific settings).
1982 ****************************************************************/
1984 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1985 const char *full_name
,
1989 const char *p
= NULL
;
1991 p
= strchr_m(full_name
, '\\');
1994 *domain
= talloc_strndup(mem_ctx
, full_name
,
1995 PTR_DIFF(p
, full_name
));
1996 if (*domain
== NULL
) {
1999 *user
= talloc_strdup(mem_ctx
, p
+1);
2000 if (*user
== NULL
) {
2001 TALLOC_FREE(*domain
);
2006 *user
= talloc_strdup(mem_ctx
, full_name
);
2007 if (*user
== NULL
) {
2015 /****************************************************************
2016 strip off leading '\\' from a hostname
2017 ****************************************************************/
2019 const char *strip_hostname(const char *s
)
2025 if (strlen_m(s
) < 3) {
2029 if (s
[0] == '\\') s
++;
2030 if (s
[0] == '\\') s
++;
2035 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
2037 if (!NT_STATUS_IS_OK(err1
)) {
2041 if (!NT_STATUS_IS_OK(err2
)) {
2048 int timeval_to_msec(struct timeval t
)
2050 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
2053 /*******************************************************************
2054 Check a given DOS pathname is valid for a share.
2055 ********************************************************************/
2057 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
2061 if (!dos_pathname
) {
2065 ptr
= talloc_strdup(ctx
, dos_pathname
);
2069 /* Convert any '\' paths to '/' */
2071 ptr
= unix_clean_name(ctx
, ptr
);
2076 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
2077 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
2080 /* Only absolute paths allowed. */
2087 /*******************************************************************
2088 Return True if the filename is one of the special executable types.
2089 ********************************************************************/
2091 bool is_executable(const char *fname
)
2093 if ((fname
= strrchr_m(fname
,'.'))) {
2094 if (strequal(fname
,".com") ||
2095 strequal(fname
,".dll") ||
2096 strequal(fname
,".exe") ||
2097 strequal(fname
,".sym")) {
2104 /****************************************************************************
2105 Open a file with a share mode - old openX method - map into NTCreate.
2106 ****************************************************************************/
2108 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
2109 int deny_mode
, int open_func
,
2110 uint32_t *paccess_mask
,
2111 uint32_t *pshare_mode
,
2112 uint32_t *pcreate_disposition
,
2113 uint32_t *pcreate_options
,
2114 uint32_t *pprivate_flags
)
2116 uint32_t access_mask
;
2117 uint32_t share_mode
;
2118 uint32_t create_disposition
;
2119 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
2120 uint32_t private_flags
= 0;
2122 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
2123 "open_func = 0x%x\n",
2124 smb_base_fname
, (unsigned int)deny_mode
,
2125 (unsigned int)open_func
));
2127 /* Create the NT compatible access_mask. */
2128 switch (GET_OPENX_MODE(deny_mode
)) {
2129 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
2130 case DOS_OPEN_RDONLY
:
2131 access_mask
= FILE_GENERIC_READ
;
2133 case DOS_OPEN_WRONLY
:
2134 access_mask
= FILE_GENERIC_WRITE
;
2138 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
2141 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
2142 (unsigned int)GET_OPENX_MODE(deny_mode
)));
2146 /* Create the NT compatible create_disposition. */
2147 switch (open_func
) {
2148 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2149 create_disposition
= FILE_CREATE
;
2152 case OPENX_FILE_EXISTS_OPEN
:
2153 create_disposition
= FILE_OPEN
;
2156 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2157 create_disposition
= FILE_OPEN_IF
;
2160 case OPENX_FILE_EXISTS_TRUNCATE
:
2161 create_disposition
= FILE_OVERWRITE
;
2164 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2165 create_disposition
= FILE_OVERWRITE_IF
;
2169 /* From samba4 - to be confirmed. */
2170 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
2171 create_disposition
= FILE_CREATE
;
2174 DEBUG(10,("map_open_params_to_ntcreate: bad "
2175 "open_func 0x%x\n", (unsigned int)open_func
));
2179 /* Create the NT compatible share modes. */
2180 switch (GET_DENY_MODE(deny_mode
)) {
2182 share_mode
= FILE_SHARE_NONE
;
2186 share_mode
= FILE_SHARE_READ
;
2190 share_mode
= FILE_SHARE_WRITE
;
2194 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2198 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
;
2199 if (is_executable(smb_base_fname
)) {
2200 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2202 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
2203 share_mode
= FILE_SHARE_READ
;
2205 share_mode
= FILE_SHARE_NONE
;
2211 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
;
2212 share_mode
= FILE_SHARE_NONE
;
2216 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2217 (unsigned int)GET_DENY_MODE(deny_mode
) ));
2221 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2222 "share_mode = 0x%x, create_disposition = 0x%x, "
2223 "create_options = 0x%x private_flags = 0x%x\n",
2225 (unsigned int)access_mask
,
2226 (unsigned int)share_mode
,
2227 (unsigned int)create_disposition
,
2228 (unsigned int)create_options
,
2229 (unsigned int)private_flags
));
2232 *paccess_mask
= access_mask
;
2235 *pshare_mode
= share_mode
;
2237 if (pcreate_disposition
) {
2238 *pcreate_disposition
= create_disposition
;
2240 if (pcreate_options
) {
2241 *pcreate_options
= create_options
;
2243 if (pprivate_flags
) {
2244 *pprivate_flags
= private_flags
;
2251 /*************************************************************************
2252 Return a talloced copy of a struct security_unix_token. NULL on fail.
2253 *************************************************************************/
2255 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
2257 struct security_unix_token
*cpy
;
2259 cpy
= talloc(ctx
, struct security_unix_token
);
2264 cpy
->uid
= tok
->uid
;
2265 cpy
->gid
= tok
->gid
;
2266 cpy
->ngroups
= tok
->ngroups
;
2268 /* Make this a talloc child of cpy. */
2269 cpy
->groups
= (gid_t
*)talloc_memdup(
2270 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
2281 /****************************************************************************
2282 Check that a file matches a particular file type.
2283 ****************************************************************************/
2285 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
2289 /* Check the "may have" search bits. */
2290 if (((mode
& ~dirtype
) &
2291 (FILE_ATTRIBUTE_HIDDEN
|
2292 FILE_ATTRIBUTE_SYSTEM
|
2293 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
2297 /* Check the "must have" bits,
2298 which are the may have bits shifted eight */
2299 /* If must have bit is set, the file/dir can
2300 not be returned in search unless the matching
2301 file attribute is set */
2302 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
2303 FILE_ATTRIBUTE_ARCHIVE
|
2304 FILE_ATTRIBUTE_READONLY
|
2305 FILE_ATTRIBUTE_HIDDEN
|
2306 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
2308 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
2309 FILE_ATTRIBUTE_ARCHIVE
|
2310 FILE_ATTRIBUTE_READONLY
|
2311 FILE_ATTRIBUTE_HIDDEN
|
2312 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
2313 /* check if matching attribute present */