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 #ifdef WITH_NISPLUS_HOME
49 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
51 * The following lines are needed due to buggy include files
52 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
53 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
54 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
55 * an enum in /usr/include/rpcsvc/nis.h.
62 #if defined(GROUP_OBJ)
66 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
68 #include <rpcsvc/nis.h>
70 #endif /* WITH_NISPLUS_HOME */
71 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
73 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
75 enum protocol_types
get_Protocol(void)
80 void set_Protocol(enum protocol_types p
)
85 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
87 void gfree_all( void )
96 /*******************************************************************
97 Check if a file exists - call vfs_file_exist for samba files.
98 ********************************************************************/
100 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
101 bool fake_dir_create_times
)
107 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
110 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
113 /*******************************************************************
114 Check if a unix domain socket exists - call vfs_file_exist for samba files.
115 ********************************************************************/
117 bool socket_exist(const char *fname
)
120 if (sys_stat(fname
, &st
, false) != 0)
123 return S_ISSOCK(st
.st_ex_mode
);
126 /*******************************************************************
127 Returns the size in bytes of the named given the stat struct.
128 ********************************************************************/
130 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
132 return sbuf
->st_ex_size
;
135 /****************************************************************************
136 Check two stats have identical dev and ino fields.
137 ****************************************************************************/
139 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
140 const SMB_STRUCT_STAT
*sbuf2
)
142 if (sbuf1
->st_ex_dev
!= sbuf2
->st_ex_dev
||
143 sbuf1
->st_ex_ino
!= sbuf2
->st_ex_ino
) {
149 /****************************************************************************
150 Check if a stat struct is identical for use.
151 ****************************************************************************/
153 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
154 const SMB_STRUCT_STAT
*sbuf2
)
156 if (sbuf1
->st_ex_uid
!= sbuf2
->st_ex_uid
||
157 sbuf1
->st_ex_gid
!= sbuf2
->st_ex_gid
||
158 !check_same_dev_ino(sbuf1
, sbuf2
)) {
164 /*******************************************************************
165 Show a smb message structure.
166 ********************************************************************/
168 void show_msg(const char *buf
)
176 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
178 (int)CVAL(buf
,smb_com
),
179 (int)CVAL(buf
,smb_rcls
),
180 (int)CVAL(buf
,smb_reh
),
181 (int)SVAL(buf
,smb_err
),
182 (int)CVAL(buf
,smb_flg
),
183 (int)SVAL(buf
,smb_flg2
)));
184 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
185 (int)SVAL(buf
,smb_tid
),
186 (int)SVAL(buf
,smb_pid
),
187 (int)SVAL(buf
,smb_uid
),
188 (int)SVAL(buf
,smb_mid
)));
189 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
191 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
192 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
193 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
195 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
197 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
205 dump_data(10, (const uint8_t *)smb_buf_const(buf
), bcc
);
208 /*******************************************************************
209 Setup only the byte count for a smb message.
210 ********************************************************************/
212 int set_message_bcc(char *buf
,int num_bytes
)
214 int num_words
= CVAL(buf
,smb_wct
);
215 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
216 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
217 return (smb_size
+ num_words
*2 + num_bytes
);
220 /*******************************************************************
221 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
222 Return the bytes added
223 ********************************************************************/
225 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
227 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
230 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
231 DEBUG(0, ("talloc failed\n"));
236 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
237 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
241 /*******************************************************************
242 Reduce a file name, removing .. elements.
243 ********************************************************************/
245 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
250 DEBUG(3,("dos_clean_name [%s]\n",s
));
252 /* remove any double slashes */
253 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
258 /* Remove leading .\\ characters */
259 if(strncmp(str
, ".\\", 2) == 0) {
260 trim_string(str
, ".\\", NULL
);
262 str
= talloc_strdup(ctx
, ".\\");
269 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
275 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
280 str
= talloc_asprintf(ctx
,
289 trim_string(str
,NULL
,"\\..");
290 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
293 /*******************************************************************
294 Reduce a file name, removing .. elements.
295 ********************************************************************/
297 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
302 DEBUG(3,("unix_clean_name [%s]\n",s
));
304 /* remove any double slashes */
305 str
= talloc_all_string_sub(ctx
, s
, "//","/");
310 /* Remove leading ./ characters */
311 if(strncmp(str
, "./", 2) == 0) {
312 trim_string(str
, "./", NULL
);
314 str
= talloc_strdup(ctx
, "./");
321 while ((p
= strstr_m(str
,"/../")) != NULL
) {
327 if ((p
=strrchr_m(str
,'/')) != NULL
) {
332 str
= talloc_asprintf(ctx
,
341 trim_string(str
,NULL
,"/..");
342 return talloc_all_string_sub(ctx
, str
, "/./", "/");
345 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
347 char *str
= dos_clean_name(ctx
, s
);
351 return unix_clean_name(ctx
, str
);
354 /*******************************************************************
355 Write data into an fd at a given offset. Ignore seek errors.
356 ********************************************************************/
358 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
363 if (pos
== (off_t
)-1) {
364 return write_data(fd
, buffer
, N
);
366 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
368 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
369 if (ret
== -1 && errno
== ESPIPE
) {
370 return write_data(fd
, buffer
+ total
,N
- total
);
373 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
382 return (ssize_t
)total
;
384 /* Use lseek and write_data. */
385 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
386 if (errno
!= ESPIPE
) {
390 return write_data(fd
, buffer
, N
);
394 static int reinit_after_fork_pipe
[2] = { -1, -1 };
396 NTSTATUS
init_before_fork(void)
400 ret
= pipe(reinit_after_fork_pipe
);
404 status
= map_nt_error_from_unix_common(errno
);
406 DEBUG(0, ("Error creating child_pipe: %s\n",
416 * Detect died parent by detecting EOF on the pipe
418 static void reinit_after_fork_pipe_handler(struct tevent_context
*ev
,
419 struct tevent_fd
*fde
,
425 if (sys_read(reinit_after_fork_pipe
[0], &c
, 1) != 1) {
427 * we have reached EOF on stdin, which means the
428 * parent has exited. Shutdown the server
430 (void)kill(getpid(), SIGTERM
);
435 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
436 struct tevent_context
*ev_ctx
,
437 bool parent_longlived
,
440 NTSTATUS status
= NT_STATUS_OK
;
443 if (reinit_after_fork_pipe
[1] != -1) {
444 close(reinit_after_fork_pipe
[1]);
445 reinit_after_fork_pipe
[1] = -1;
448 /* tdb needs special fork handling */
449 if (tdb_reopen_all(parent_longlived
? 1 : 0) != 0) {
450 DEBUG(0,("tdb_reopen_all failed.\n"));
451 status
= NT_STATUS_OPEN_FAILED
;
455 if (ev_ctx
!= NULL
) {
456 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
457 if (tevent_re_initialise(ev_ctx
) != 0) {
458 smb_panic(__location__
": Failed to re-initialise event context");
462 if (reinit_after_fork_pipe
[0] != -1) {
463 struct tevent_fd
*fde
;
465 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
466 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
467 reinit_after_fork_pipe_handler
, NULL
);
469 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
475 * For clustering, we need to re-init our ctdbd connection after the
478 status
= messaging_reinit(msg_ctx
);
479 if (!NT_STATUS_IS_OK(status
)) {
480 DEBUG(0,("messaging_reinit() failed: %s\n",
484 if (lp_clustering()) {
485 ret
= ctdb_async_ctx_reinit(
486 NULL
, messaging_tevent_context(msg_ctx
));
488 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
490 return map_nt_error_from_unix(ret
);
496 prctl_set_comment(comment
);
503 /****************************************************************************
504 (Hopefully) efficient array append.
505 ****************************************************************************/
507 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
508 void *element
, void *_array
, uint32_t *num_elements
,
511 void **array
= (void **)_array
;
513 if (*array_size
< 0) {
517 if (*array
== NULL
) {
518 if (*array_size
== 0) {
522 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
526 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
527 if (*array
== NULL
) {
532 if (*num_elements
== *array_size
) {
535 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
539 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
540 element_size
* (*array_size
));
542 if (*array
== NULL
) {
547 memcpy((char *)(*array
) + element_size
*(*num_elements
),
548 element
, element_size
);
558 /****************************************************************************
559 Get my own domain name, or "" if we have none.
560 ****************************************************************************/
562 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
567 domname
= get_mydnsfullname();
572 p
= strchr_m(domname
, '.');
575 return talloc_strdup(ctx
, p
);
577 return talloc_strdup(ctx
, "");
581 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
582 /******************************************************************
583 Remove any mount options such as -rsize=2048,wsize=2048 etc.
584 Based on a fix from <Thomas.Hepper@icem.de>.
585 Returns a malloc'ed string.
586 *******************************************************************/
588 static char *strip_mount_options(TALLOC_CTX
*ctx
, const char *str
)
592 while(*p
&& !isspace(*p
))
594 while(*p
&& isspace(*p
))
597 return talloc_strdup(ctx
, p
);
603 /*******************************************************************
604 Patch from jkf@soton.ac.uk
605 Split Luke's automount_server into YP lookup and string splitter
606 so can easily implement automount_path().
607 Returns a malloc'ed string.
608 *******************************************************************/
610 #ifdef WITH_NISPLUS_HOME
611 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
615 char *nis_map
= (char *)lp_homedir_map();
617 char buffer
[NIS_MAXATTRVAL
+ 1];
622 snprintf(buffer
, sizeof(buffer
), "[key=%s],%s", user_name
, nis_map
);
623 DEBUG(5, ("NIS+ querystring: %s\n", buffer
));
625 if (result
= nis_list(buffer
, FOLLOW_PATH
|EXPAND_NAME
|HARD_LOOKUP
, NULL
, NULL
)) {
626 if (result
->status
!= NIS_SUCCESS
) {
627 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result
->status
)));
629 object
= result
->objects
.objects_val
;
630 if (object
->zo_data
.zo_type
== ENTRY_OBJ
) {
631 entry
= &object
->zo_data
.objdata_u
.en_data
;
632 DEBUG(5, ("NIS+ entry type: %s\n", entry
->en_type
));
633 DEBUG(3, ("NIS+ result: %s\n", entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
));
635 value
= talloc_strdup(ctx
,
636 entry
->en_cols
.en_cols_val
[1].ec_value
.ec_value_val
);
638 nis_freeresult(result
);
641 value
= talloc_string_sub(ctx
,
648 nis_freeresult(result
);
651 value
= strip_mount_options(ctx
, value
);
652 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
657 #else /* WITH_NISPLUS_HOME */
659 char *automount_lookup(TALLOC_CTX
*ctx
, const char *user_name
)
663 int nis_error
; /* returned by yp all functions */
664 char *nis_result
; /* yp_match inits this */
665 int nis_result_len
; /* and set this */
666 char *nis_domain
; /* yp_get_default_domain inits this */
667 char *nis_map
= lp_homedir_map(talloc_tos());
669 if ((nis_error
= yp_get_default_domain(&nis_domain
)) != 0) {
670 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error
)));
674 DEBUG(5, ("NIS Domain: %s\n", nis_domain
));
676 if ((nis_error
= yp_match(nis_domain
, nis_map
, user_name
,
677 strlen(user_name
), &nis_result
,
678 &nis_result_len
)) == 0) {
679 if (nis_result_len
> 0 && nis_result
[nis_result_len
] == '\n') {
680 nis_result
[nis_result_len
] = '\0';
682 value
= talloc_strdup(ctx
, nis_result
);
686 value
= strip_mount_options(ctx
, value
);
687 } else if(nis_error
== YPERR_KEY
) {
688 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
689 user_name
, nis_map
));
690 DEBUG(3, ("using defaults for server and home directory\n"));
692 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
693 yperr_string(nis_error
), user_name
, nis_map
));
697 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name
, value
));
701 #endif /* WITH_NISPLUS_HOME */
704 bool process_exists(const struct server_id pid
)
706 return serverid_exists(&pid
);
709 /*******************************************************************
710 Convert a uid into a user name.
711 ********************************************************************/
713 const char *uidtoname(uid_t uid
)
715 TALLOC_CTX
*ctx
= talloc_tos();
717 struct passwd
*pass
= NULL
;
719 pass
= getpwuid_alloc(ctx
,uid
);
721 name
= talloc_strdup(ctx
,pass
->pw_name
);
724 name
= talloc_asprintf(ctx
,
731 /*******************************************************************
732 Convert a gid into a group name.
733 ********************************************************************/
735 char *gidtoname(gid_t gid
)
741 return talloc_strdup(talloc_tos(), grp
->gr_name
);
744 return talloc_asprintf(talloc_tos(),
750 /*******************************************************************
751 Convert a user name into a uid.
752 ********************************************************************/
754 uid_t
nametouid(const char *name
)
760 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
767 u
= (uid_t
)strtol(name
, &p
, 0);
768 if ((p
!= name
) && (*p
== '\0'))
774 /*******************************************************************
775 Convert a name to a gid_t if possible. Return -1 if not a group.
776 ********************************************************************/
778 gid_t
nametogid(const char *name
)
784 g
= (gid_t
)strtol(name
, &p
, 0);
785 if ((p
!= name
) && (*p
== '\0'))
788 grp
= getgrnam(name
);
794 /*******************************************************************
795 Something really nasty happened - panic !
796 ********************************************************************/
798 void smb_panic_s3(const char *why
)
803 DEBUG(0,("PANIC (pid %llu): %s\n",
804 (unsigned long long)getpid(), why
));
807 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
809 * Make sure all children can attach a debugger.
811 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
814 cmd
= lp_panic_action(talloc_tos());
816 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd
));
817 result
= system(cmd
);
820 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
823 DEBUG(0, ("smb_panic(): action returned status %d\n",
824 WEXITSTATUS(result
)));
830 /*******************************************************************
831 Print a backtrace of the stack to the debug log. This function
832 DELIBERATELY LEAKS MEMORY. The expectation is that you should
833 exit shortly after calling it.
834 ********************************************************************/
836 #ifdef HAVE_LIBUNWIND_H
837 #include <libunwind.h>
840 #ifdef HAVE_EXECINFO_H
841 #include <execinfo.h>
848 void log_stack_trace(void)
850 #ifdef HAVE_LIBUNWIND
851 /* Try to use libunwind before any other technique since on ia64
852 * libunwind correctly walks the stack in more circumstances than
860 unw_word_t ip
, sp
, off
;
862 procname
[sizeof(procname
) - 1] = '\0';
864 if (unw_getcontext(&uc
) != 0) {
865 goto libunwind_failed
;
868 if (unw_init_local(&cursor
, &uc
) != 0) {
869 goto libunwind_failed
;
872 DEBUG(0, ("BACKTRACE:\n"));
876 unw_get_reg(&cursor
, UNW_REG_IP
, &ip
);
877 unw_get_reg(&cursor
, UNW_REG_SP
, &sp
);
879 switch (unw_get_proc_name(&cursor
,
880 procname
, sizeof(procname
) - 1, &off
) ) {
884 /* Name truncated. */
885 DEBUGADD(0, (" #%u %s + %#llx [ip=%#llx] [sp=%#llx]\n",
886 i
, procname
, (long long)off
,
887 (long long)ip
, (long long) sp
));
890 /* case -UNW_ENOINFO: */
891 /* case -UNW_EUNSPEC: */
892 /* No symbol name found. */
893 DEBUGADD(0, (" #%u %s [ip=%#llx] [sp=%#llx]\n",
894 i
, "<unknown symbol>",
895 (long long)ip
, (long long) sp
));
898 } while (unw_step(&cursor
) > 0);
903 DEBUG(0, ("unable to produce a stack trace with libunwind\n"));
905 #elif HAVE_BACKTRACE_SYMBOLS
906 void *backtrace_stack
[BACKTRACE_STACK_SIZE
];
907 size_t backtrace_size
;
908 char **backtrace_strings
;
910 /* get the backtrace (stack frames) */
911 backtrace_size
= backtrace(backtrace_stack
,BACKTRACE_STACK_SIZE
);
912 backtrace_strings
= backtrace_symbols(backtrace_stack
, backtrace_size
);
914 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
915 (unsigned long)backtrace_size
));
917 if (backtrace_strings
) {
920 for (i
= 0; i
< backtrace_size
; i
++)
921 DEBUGADD(0, (" #%u %s\n", i
, backtrace_strings
[i
]));
923 /* Leak the backtrace_strings, rather than risk what free() might do */
928 /* The IRIX libexc library provides an API for unwinding the stack. See
929 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
930 * since we are about to abort anyway, it hardly matters.
933 #define NAMESIZE 32 /* Arbitrary */
935 __uint64_t addrs
[BACKTRACE_STACK_SIZE
];
936 char * names
[BACKTRACE_STACK_SIZE
];
937 char namebuf
[BACKTRACE_STACK_SIZE
* NAMESIZE
];
946 /* We need to be root so we can open our /proc entry to walk
947 * our stack. It also helps when we want to dump core.
951 for (i
= 0; i
< BACKTRACE_STACK_SIZE
; i
++) {
952 names
[i
] = namebuf
+ (i
* NAMESIZE
);
955 levels
= trace_back_stack(0, addrs
, names
,
956 BACKTRACE_STACK_SIZE
, NAMESIZE
- 1);
958 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels
));
959 for (i
= 0; i
< levels
; i
++) {
960 DEBUGADD(0, (" #%d 0x%llx %s\n", i
, addrs
[i
], names
[i
]));
965 DEBUG(0, ("unable to produce a stack trace on this platform\n"));
969 /*******************************************************************
970 A readdir wrapper which just returns the file name.
971 ********************************************************************/
973 const char *readdirname(DIR *p
)
981 ptr
= (struct dirent
*)readdir(p
);
992 #ifdef HAVE_BROKEN_READDIR_NAME
993 /* using /usr/ucb/cc is BAD */
997 return talloc_strdup(talloc_tos(), dname
);
1000 /*******************************************************************
1001 Utility function used to decide if the last component
1002 of a path matches a (possibly wildcarded) entry in a namelist.
1003 ********************************************************************/
1005 bool is_in_path(const char *name
, name_compare_entry
*namelist
, bool case_sensitive
)
1007 const char *last_component
;
1009 /* if we have no list it's obviously not in the path */
1010 if((namelist
== NULL
) || ((namelist
!= NULL
) && (namelist
[0].name
== NULL
))) {
1014 DEBUG(8, ("is_in_path: %s\n", name
));
1016 /* Get the last component of the unix name. */
1017 last_component
= strrchr_m(name
, '/');
1018 if (!last_component
) {
1019 last_component
= name
;
1021 last_component
++; /* Go past '/' */
1024 for(; namelist
->name
!= NULL
; namelist
++) {
1025 if(namelist
->is_wild
) {
1026 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
1027 DEBUG(8,("is_in_path: mask match succeeded\n"));
1031 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
1032 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
1033 DEBUG(8,("is_in_path: match succeeded\n"));
1038 DEBUG(8,("is_in_path: match not found\n"));
1042 /*******************************************************************
1043 Strip a '/' separated list into an array of
1044 name_compare_enties structures suitable for
1045 passing to is_in_path(). We do this for
1046 speed so we can pre-parse all the names in the list
1047 and don't do it for each call to is_in_path().
1048 We also check if the entry contains a wildcard to
1049 remove a potentially expensive call to mask_match
1051 ********************************************************************/
1053 void set_namearray(name_compare_entry
**ppname_array
, const char *namelist_in
)
1059 int num_entries
= 0;
1062 (*ppname_array
) = NULL
;
1064 if((namelist_in
== NULL
) || ((namelist_in
!= NULL
) && (*namelist_in
== '\0')))
1067 namelist
= talloc_strdup(talloc_tos(), namelist_in
);
1068 if (namelist
== NULL
) {
1069 DEBUG(0,("set_namearray: talloc fail\n"));
1074 namelist_end
= &namelist
[strlen(namelist
)];
1076 /* We need to make two passes over the string. The
1077 first to count the number of elements, the second
1081 while(nameptr
<= namelist_end
) {
1082 if ( *nameptr
== '/' ) {
1083 /* cope with multiple (useless) /s) */
1087 /* anything left? */
1088 if ( *nameptr
== '\0' )
1091 /* find the next '/' or consume remaining */
1092 name_end
= strchr_m(nameptr
, '/');
1093 if (name_end
== NULL
) {
1094 /* Point nameptr at the terminating '\0' */
1095 nameptr
+= strlen(nameptr
);
1097 /* next segment please */
1098 nameptr
= name_end
+ 1;
1103 if(num_entries
== 0) {
1104 talloc_free(namelist
);
1108 if(( (*ppname_array
) = SMB_MALLOC_ARRAY(name_compare_entry
, num_entries
+ 1)) == NULL
) {
1109 DEBUG(0,("set_namearray: malloc fail\n"));
1110 talloc_free(namelist
);
1114 /* Now copy out the names */
1117 while(nameptr
<= namelist_end
) {
1118 if ( *nameptr
== '/' ) {
1119 /* cope with multiple (useless) /s) */
1123 /* anything left? */
1124 if ( *nameptr
== '\0' )
1127 /* find the next '/' or consume remaining */
1128 name_end
= strchr_m(nameptr
, '/');
1129 if (name_end
!= NULL
) {
1133 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
1134 if(((*ppname_array
)[i
].name
= SMB_STRDUP(nameptr
)) == NULL
) {
1135 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1136 talloc_free(namelist
);
1140 if (name_end
== NULL
) {
1141 /* Point nameptr at the terminating '\0' */
1142 nameptr
+= strlen(nameptr
);
1144 /* next segment please */
1145 nameptr
= name_end
+ 1;
1150 (*ppname_array
)[i
].name
= NULL
;
1152 talloc_free(namelist
);
1157 #define DBGC_CLASS DBGC_LOCKING
1159 /****************************************************************************
1160 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1161 is dealt with in posix.c
1162 Returns True if we have information regarding this lock region (and returns
1163 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1164 ****************************************************************************/
1166 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
1171 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1172 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
1174 lock
.l_type
= *ptype
;
1175 lock
.l_whence
= SEEK_SET
;
1176 lock
.l_start
= *poffset
;
1177 lock
.l_len
= *pcount
;
1180 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
1184 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1185 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
1190 *ptype
= lock
.l_type
;
1191 *poffset
= lock
.l_start
;
1192 *pcount
= lock
.l_len
;
1195 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1196 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
1200 #if defined(HAVE_OFD_LOCKS)
1201 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1217 *use_ofd_locks
= false;
1220 *use_ofd_locks
= true;
1223 #else /* HAVE_OFD_LOCKS */
1224 int map_process_lock_to_ofd_lock(int op
, bool *use_ofd_locks
)
1226 *use_ofd_locks
= false;
1229 #endif /* HAVE_OFD_LOCKS */
1232 #define DBGC_CLASS DBGC_ALL
1234 /*******************************************************************
1235 Is the name specified one of my netbios names.
1236 Returns true if it is equal, false otherwise.
1237 ********************************************************************/
1239 bool is_myname(const char *s
)
1244 for (n
=0; my_netbios_names(n
); n
++) {
1245 const char *nbt_name
= my_netbios_names(n
);
1247 if (strncasecmp_m(nbt_name
, s
, MAX_NETBIOSNAME_LEN
-1) == 0) {
1252 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s
, ret
));
1256 /*******************************************************************
1257 we distinguish between 2K and XP by the "Native Lan Manager" string
1258 WinXP => "Windows 2002 5.1"
1259 WinXP 64bit => "Windows XP 5.2"
1260 Win2k => "Windows 2000 5.0"
1261 NT4 => "Windows NT 4.0"
1262 Win9x => "Windows 4.0"
1263 Windows 2003 doesn't set the native lan manager string but
1264 they do set the domain to "Windows 2003 5.2" (probably a bug).
1265 ********************************************************************/
1267 void ra_lanman_string( const char *native_lanman
)
1269 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
1270 set_remote_arch( RA_WINXP
);
1271 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
1272 set_remote_arch( RA_WINXP64
);
1273 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
1274 set_remote_arch( RA_WIN2K3
);
1277 static const char *remote_arch_strings
[] = {
1278 [RA_UNKNOWN
] = "UNKNOWN",
1281 [RA_WIN95
] = "Win95",
1282 [RA_WINNT
] = "WinNT",
1283 [RA_WIN2K
] = "Win2K",
1284 [RA_WINXP
] = "WinXP",
1285 [RA_WIN2K3
] = "Win2K3",
1286 [RA_VISTA
] = "Vista",
1287 [RA_SAMBA
] = "Samba",
1288 [RA_CIFSFS
] = "CIFSFS",
1289 [RA_WINXP64
] = "WinXP64",
1293 const char *get_remote_arch_str(void)
1295 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1297 * set_remote_arch() already checks this so ra_type
1298 * should be in the allowed range, but anyway, let's
1299 * do another bound check here.
1301 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1302 ra_type
= RA_UNKNOWN
;
1304 return remote_arch_strings
[ra_type
];
1307 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
1311 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
1312 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
1319 /*******************************************************************
1320 Set the horrid remote_arch string based on an enum.
1321 ********************************************************************/
1323 void set_remote_arch(enum remote_arch_types type
)
1325 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1327 * This protects against someone adding values to enum
1328 * remote_arch_types without updating
1329 * remote_arch_strings array.
1331 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1332 ra_type
= RA_UNKNOWN
;
1337 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1338 get_remote_arch_str()));
1341 /*******************************************************************
1342 Get the remote_arch type.
1343 ********************************************************************/
1345 enum remote_arch_types
get_remote_arch(void)
1350 #define RA_CACHE_TTL 7*24*3600
1352 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1355 struct GUID_txt_buf guid_buf
;
1356 const char *guid_string
= NULL
;
1358 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1359 if (guid_string
== NULL
) {
1363 fstr_sprintf(key
, "RA/%s", guid_string
);
1367 struct ra_parser_state
{
1369 enum remote_arch_types ra
;
1372 static void ra_parser(time_t timeout
, DATA_BLOB blob
, void *priv_data
)
1374 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1375 const char *ra_str
= NULL
;
1377 if (timeout
<= time(NULL
)) {
1381 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1382 DBG_ERR("Remote arch cache key not a string\n");
1386 ra_str
= (const char *)blob
.data
;
1387 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1389 state
->ra
= get_remote_arch_from_str(ra_str
);
1390 state
->found
= true;
1394 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1398 struct ra_parser_state state
= (struct ra_parser_state
) {
1403 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1408 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1409 if (!ok
|| !state
.found
) {
1413 if (state
.ra
== RA_UNKNOWN
) {
1417 set_remote_arch(state
.ra
);
1421 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1425 const char *ra_str
= NULL
;
1427 if (get_remote_arch() == RA_UNKNOWN
) {
1431 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1436 ra_str
= get_remote_arch_str();
1437 if (ra_str
== NULL
) {
1441 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1449 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1453 if (get_remote_arch() == RA_UNKNOWN
) {
1456 ok
= remote_arch_cache_get(client_guid
);
1463 ok
= remote_arch_cache_set(client_guid
);
1469 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1474 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1480 ok
= gencache_del(ra_key
);
1490 const char *tab_depth(int level
, int depth
)
1492 if( CHECK_DEBUGLVL(level
) ) {
1493 dbgtext("%*s", depth
*4, "");
1498 /*****************************************************************************
1499 Provide a checksum on a string
1501 Input: s - the null-terminated character string for which the checksum
1504 Output: The checksum value calculated for s.
1505 *****************************************************************************/
1507 int str_checksum(const char *s
)
1513 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1514 .dsize
= strlen(s
) };
1516 return tdb_jenkins_hash(&key
);
1519 /*****************************************************************
1520 Zero a memory area then free it. Used to catch bugs faster.
1521 *****************************************************************/
1523 void zero_free(void *p
, size_t size
)
1529 /*****************************************************************
1530 Set our open file limit to a requested max and return the limit.
1531 *****************************************************************/
1533 int set_maxfiles(int requested_max
)
1535 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1537 int saved_current_limit
;
1539 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1540 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1543 return requested_max
;
1547 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1548 * account for the extra fd we need
1549 * as well as the log files and standard
1550 * handles etc. Save the limit we want to set in case
1551 * we are running on an OS that doesn't support this limit (AIX)
1552 * which always returns RLIM_INFINITY for rlp.rlim_max.
1555 /* Try raising the hard (max) limit to the requested amount. */
1557 #if defined(RLIM_INFINITY)
1558 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1559 int orig_max
= rlp
.rlim_max
;
1561 if ( rlp
.rlim_max
< requested_max
)
1562 rlp
.rlim_max
= requested_max
;
1564 /* This failing is not an error - many systems (Linux) don't
1565 support our default request of 10,000 open files. JRA. */
1567 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1568 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1569 (int)rlp
.rlim_max
, strerror(errno
) ));
1571 /* Set failed - restore original value from get. */
1572 rlp
.rlim_max
= orig_max
;
1577 /* Now try setting the soft (current) limit. */
1579 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1581 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1582 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1583 (int)rlp
.rlim_cur
, strerror(errno
) ));
1585 return saved_current_limit
;
1588 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1589 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1592 return saved_current_limit
;
1595 #if defined(RLIM_INFINITY)
1596 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1597 return saved_current_limit
;
1600 if((int)rlp
.rlim_cur
> saved_current_limit
)
1601 return saved_current_limit
;
1603 return rlp
.rlim_cur
;
1604 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1606 * No way to know - just guess...
1608 return requested_max
;
1612 /*****************************************************************
1613 malloc that aborts with smb_panic on fail or zero size.
1614 *****************************************************************/
1616 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1620 smb_panic("smb_xmalloc_array: called with zero size");
1622 if (count
>= MAX_ALLOC_SIZE
/size
) {
1623 smb_panic("smb_xmalloc_array: alloc size too large");
1625 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1626 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1627 (unsigned long)size
, (unsigned long)count
));
1628 smb_panic("smb_xmalloc_array: malloc failed");
1634 vasprintf that aborts on malloc fail
1637 int smb_xvasprintf(char **ptr
, const char *format
, va_list ap
)
1644 n
= vasprintf(ptr
, format
, ap2
);
1646 if (n
== -1 || ! *ptr
) {
1647 smb_panic("smb_xvasprintf: out of memory");
1652 /*****************************************************************
1653 Get local hostname and cache result.
1654 *****************************************************************/
1656 char *myhostname(void)
1660 ret
= get_myname(NULL
);
1665 /*****************************************************************
1666 Get local hostname and cache result.
1667 *****************************************************************/
1669 char *myhostname_upper(void)
1673 char *name
= get_myname(NULL
);
1677 ret
= strupper_talloc(NULL
, name
);
1683 /*******************************************************************
1684 Given a filename - get its directory name
1685 ********************************************************************/
1687 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1693 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1696 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1707 if (!(*parent
= (char *)talloc_memdup(mem_ctx
, dir
, len
+1))) {
1710 (*parent
)[len
] = '\0';
1718 /*******************************************************************
1719 Determine if a pattern contains any Microsoft wildcard characters.
1720 *******************************************************************/
1722 bool ms_has_wild(const char *s
)
1726 while ((c
= *s
++)) {
1739 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1742 if (!s
) return False
;
1743 while ((c
= *s
++)) {
1745 case UCS2_CHAR('*'):
1746 case UCS2_CHAR('?'):
1747 case UCS2_CHAR('<'):
1748 case UCS2_CHAR('>'):
1749 case UCS2_CHAR('"'):
1756 /*******************************************************************
1757 A wrapper that handles case sensitivity and the special handling
1759 *******************************************************************/
1761 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1763 if (ISDOTDOT(string
))
1768 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1771 /*******************************************************************
1772 A wrapper that handles case sensitivity and the special handling
1773 of the ".." name. Varient that is only called by old search code which requires
1774 pattern translation.
1775 *******************************************************************/
1777 bool mask_match_search(const char *string
, const char *pattern
, bool is_case_sensitive
)
1779 if (ISDOTDOT(string
))
1784 return ms_fnmatch(pattern
, string
, True
, is_case_sensitive
) == 0;
1787 /*******************************************************************
1788 A wrapper that handles a list of patters and calls mask_match()
1789 on each. Returns True if any of the patterns match.
1790 *******************************************************************/
1792 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1794 while (listLen
-- > 0) {
1795 if (mask_match(string
, *list
++, is_case_sensitive
))
1801 /**********************************************************************
1802 Converts a name to a fully qualified domain name.
1803 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1804 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1805 canonical name of the host. getaddrinfo() may use a variety of sources
1806 including /etc/hosts to obtain the domainname. It expects aliases in
1807 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1808 ************************************************************************/
1810 bool name_to_fqdn(fstring fqdn
, const char *name
)
1813 struct addrinfo hints
;
1814 struct addrinfo
*result
;
1817 /* Configure hints to obtain canonical name */
1819 memset(&hints
, 0, sizeof(struct addrinfo
));
1820 hints
.ai_family
= AF_UNSPEC
; /* Allow IPv4 or IPv6 */
1821 hints
.ai_socktype
= SOCK_DGRAM
; /* Datagram socket */
1822 hints
.ai_flags
= AI_CANONNAME
; /* Get host's FQDN */
1823 hints
.ai_protocol
= 0; /* Any protocol */
1825 s
= getaddrinfo(name
, NULL
, &hints
, &result
);
1827 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s
)));
1828 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name
));
1829 fstrcpy(fqdn
, name
);
1832 full
= result
->ai_canonname
;
1834 /* Find out if the FQDN is returned as an alias
1835 * to cope with /etc/hosts files where the first
1836 * name is not the FQDN but the short name.
1837 * getaddrinfo provides no easy way of handling aliases
1838 * in /etc/hosts. Users should make sure the FQDN
1839 * comes first in /etc/hosts. */
1840 if (full
&& (! strchr_m(full
, '.'))) {
1841 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1842 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1843 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1844 DEBUGADD(1, (" prior to any aliases.\n"));
1846 if (full
&& (strcasecmp_m(full
, "localhost.localdomain") == 0)) {
1847 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1848 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1849 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1850 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1853 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name
, full
));
1854 fstrcpy(fqdn
, full
);
1855 freeaddrinfo(result
); /* No longer needed */
1859 uint32_t map_share_mode_to_deny_mode(uint32_t share_access
, uint32_t private_options
)
1861 switch (share_access
& ~FILE_SHARE_DELETE
) {
1862 case FILE_SHARE_NONE
:
1864 case FILE_SHARE_READ
:
1866 case FILE_SHARE_WRITE
:
1868 case FILE_SHARE_READ
|FILE_SHARE_WRITE
:
1871 if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
) {
1873 } else if (private_options
& NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
) {
1877 return (uint32_t)-1;
1880 struct server_id
interpret_pid(const char *pid_string
)
1882 return server_id_from_string(get_my_vnn(), pid_string
);
1885 /****************************************************************
1886 Check if an offset into a buffer is safe.
1887 If this returns True it's safe to indirect into the byte at
1889 ****************************************************************/
1891 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1893 const char *end_base
= buf_base
+ buf_len
;
1894 char *end_ptr
= ptr
+ off
;
1896 if (!buf_base
|| !ptr
) {
1900 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1901 return False
; /* wrap. */
1904 if (end_ptr
< end_base
) {
1910 /****************************************************************
1911 Return a safe pointer into a buffer, or NULL.
1912 ****************************************************************/
1914 char *get_safe_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1916 return is_offset_safe(buf_base
, buf_len
, ptr
, off
) ?
1920 /****************************************************************
1921 Return a safe pointer into a string within a buffer, or NULL.
1922 ****************************************************************/
1924 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1926 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1929 /* Check if a valid string exists at this offset. */
1930 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1936 /****************************************************************
1937 Return an SVAL at a pointer, or failval if beyond the end.
1938 ****************************************************************/
1940 int get_safe_SVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1943 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1946 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+1)) {
1949 return SVAL(ptr
,off
);
1952 /****************************************************************
1953 Return an IVAL at a pointer, or failval if beyond the end.
1954 ****************************************************************/
1956 int get_safe_IVAL(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
, int failval
)
1959 * Note we use off+3 here, not off+4 as IVAL accesses
1960 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1962 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
+3)) {
1965 return IVAL(ptr
,off
);
1968 /****************************************************************
1969 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1970 call (they take care of winbind separator and other winbind specific settings).
1971 ****************************************************************/
1973 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1974 const char *full_name
,
1978 const char *p
= NULL
;
1980 p
= strchr_m(full_name
, '\\');
1983 *domain
= talloc_strndup(mem_ctx
, full_name
,
1984 PTR_DIFF(p
, full_name
));
1985 if (*domain
== NULL
) {
1988 *user
= talloc_strdup(mem_ctx
, p
+1);
1989 if (*user
== NULL
) {
1990 TALLOC_FREE(*domain
);
1995 *user
= talloc_strdup(mem_ctx
, full_name
);
1996 if (*user
== NULL
) {
2004 /****************************************************************
2005 strip off leading '\\' from a hostname
2006 ****************************************************************/
2008 const char *strip_hostname(const char *s
)
2014 if (strlen_m(s
) < 3) {
2018 if (s
[0] == '\\') s
++;
2019 if (s
[0] == '\\') s
++;
2024 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
2026 if (!NT_STATUS_IS_OK(err1
)) {
2030 if (!NT_STATUS_IS_OK(err2
)) {
2037 int timeval_to_msec(struct timeval t
)
2039 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
2042 /*******************************************************************
2043 Check a given DOS pathname is valid for a share.
2044 ********************************************************************/
2046 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
2050 if (!dos_pathname
) {
2054 ptr
= talloc_strdup(ctx
, dos_pathname
);
2058 /* Convert any '\' paths to '/' */
2060 ptr
= unix_clean_name(ctx
, ptr
);
2065 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
2066 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
2069 /* Only absolute paths allowed. */
2076 /*******************************************************************
2077 Return True if the filename is one of the special executable types.
2078 ********************************************************************/
2080 bool is_executable(const char *fname
)
2082 if ((fname
= strrchr_m(fname
,'.'))) {
2083 if (strequal(fname
,".com") ||
2084 strequal(fname
,".dll") ||
2085 strequal(fname
,".exe") ||
2086 strequal(fname
,".sym")) {
2093 /****************************************************************************
2094 Open a file with a share mode - old openX method - map into NTCreate.
2095 ****************************************************************************/
2097 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
2098 int deny_mode
, int open_func
,
2099 uint32_t *paccess_mask
,
2100 uint32_t *pshare_mode
,
2101 uint32_t *pcreate_disposition
,
2102 uint32_t *pcreate_options
,
2103 uint32_t *pprivate_flags
)
2105 uint32_t access_mask
;
2106 uint32_t share_mode
;
2107 uint32_t create_disposition
;
2108 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
2109 uint32_t private_flags
= 0;
2111 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
2112 "open_func = 0x%x\n",
2113 smb_base_fname
, (unsigned int)deny_mode
,
2114 (unsigned int)open_func
));
2116 /* Create the NT compatible access_mask. */
2117 switch (GET_OPENX_MODE(deny_mode
)) {
2118 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
2119 case DOS_OPEN_RDONLY
:
2120 access_mask
= FILE_GENERIC_READ
;
2122 case DOS_OPEN_WRONLY
:
2123 access_mask
= FILE_GENERIC_WRITE
;
2127 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
2130 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
2131 (unsigned int)GET_OPENX_MODE(deny_mode
)));
2135 /* Create the NT compatible create_disposition. */
2136 switch (open_func
) {
2137 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2138 create_disposition
= FILE_CREATE
;
2141 case OPENX_FILE_EXISTS_OPEN
:
2142 create_disposition
= FILE_OPEN
;
2145 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2146 create_disposition
= FILE_OPEN_IF
;
2149 case OPENX_FILE_EXISTS_TRUNCATE
:
2150 create_disposition
= FILE_OVERWRITE
;
2153 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
2154 create_disposition
= FILE_OVERWRITE_IF
;
2158 /* From samba4 - to be confirmed. */
2159 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
2160 create_disposition
= FILE_CREATE
;
2163 DEBUG(10,("map_open_params_to_ntcreate: bad "
2164 "open_func 0x%x\n", (unsigned int)open_func
));
2168 /* Create the NT compatible share modes. */
2169 switch (GET_DENY_MODE(deny_mode
)) {
2171 share_mode
= FILE_SHARE_NONE
;
2175 share_mode
= FILE_SHARE_READ
;
2179 share_mode
= FILE_SHARE_WRITE
;
2183 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2187 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS
;
2188 if (is_executable(smb_base_fname
)) {
2189 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
2191 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
2192 share_mode
= FILE_SHARE_READ
;
2194 share_mode
= FILE_SHARE_NONE
;
2200 private_flags
|= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB
;
2201 share_mode
= FILE_SHARE_NONE
;
2205 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2206 (unsigned int)GET_DENY_MODE(deny_mode
) ));
2210 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2211 "share_mode = 0x%x, create_disposition = 0x%x, "
2212 "create_options = 0x%x private_flags = 0x%x\n",
2214 (unsigned int)access_mask
,
2215 (unsigned int)share_mode
,
2216 (unsigned int)create_disposition
,
2217 (unsigned int)create_options
,
2218 (unsigned int)private_flags
));
2221 *paccess_mask
= access_mask
;
2224 *pshare_mode
= share_mode
;
2226 if (pcreate_disposition
) {
2227 *pcreate_disposition
= create_disposition
;
2229 if (pcreate_options
) {
2230 *pcreate_options
= create_options
;
2232 if (pprivate_flags
) {
2233 *pprivate_flags
= private_flags
;
2240 /*************************************************************************
2241 Return a talloced copy of a struct security_unix_token. NULL on fail.
2242 *************************************************************************/
2244 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
2246 struct security_unix_token
*cpy
;
2248 cpy
= talloc(ctx
, struct security_unix_token
);
2253 cpy
->uid
= tok
->uid
;
2254 cpy
->gid
= tok
->gid
;
2255 cpy
->ngroups
= tok
->ngroups
;
2257 /* Make this a talloc child of cpy. */
2258 cpy
->groups
= (gid_t
*)talloc_memdup(
2259 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
2270 /****************************************************************************
2271 Check that a file matches a particular file type.
2272 ****************************************************************************/
2274 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
2278 /* Check the "may have" search bits. */
2279 if (((mode
& ~dirtype
) &
2280 (FILE_ATTRIBUTE_HIDDEN
|
2281 FILE_ATTRIBUTE_SYSTEM
|
2282 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
2286 /* Check the "must have" bits,
2287 which are the may have bits shifted eight */
2288 /* If must have bit is set, the file/dir can
2289 not be returned in search unless the matching
2290 file attribute is set */
2291 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
2292 FILE_ATTRIBUTE_ARCHIVE
|
2293 FILE_ATTRIBUTE_READONLY
|
2294 FILE_ATTRIBUTE_HIDDEN
|
2295 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
2297 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
2298 FILE_ATTRIBUTE_ARCHIVE
|
2299 FILE_ATTRIBUTE_READONLY
|
2300 FILE_ATTRIBUTE_HIDDEN
|
2301 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
2302 /* check if matching attribute present */