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 * @brief Small functions that don't fit anywhere else
30 #include "system/passwd.h"
31 #include "system/filesys.h"
32 #include "lib/util/server_id.h"
33 #include "lib/util/memcache.h"
35 #include "ctdbd_conn.h"
36 #include "../lib/util/util_pw.h"
38 #include "lib/messaging/messages_dgm.h"
39 #include "libcli/security/security.h"
41 #include "lib/util/sys_rw.h"
42 #include "lib/util/sys_rw_data.h"
43 #include "lib/util/util_process.h"
44 #include "lib/dbwrap/dbwrap_ctdb.h"
45 #include "lib/gencache.h"
46 #include "lib/util/string_wrappers.h"
48 #ifdef HAVE_SYS_PRCTL_H
49 #include <sys/prctl.h>
52 /* Max allowable allococation - 256mb - 0x10000000 */
53 #define MAX_ALLOC_SIZE (1024*1024*256)
55 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
57 void set_Protocol(enum protocol_types p
)
62 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
64 void gfree_all( void )
74 /*******************************************************************
75 Check if a file exists - call vfs_file_exist for samba files.
76 ********************************************************************/
78 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
79 bool fake_dir_create_times
)
85 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
88 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
91 /*******************************************************************
92 Check if a unix domain socket exists - call vfs_file_exist for samba files.
93 ********************************************************************/
95 bool socket_exist(const char *fname
)
98 if (sys_stat(fname
, &st
, false) != 0)
101 return S_ISSOCK(st
.st_ex_mode
);
104 /*******************************************************************
105 Returns the size in bytes of the named given the stat struct.
106 ********************************************************************/
108 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
110 return sbuf
->st_ex_size
;
113 /****************************************************************************
114 Check two stats have identical dev and ino fields.
115 ****************************************************************************/
117 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
118 const SMB_STRUCT_STAT
*sbuf2
)
120 return ((sbuf1
->st_ex_dev
== sbuf2
->st_ex_dev
) &&
121 (sbuf1
->st_ex_ino
== sbuf2
->st_ex_ino
));
124 /****************************************************************************
125 Check if a stat struct is identical for use.
126 ****************************************************************************/
128 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
129 const SMB_STRUCT_STAT
*sbuf2
)
131 return ((sbuf1
->st_ex_uid
== sbuf2
->st_ex_uid
) &&
132 (sbuf1
->st_ex_gid
== sbuf2
->st_ex_gid
) &&
133 check_same_dev_ino(sbuf1
, sbuf2
));
136 /*******************************************************************
137 Show a smb message structure.
138 ********************************************************************/
140 void show_msg(const char *buf
)
148 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
150 (int)CVAL(buf
,smb_com
),
151 (int)CVAL(buf
,smb_rcls
),
152 (int)CVAL(buf
,smb_reh
),
153 (int)SVAL(buf
,smb_err
),
154 (int)CVAL(buf
,smb_flg
),
155 (int)SVAL(buf
,smb_flg2
)));
156 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
157 (int)SVAL(buf
,smb_tid
),
158 (int)SVAL(buf
,smb_pid
),
159 (int)SVAL(buf
,smb_uid
),
160 (int)SVAL(buf
,smb_mid
)));
161 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf
,smb_wct
)));
163 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++)
164 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i
,
165 SVAL(buf
,smb_vwv
+2*i
),SVAL(buf
,smb_vwv
+2*i
)));
167 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
169 DEBUGADD(5,("smb_bcc=%d\n",bcc
));
177 dump_data(10, (const uint8_t *)smb_buf_const(buf
), bcc
);
180 /*******************************************************************
181 Setup only the byte count for a smb message.
182 ********************************************************************/
184 int set_message_bcc(char *buf
,int num_bytes
)
186 int num_words
= CVAL(buf
,smb_wct
);
187 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
188 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
189 return (smb_size
+ num_words
*2 + num_bytes
);
192 /*******************************************************************
193 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
194 Return the bytes added
195 ********************************************************************/
197 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
199 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
202 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
203 DEBUG(0, ("talloc failed\n"));
208 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
209 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
213 /*******************************************************************
214 Reduce a file name, removing .. elements.
215 ********************************************************************/
217 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
222 DEBUG(3,("dos_clean_name [%s]\n",s
));
224 /* remove any double slashes */
225 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
230 /* Remove leading .\\ characters */
231 if(strncmp(str
, ".\\", 2) == 0) {
232 trim_string(str
, ".\\", NULL
);
234 str
= talloc_strdup(ctx
, ".\\");
241 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
247 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
252 str
= talloc_asprintf(ctx
,
261 trim_string(str
,NULL
,"\\..");
262 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
265 /*******************************************************************
266 Reduce a file name, removing .. elements.
267 ********************************************************************/
269 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
274 DEBUG(3,("unix_clean_name [%s]\n",s
));
276 /* remove any double slashes */
277 str
= talloc_all_string_sub(ctx
, s
, "//","/");
282 /* Remove leading ./ characters */
283 if(strncmp(str
, "./", 2) == 0) {
284 trim_string(str
, "./", NULL
);
286 str
= talloc_strdup(ctx
, "./");
293 while ((p
= strstr_m(str
,"/../")) != NULL
) {
299 if ((p
=strrchr_m(str
,'/')) != NULL
) {
304 str
= talloc_asprintf(ctx
,
313 trim_string(str
,NULL
,"/..");
314 return talloc_all_string_sub(ctx
, str
, "/./", "/");
317 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
319 char *str
= dos_clean_name(ctx
, s
);
323 return unix_clean_name(ctx
, str
);
326 /*******************************************************************
327 Write data into an fd at a given offset. Ignore seek errors.
328 ********************************************************************/
330 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
335 if (pos
== (off_t
)-1) {
336 return write_data(fd
, buffer
, N
);
338 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
340 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
341 if (ret
== -1 && errno
== ESPIPE
) {
342 return write_data(fd
, buffer
+ total
,N
- total
);
345 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
354 return (ssize_t
)total
;
356 /* Use lseek and write_data. */
357 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
358 if (errno
!= ESPIPE
) {
362 return write_data(fd
, buffer
, N
);
366 static int reinit_after_fork_pipe
[2] = { -1, -1 };
368 NTSTATUS
init_before_fork(void)
372 ret
= pipe(reinit_after_fork_pipe
);
376 status
= map_nt_error_from_unix_common(errno
);
378 DEBUG(0, ("Error creating child_pipe: %s\n",
388 * @brief Get a fd to watch for our parent process to exit
390 * Samba parent processes open a pipe that naturally closes when the
391 * parent exits. Child processes can watch the read end of the pipe
392 * for readability: Readability with 0 bytes to read means the parent
393 * has exited and the child process might also want to exit.
396 int parent_watch_fd(void)
398 return reinit_after_fork_pipe
[0];
402 * Detect died parent by detecting EOF on the pipe
404 static void reinit_after_fork_pipe_handler(struct tevent_context
*ev
,
405 struct tevent_fd
*fde
,
411 if (sys_read(reinit_after_fork_pipe
[0], &c
, 1) != 1) {
413 * we have reached EOF on stdin, which means the
414 * parent has exited. Shutdown the server
417 (void)kill(getpid(), SIGTERM
);
422 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
423 struct tevent_context
*ev_ctx
,
424 bool parent_longlived
)
426 NTSTATUS status
= NT_STATUS_OK
;
430 * The main process thread should never
431 * allow per_thread_cwd_enable() to be
434 per_thread_cwd_disable();
436 if (reinit_after_fork_pipe
[1] != -1) {
437 close(reinit_after_fork_pipe
[1]);
438 reinit_after_fork_pipe
[1] = -1;
441 /* tdb needs special fork handling */
442 if (tdb_reopen_all(parent_longlived
? 1 : 0) != 0) {
443 DEBUG(0,("tdb_reopen_all failed.\n"));
444 status
= NT_STATUS_OPEN_FAILED
;
448 if (ev_ctx
!= NULL
) {
450 * The parent can have different private data for the callbacks,
451 * which are gone in the child. Reset the callbacks to be safe.
453 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
454 tevent_set_trace_fd_callback(ev_ctx
, NULL
, NULL
);
455 tevent_set_trace_signal_callback(ev_ctx
, NULL
, NULL
);
456 tevent_set_trace_timer_callback(ev_ctx
, NULL
, NULL
);
457 tevent_set_trace_immediate_callback(ev_ctx
, NULL
, NULL
);
458 tevent_set_trace_queue_callback(ev_ctx
, NULL
, NULL
);
459 if (tevent_re_initialise(ev_ctx
) != 0) {
460 smb_panic(__location__
": Failed to re-initialise event context");
464 if (reinit_after_fork_pipe
[0] != -1) {
465 struct tevent_fd
*fde
;
467 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
468 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
469 reinit_after_fork_pipe_handler
, NULL
);
471 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
477 * For clustering, we need to re-init our ctdbd connection after the
480 status
= messaging_reinit(msg_ctx
);
481 if (!NT_STATUS_IS_OK(status
)) {
482 DEBUG(0,("messaging_reinit() failed: %s\n",
486 if (lp_clustering()) {
487 ret
= ctdb_async_ctx_reinit(
488 NULL
, messaging_tevent_context(msg_ctx
));
490 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
492 return map_nt_error_from_unix(ret
);
501 /****************************************************************************
502 (Hopefully) efficient array append.
503 ****************************************************************************/
505 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
506 void *element
, void *_array
, uint32_t *num_elements
,
509 void **array
= (void **)_array
;
511 if (*array_size
< 0) {
515 if (*array
== NULL
) {
516 if (*array_size
== 0) {
520 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
524 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
525 if (*array
== NULL
) {
530 if (*num_elements
== *array_size
) {
533 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
537 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
538 element_size
* (*array_size
));
540 if (*array
== NULL
) {
545 memcpy((char *)(*array
) + element_size
*(*num_elements
),
546 element
, element_size
);
556 /****************************************************************************
557 Get my own domain name, or "" if we have none.
558 ****************************************************************************/
560 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
565 domname
= get_mydnsfullname();
570 p
= strchr_m(domname
, '.');
573 return talloc_strdup(ctx
, p
);
575 return talloc_strdup(ctx
, "");
579 bool process_exists(const struct server_id pid
)
581 return serverid_exists(&pid
);
584 /*******************************************************************
585 Convert a uid into a user name.
586 ********************************************************************/
588 const char *uidtoname(uid_t uid
)
590 TALLOC_CTX
*ctx
= talloc_tos();
592 struct passwd
*pass
= NULL
;
594 pass
= getpwuid_alloc(ctx
,uid
);
596 name
= talloc_strdup(ctx
,pass
->pw_name
);
599 name
= talloc_asprintf(ctx
,
606 /*******************************************************************
607 Convert a gid into a group name.
608 ********************************************************************/
610 char *gidtoname(gid_t gid
)
616 return talloc_strdup(talloc_tos(), grp
->gr_name
);
619 return talloc_asprintf(talloc_tos(),
625 /*******************************************************************
626 Convert a user name into a uid.
627 ********************************************************************/
629 uid_t
nametouid(const char *name
)
635 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
642 u
= (uid_t
)strtol(name
, &p
, 0);
643 if ((p
!= name
) && (*p
== '\0'))
649 /*******************************************************************
650 Convert a name to a gid_t if possible. Return -1 if not a group.
651 ********************************************************************/
653 gid_t
nametogid(const char *name
)
659 g
= (gid_t
)strtol(name
, &p
, 0);
660 if ((p
!= name
) && (*p
== '\0'))
663 grp
= getgrnam(name
);
669 /*******************************************************************
670 Something really nasty happened - panic !
671 ********************************************************************/
673 static void call_panic_action(const char *why
, bool as_root
)
675 const struct loadparm_substitution
*lp_sub
=
676 loadparm_s3_global_substitution();
680 cmd
= lp_panic_action(talloc_tos(), lp_sub
);
681 if (cmd
== NULL
|| cmd
[0] == '\0') {
685 DBG_ERR("Calling panic action [%s]\n", cmd
);
687 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
689 * Make sure all children can attach a debugger.
691 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
698 result
= system(cmd
);
705 DBG_ERR("fork failed in panic action: %s\n",
708 DBG_ERR("action returned status %d\n",
709 WEXITSTATUS(result
));
712 void smb_panic_s3(const char *why
)
714 call_panic_action(why
, false);
718 void log_panic_action(const char *msg
)
721 call_panic_action(msg
, true);
724 /*******************************************************************
725 A readdir wrapper which just returns the file name.
726 ********************************************************************/
728 const char *readdirname(DIR *p
)
736 ptr
= (struct dirent
*)readdir(p
);
742 return talloc_strdup(talloc_tos(), dname
);
745 /*******************************************************************
746 Utility function used to decide if the last component
747 of a path matches a (possibly wildcarded) entry in a namelist.
748 ********************************************************************/
750 bool is_in_path(const char *name
, name_compare_entry
*namelist
, bool case_sensitive
)
752 const char *last_component
;
754 /* if we have no list it's obviously not in the path */
755 if ((namelist
== NULL
) || (namelist
[0].name
== NULL
)) {
759 /* Do not reject path components if namelist is set to '.*' */
760 if (ISDOT(name
) || ISDOTDOT(name
)) {
764 DEBUG(8, ("is_in_path: %s\n", name
));
766 /* Get the last component of the unix name. */
767 last_component
= strrchr_m(name
, '/');
768 if (!last_component
) {
769 last_component
= name
;
771 last_component
++; /* Go past '/' */
774 for(; namelist
->name
!= NULL
; namelist
++) {
775 if(namelist
->is_wild
) {
776 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
777 DEBUG(8,("is_in_path: mask match succeeded\n"));
781 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
782 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
783 DEBUG(8,("is_in_path: match succeeded\n"));
788 DEBUG(8,("is_in_path: match not found\n"));
792 /*******************************************************************
793 Strip a '/' separated list into an array of
794 name_compare_enties structures suitable for
795 passing to is_in_path(). We do this for
796 speed so we can pre-parse all the names in the list
797 and don't do it for each call to is_in_path().
798 We also check if the entry contains a wildcard to
799 remove a potentially expensive call to mask_match
801 ********************************************************************/
803 void set_namearray(name_compare_entry
**ppname_array
, const char *namelist_in
)
812 (*ppname_array
) = NULL
;
814 if((namelist_in
== NULL
) || ((namelist_in
!= NULL
) && (*namelist_in
== '\0')))
817 namelist
= talloc_strdup(talloc_tos(), namelist_in
);
818 if (namelist
== NULL
) {
819 DEBUG(0,("set_namearray: talloc fail\n"));
824 namelist_end
= &namelist
[strlen(namelist
)];
826 /* We need to make two passes over the string. The
827 first to count the number of elements, the second
831 while(nameptr
<= namelist_end
) {
832 if ( *nameptr
== '/' ) {
833 /* cope with multiple (useless) /s) */
838 if ( *nameptr
== '\0' )
841 /* find the next '/' or consume remaining */
842 name_end
= strchr_m(nameptr
, '/');
843 if (name_end
== NULL
) {
844 /* Point nameptr at the terminating '\0' */
845 nameptr
+= strlen(nameptr
);
847 /* next segment please */
848 nameptr
= name_end
+ 1;
853 if(num_entries
== 0) {
854 talloc_free(namelist
);
858 if(( (*ppname_array
) = SMB_MALLOC_ARRAY(name_compare_entry
, num_entries
+ 1)) == NULL
) {
859 DEBUG(0,("set_namearray: malloc fail\n"));
860 talloc_free(namelist
);
864 /* Now copy out the names */
867 while(nameptr
<= namelist_end
) {
868 if ( *nameptr
== '/' ) {
869 /* cope with multiple (useless) /s) */
874 if ( *nameptr
== '\0' )
877 /* find the next '/' or consume remaining */
878 name_end
= strchr_m(nameptr
, '/');
879 if (name_end
!= NULL
) {
883 (*ppname_array
)[i
].is_wild
= ms_has_wild(nameptr
);
884 if(((*ppname_array
)[i
].name
= SMB_STRDUP(nameptr
)) == NULL
) {
885 DEBUG(0,("set_namearray: malloc fail (1)\n"));
886 talloc_free(namelist
);
890 if (name_end
== NULL
) {
891 /* Point nameptr at the terminating '\0' */
892 nameptr
+= strlen(nameptr
);
894 /* next segment please */
895 nameptr
= name_end
+ 1;
900 (*ppname_array
)[i
].name
= NULL
;
902 talloc_free(namelist
);
907 #define DBGC_CLASS DBGC_LOCKING
909 /****************************************************************************
910 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
911 is dealt with in posix.c
912 Returns True if we have information regarding this lock region (and returns
913 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
914 ****************************************************************************/
916 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
921 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
922 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
924 lock
.l_type
= *ptype
;
925 lock
.l_whence
= SEEK_SET
;
926 lock
.l_start
= *poffset
;
927 lock
.l_len
= *pcount
;
930 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
933 int saved_errno
= errno
;
934 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
935 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
940 *ptype
= lock
.l_type
;
941 *poffset
= lock
.l_start
;
942 *pcount
= lock
.l_len
;
945 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
946 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
950 #if defined(HAVE_OFD_LOCKS)
951 int map_process_lock_to_ofd_lock(int op
)
971 #else /* HAVE_OFD_LOCKS */
972 int map_process_lock_to_ofd_lock(int op
)
976 #endif /* HAVE_OFD_LOCKS */
979 #define DBGC_CLASS DBGC_ALL
981 /*******************************************************************
982 Is the name specified one of my netbios names.
983 Returns true if it is equal, false otherwise.
984 ********************************************************************/
986 static bool nb_name_equal(const char *s1
, const char *s2
)
988 int cmp
= strncasecmp_m(s1
, s2
, MAX_NETBIOSNAME_LEN
-1);
992 bool is_myname(const char *s
)
994 const char **aliases
= NULL
;
997 ok
= nb_name_equal(lp_netbios_name(), s
);
1002 aliases
= lp_netbios_aliases();
1003 if (aliases
== NULL
) {
1007 while (*aliases
!= NULL
) {
1008 ok
= nb_name_equal(*aliases
, s
);
1016 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s
, (int)ok
);
1020 /*******************************************************************
1021 we distinguish between 2K and XP by the "Native Lan Manager" string
1022 WinXP => "Windows 2002 5.1"
1023 WinXP 64bit => "Windows XP 5.2"
1024 Win2k => "Windows 2000 5.0"
1025 NT4 => "Windows NT 4.0"
1026 Win9x => "Windows 4.0"
1027 Windows 2003 doesn't set the native lan manager string but
1028 they do set the domain to "Windows 2003 5.2" (probably a bug).
1029 ********************************************************************/
1031 void ra_lanman_string( const char *native_lanman
)
1033 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
1034 set_remote_arch( RA_WINXP
);
1035 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
1036 set_remote_arch( RA_WINXP64
);
1037 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
1038 set_remote_arch( RA_WIN2K3
);
1041 static const char *remote_arch_strings
[] = {
1042 [RA_UNKNOWN
] = "UNKNOWN",
1045 [RA_WIN95
] = "Win95",
1046 [RA_WINNT
] = "WinNT",
1047 [RA_WIN2K
] = "Win2K",
1048 [RA_WINXP
] = "WinXP",
1049 [RA_WIN2K3
] = "Win2K3",
1050 [RA_VISTA
] = "Vista",
1051 [RA_SAMBA
] = "Samba",
1052 [RA_CIFSFS
] = "CIFSFS",
1053 [RA_WINXP64
] = "WinXP64",
1057 const char *get_remote_arch_str(void)
1059 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1061 * set_remote_arch() already checks this so ra_type
1062 * should be in the allowed range, but anyway, let's
1063 * do another bound check here.
1065 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1066 ra_type
= RA_UNKNOWN
;
1068 return remote_arch_strings
[ra_type
];
1071 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
1075 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
1076 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
1083 /*******************************************************************
1084 Set the horrid remote_arch string based on an enum.
1085 ********************************************************************/
1087 void set_remote_arch(enum remote_arch_types type
)
1089 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
1091 * This protects against someone adding values to enum
1092 * remote_arch_types without updating
1093 * remote_arch_strings array.
1095 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
1096 ra_type
= RA_UNKNOWN
;
1101 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1102 get_remote_arch_str()));
1105 /*******************************************************************
1106 Get the remote_arch type.
1107 ********************************************************************/
1109 enum remote_arch_types
get_remote_arch(void)
1114 #define RA_CACHE_TTL 7*24*3600
1116 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1119 struct GUID_txt_buf guid_buf
;
1120 const char *guid_string
= NULL
;
1122 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1123 if (guid_string
== NULL
) {
1127 fstr_sprintf(key
, "RA/%s", guid_string
);
1131 struct ra_parser_state
{
1133 enum remote_arch_types ra
;
1136 static void ra_parser(const struct gencache_timeout
*t
,
1140 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1141 const char *ra_str
= NULL
;
1143 if (gencache_timeout_expired(t
)) {
1147 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1148 DBG_ERR("Remote arch cache key not a string\n");
1152 ra_str
= (const char *)blob
.data
;
1153 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1155 state
->ra
= get_remote_arch_from_str(ra_str
);
1156 state
->found
= true;
1160 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1164 struct ra_parser_state state
= (struct ra_parser_state
) {
1169 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1174 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1175 if (!ok
|| !state
.found
) {
1179 if (state
.ra
== RA_UNKNOWN
) {
1183 set_remote_arch(state
.ra
);
1187 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1191 const char *ra_str
= NULL
;
1193 if (get_remote_arch() == RA_UNKNOWN
) {
1197 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1202 ra_str
= get_remote_arch_str();
1203 if (ra_str
== NULL
) {
1207 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1215 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1219 if (get_remote_arch() == RA_UNKNOWN
) {
1222 ok
= remote_arch_cache_get(client_guid
);
1229 ok
= remote_arch_cache_set(client_guid
);
1235 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1240 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1246 ok
= gencache_del(ra_key
);
1257 /*****************************************************************************
1258 Provide a checksum on a string
1260 Input: s - the null-terminated character string for which the checksum
1263 Output: The checksum value calculated for s.
1264 *****************************************************************************/
1266 int str_checksum(const char *s
)
1272 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1273 .dsize
= strlen(s
) };
1275 return tdb_jenkins_hash(&key
);
1278 /*****************************************************************
1279 Zero a memory area then free it. Used to catch bugs faster.
1280 *****************************************************************/
1282 void zero_free(void *p
, size_t size
)
1288 /*****************************************************************
1289 Set our open file limit to a requested max and return the limit.
1290 *****************************************************************/
1292 int set_maxfiles(int requested_max
)
1294 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1296 int saved_current_limit
;
1298 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1299 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1302 return requested_max
;
1306 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1307 * account for the extra fd we need
1308 * as well as the log files and standard
1309 * handles etc. Save the limit we want to set in case
1310 * we are running on an OS that doesn't support this limit (AIX)
1311 * which always returns RLIM_INFINITY for rlp.rlim_max.
1314 /* Try raising the hard (max) limit to the requested amount. */
1316 #if defined(RLIM_INFINITY)
1317 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1318 int orig_max
= rlp
.rlim_max
;
1320 if ( rlp
.rlim_max
< requested_max
)
1321 rlp
.rlim_max
= requested_max
;
1323 /* This failing is not an error - many systems (Linux) don't
1324 support our default request of 10,000 open files. JRA. */
1326 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1327 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1328 (int)rlp
.rlim_max
, strerror(errno
) ));
1330 /* Set failed - restore original value from get. */
1331 rlp
.rlim_max
= orig_max
;
1336 /* Now try setting the soft (current) limit. */
1338 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1340 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1341 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1342 (int)rlp
.rlim_cur
, strerror(errno
) ));
1344 return saved_current_limit
;
1347 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1348 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1351 return saved_current_limit
;
1354 #if defined(RLIM_INFINITY)
1355 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1356 return saved_current_limit
;
1359 if((int)rlp
.rlim_cur
> saved_current_limit
)
1360 return saved_current_limit
;
1362 return rlp
.rlim_cur
;
1363 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1365 * No way to know - just guess...
1367 return requested_max
;
1371 /*****************************************************************
1372 malloc that aborts with smb_panic on fail or zero size.
1373 *****************************************************************/
1375 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1379 smb_panic("smb_xmalloc_array: called with zero size");
1381 if (count
>= MAX_ALLOC_SIZE
/size
) {
1382 smb_panic("smb_xmalloc_array: alloc size too large");
1384 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1385 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1386 (unsigned long)size
, (unsigned long)count
));
1387 smb_panic("smb_xmalloc_array: malloc failed");
1392 /*****************************************************************
1393 Get local hostname and cache result.
1394 *****************************************************************/
1396 char *myhostname(void)
1400 ret
= get_myname(NULL
);
1405 /*****************************************************************
1406 Get local hostname and cache result.
1407 *****************************************************************/
1409 char *myhostname_upper(void)
1413 char *name
= get_myname(NULL
);
1417 ret
= strupper_talloc(NULL
, name
);
1423 /*******************************************************************
1424 Given a filename - get its directory name
1425 ********************************************************************/
1427 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1433 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1436 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1447 *parent
= talloc_strndup(mem_ctx
, dir
, len
);
1448 if (*parent
== NULL
) {
1458 /*******************************************************************
1459 Determine if a pattern contains any Microsoft wildcard characters.
1460 *******************************************************************/
1462 bool ms_has_wild(const char *s
)
1464 const char *found
= strpbrk(s
, "*?<>\"");
1465 return (found
!= NULL
);
1468 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1471 if (!s
) return False
;
1472 while ((c
= *s
++)) {
1474 case UCS2_CHAR('*'):
1475 case UCS2_CHAR('?'):
1476 case UCS2_CHAR('<'):
1477 case UCS2_CHAR('>'):
1478 case UCS2_CHAR('"'):
1485 /*******************************************************************
1486 A wrapper that handles case sensitivity and the special handling
1488 *******************************************************************/
1490 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1492 if (ISDOTDOT(string
))
1497 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1500 /*******************************************************************
1501 A wrapper that handles a list of patterns and calls mask_match()
1502 on each. Returns True if any of the patterns match.
1503 *******************************************************************/
1505 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1507 while (listLen
-- > 0) {
1508 if (mask_match(string
, *list
++, is_case_sensitive
))
1514 struct server_id
interpret_pid(const char *pid_string
)
1516 return server_id_from_string(get_my_vnn(), pid_string
);
1519 /****************************************************************
1520 Check if an offset into a buffer is safe.
1521 If this returns True it's safe to indirect into the byte at
1523 ****************************************************************/
1525 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1527 const char *end_base
= buf_base
+ buf_len
;
1528 char *end_ptr
= ptr
+ off
;
1530 if (!buf_base
|| !ptr
) {
1534 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1535 return False
; /* wrap. */
1538 if (end_ptr
< end_base
) {
1544 /****************************************************************
1545 Return a safe pointer into a string within a buffer, or NULL.
1546 ****************************************************************/
1548 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1550 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1553 /* Check if a valid string exists at this offset. */
1554 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1561 /****************************************************************
1562 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1563 call (they take care of winbind separator and other winbind specific settings).
1564 ****************************************************************/
1566 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1567 const char *full_name
,
1571 const char *p
= NULL
;
1573 p
= strchr_m(full_name
, '\\');
1576 *domain
= talloc_strndup(mem_ctx
, full_name
,
1577 PTR_DIFF(p
, full_name
));
1578 if (*domain
== NULL
) {
1581 *user
= talloc_strdup(mem_ctx
, p
+1);
1582 if (*user
== NULL
) {
1583 TALLOC_FREE(*domain
);
1588 *user
= talloc_strdup(mem_ctx
, full_name
);
1589 if (*user
== NULL
) {
1597 /****************************************************************
1598 strip off leading '\\' from a hostname
1599 ****************************************************************/
1601 const char *strip_hostname(const char *s
)
1607 if (strlen_m(s
) < 3) {
1611 if (s
[0] == '\\') s
++;
1612 if (s
[0] == '\\') s
++;
1617 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
1619 if (!NT_STATUS_IS_OK(err1
)) {
1623 if (!NT_STATUS_IS_OK(err2
)) {
1630 int timeval_to_msec(struct timeval t
)
1632 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
1635 /*******************************************************************
1636 Check a given DOS pathname is valid for a share.
1637 ********************************************************************/
1639 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
1643 if (!dos_pathname
) {
1647 ptr
= talloc_strdup(ctx
, dos_pathname
);
1651 /* Convert any '\' paths to '/' */
1653 ptr
= unix_clean_name(ctx
, ptr
);
1658 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1659 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
1662 /* Only absolute paths allowed. */
1669 /*******************************************************************
1670 Return True if the filename is one of the special executable types.
1671 ********************************************************************/
1673 bool is_executable(const char *fname
)
1675 if ((fname
= strrchr_m(fname
,'.'))) {
1676 if (strequal(fname
,".com") ||
1677 strequal(fname
,".dll") ||
1678 strequal(fname
,".exe") ||
1679 strequal(fname
,".sym")) {
1686 /****************************************************************************
1687 Open a file with a share mode - old openX method - map into NTCreate.
1688 ****************************************************************************/
1690 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
1691 int deny_mode
, int open_func
,
1692 uint32_t *paccess_mask
,
1693 uint32_t *pshare_mode
,
1694 uint32_t *pcreate_disposition
,
1695 uint32_t *pcreate_options
,
1696 uint32_t *pprivate_flags
)
1698 uint32_t access_mask
;
1699 uint32_t share_mode
;
1700 uint32_t create_disposition
;
1701 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
1702 uint32_t private_flags
= 0;
1704 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1705 "open_func = 0x%x\n",
1706 smb_base_fname
, (unsigned int)deny_mode
,
1707 (unsigned int)open_func
));
1709 /* Create the NT compatible access_mask. */
1710 switch (GET_OPENX_MODE(deny_mode
)) {
1711 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
1712 case DOS_OPEN_RDONLY
:
1713 access_mask
= FILE_GENERIC_READ
;
1715 case DOS_OPEN_WRONLY
:
1716 access_mask
= FILE_GENERIC_WRITE
;
1720 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
1723 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1724 (unsigned int)GET_OPENX_MODE(deny_mode
)));
1728 /* Create the NT compatible create_disposition. */
1729 switch (open_func
) {
1730 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1731 create_disposition
= FILE_CREATE
;
1734 case OPENX_FILE_EXISTS_OPEN
:
1735 create_disposition
= FILE_OPEN
;
1738 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1739 create_disposition
= FILE_OPEN_IF
;
1742 case OPENX_FILE_EXISTS_TRUNCATE
:
1743 create_disposition
= FILE_OVERWRITE
;
1746 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1747 create_disposition
= FILE_OVERWRITE_IF
;
1751 /* From samba4 - to be confirmed. */
1752 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
1753 create_disposition
= FILE_CREATE
;
1756 DEBUG(10,("map_open_params_to_ntcreate: bad "
1757 "open_func 0x%x\n", (unsigned int)open_func
));
1761 /* Create the NT compatible share modes. */
1762 switch (GET_DENY_MODE(deny_mode
)) {
1764 share_mode
= FILE_SHARE_NONE
;
1768 share_mode
= FILE_SHARE_READ
;
1772 share_mode
= FILE_SHARE_WRITE
;
1776 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
1780 private_flags
|= NTCREATEX_FLAG_DENY_DOS
;
1781 if (is_executable(smb_base_fname
)) {
1782 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
1784 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
1785 share_mode
= FILE_SHARE_READ
;
1787 share_mode
= FILE_SHARE_NONE
;
1793 private_flags
|= NTCREATEX_FLAG_DENY_FCB
;
1794 share_mode
= FILE_SHARE_NONE
;
1798 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1799 (unsigned int)GET_DENY_MODE(deny_mode
) ));
1803 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1804 "share_mode = 0x%x, create_disposition = 0x%x, "
1805 "create_options = 0x%x private_flags = 0x%x\n",
1807 (unsigned int)access_mask
,
1808 (unsigned int)share_mode
,
1809 (unsigned int)create_disposition
,
1810 (unsigned int)create_options
,
1811 (unsigned int)private_flags
));
1814 *paccess_mask
= access_mask
;
1817 *pshare_mode
= share_mode
;
1819 if (pcreate_disposition
) {
1820 *pcreate_disposition
= create_disposition
;
1822 if (pcreate_options
) {
1823 *pcreate_options
= create_options
;
1825 if (pprivate_flags
) {
1826 *pprivate_flags
= private_flags
;
1833 /*************************************************************************
1834 Return a talloced copy of a struct security_unix_token. NULL on fail.
1835 *************************************************************************/
1837 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
1839 struct security_unix_token
*cpy
;
1841 cpy
= talloc(ctx
, struct security_unix_token
);
1846 *cpy
= (struct security_unix_token
){
1849 .ngroups
= tok
->ngroups
,
1853 /* Make this a talloc child of cpy. */
1854 cpy
->groups
= (gid_t
*)talloc_memdup(
1855 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
1864 /****************************************************************************
1866 ****************************************************************************/
1868 struct security_unix_token
*root_unix_token(TALLOC_CTX
*mem_ctx
)
1870 struct security_unix_token
*t
= NULL
;
1872 t
= talloc_zero(mem_ctx
, struct security_unix_token
);
1878 * This is not needed, but lets make it explicit, not implicit.
1880 *t
= (struct security_unix_token
) {
1890 char *utok_string(TALLOC_CTX
*mem_ctx
, const struct security_unix_token
*tok
)
1895 str
= talloc_asprintf(
1897 "uid=%ju, gid=%ju, %"PRIu32
" groups:",
1898 (uintmax_t)(tok
->uid
),
1899 (uintmax_t)(tok
->gid
),
1902 for (i
=0; i
<tok
->ngroups
; i
++) {
1903 talloc_asprintf_addbuf(
1904 &str
, " %ju", (uintmax_t)tok
->groups
[i
]);
1910 /****************************************************************************
1911 Check that a file matches a particular file type.
1912 ****************************************************************************/
1914 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
1918 /* Check the "may have" search bits. */
1919 if (((mode
& ~dirtype
) &
1920 (FILE_ATTRIBUTE_HIDDEN
|
1921 FILE_ATTRIBUTE_SYSTEM
|
1922 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
1926 /* Check the "must have" bits,
1927 which are the may have bits shifted eight */
1928 /* If must have bit is set, the file/dir can
1929 not be returned in search unless the matching
1930 file attribute is set */
1931 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
1932 FILE_ATTRIBUTE_ARCHIVE
|
1933 FILE_ATTRIBUTE_READONLY
|
1934 FILE_ATTRIBUTE_HIDDEN
|
1935 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
1937 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
1938 FILE_ATTRIBUTE_ARCHIVE
|
1939 FILE_ATTRIBUTE_READONLY
|
1940 FILE_ATTRIBUTE_HIDDEN
|
1941 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
1942 /* check if matching attribute present */