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"
47 #include "lib/util/strv.h"
49 #ifdef HAVE_SYS_PRCTL_H
50 #include <sys/prctl.h>
53 /* Max allowable allococation - 256mb - 0x10000000 */
54 #define MAX_ALLOC_SIZE (1024*1024*256)
56 static enum protocol_types Protocol
= PROTOCOL_COREPLUS
;
58 void set_Protocol(enum protocol_types p
)
63 static enum remote_arch_types ra_type
= RA_UNKNOWN
;
65 void gfree_all( void )
75 /*******************************************************************
76 Check if a file exists - call vfs_file_exist for samba files.
77 ********************************************************************/
79 bool file_exist_stat(const char *fname
,SMB_STRUCT_STAT
*sbuf
,
80 bool fake_dir_create_times
)
86 if (sys_stat(fname
, sbuf
, fake_dir_create_times
) != 0)
89 return((S_ISREG(sbuf
->st_ex_mode
)) || (S_ISFIFO(sbuf
->st_ex_mode
)));
92 /*******************************************************************
93 Check if a unix domain socket exists - call vfs_file_exist for samba files.
94 ********************************************************************/
96 bool socket_exist(const char *fname
)
99 if (sys_stat(fname
, &st
, false) != 0)
102 return S_ISSOCK(st
.st_ex_mode
);
105 /*******************************************************************
106 Returns the size in bytes of the named given the stat struct.
107 ********************************************************************/
109 uint64_t get_file_size_stat(const SMB_STRUCT_STAT
*sbuf
)
111 return sbuf
->st_ex_size
;
114 /****************************************************************************
115 Check two stats have identical dev and ino fields.
116 ****************************************************************************/
118 bool check_same_dev_ino(const SMB_STRUCT_STAT
*sbuf1
,
119 const SMB_STRUCT_STAT
*sbuf2
)
121 return ((sbuf1
->st_ex_dev
== sbuf2
->st_ex_dev
) &&
122 (sbuf1
->st_ex_ino
== sbuf2
->st_ex_ino
));
125 /****************************************************************************
126 Check if a stat struct is identical for use.
127 ****************************************************************************/
129 bool check_same_stat(const SMB_STRUCT_STAT
*sbuf1
,
130 const SMB_STRUCT_STAT
*sbuf2
)
132 return ((sbuf1
->st_ex_uid
== sbuf2
->st_ex_uid
) &&
133 (sbuf1
->st_ex_gid
== sbuf2
->st_ex_gid
) &&
134 check_same_dev_ino(sbuf1
, sbuf2
));
137 /*******************************************************************
138 Show a smb message structure.
139 ********************************************************************/
141 void show_msg(const char *buf
)
150 msg
= talloc_asprintf(
152 "size=%d\nsmb_com=0x%x\nsmb_rcls=%d\n"
153 "smb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n"
154 "smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n"
157 (int)CVAL(buf
, smb_com
),
158 (int)CVAL(buf
, smb_rcls
),
159 (int)CVAL(buf
, smb_reh
),
160 (int)SVAL(buf
, smb_err
),
161 (int)CVAL(buf
, smb_flg
),
162 (int)SVAL(buf
, smb_flg2
),
163 (int)SVAL(buf
, smb_tid
),
164 (int)SVAL(buf
, smb_pid
),
165 (int)SVAL(buf
, smb_uid
),
166 (int)SVAL(buf
, smb_mid
),
167 (int)CVAL(buf
, smb_wct
));
169 for (i
=0;i
<(int)CVAL(buf
,smb_wct
);i
++) {
170 talloc_asprintf_addbuf(&msg
,
171 "smb_vwv[%2d]=%5d (0x%X)\n",
173 SVAL(buf
, smb_vwv
+ 2 * i
),
174 SVAL(buf
, smb_vwv
+ 2 * i
));
177 bcc
= (int)SVAL(buf
,smb_vwv
+2*(CVAL(buf
,smb_wct
)));
179 talloc_asprintf_addbuf(&msg
, "smb_bcc=%d\n", bcc
);
181 if (DEBUGLEVEL
>= 10) {
182 if (DEBUGLEVEL
< 50) {
185 dump_data_addbuf((const uint8_t *)smb_buf_const(buf
),
190 DEBUG(5, ("%s", msg
));
194 /*******************************************************************
195 Setup only the byte count for a smb message.
196 ********************************************************************/
198 int set_message_bcc(char *buf
,int num_bytes
)
200 int num_words
= CVAL(buf
,smb_wct
);
201 SSVAL(buf
,smb_vwv
+ num_words
*SIZEOFWORD
,num_bytes
);
202 _smb_setlen(buf
,smb_size
+ num_words
*2 + num_bytes
- 4);
203 return (smb_size
+ num_words
*2 + num_bytes
);
206 /*******************************************************************
207 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
208 Return the bytes added
209 ********************************************************************/
211 ssize_t
message_push_blob(uint8_t **outbuf
, DATA_BLOB blob
)
213 size_t newlen
= smb_len(*outbuf
) + 4 + blob
.length
;
216 if (!(tmp
= talloc_realloc(NULL
, *outbuf
, uint8_t, newlen
))) {
217 DEBUG(0, ("talloc failed\n"));
222 memcpy(tmp
+ smb_len(tmp
) + 4, blob
.data
, blob
.length
);
223 set_message_bcc((char *)tmp
, smb_buflen(tmp
) + blob
.length
);
227 /*******************************************************************
228 Reduce a file name, removing .. elements.
229 ********************************************************************/
231 static char *dos_clean_name(TALLOC_CTX
*ctx
, const char *s
)
236 DEBUG(3,("dos_clean_name [%s]\n",s
));
238 /* remove any double slashes */
239 str
= talloc_all_string_sub(ctx
, s
, "\\\\", "\\");
244 /* Remove leading .\\ characters */
245 if(strncmp(str
, ".\\", 2) == 0) {
246 trim_string(str
, ".\\", NULL
);
248 str
= talloc_strdup(ctx
, ".\\");
255 while ((p
= strstr_m(str
,"\\..\\")) != NULL
) {
261 if ((p
=strrchr_m(str
,'\\')) != NULL
) {
266 str
= talloc_asprintf(ctx
,
275 trim_string(str
,NULL
,"\\..");
276 return talloc_all_string_sub(ctx
, str
, "\\.\\", "\\");
279 /*******************************************************************
280 Reduce a file name, removing .. elements.
281 ********************************************************************/
283 char *unix_clean_name(TALLOC_CTX
*ctx
, const char *s
)
288 DEBUG(3,("unix_clean_name [%s]\n",s
));
290 /* remove any double slashes */
291 str
= talloc_all_string_sub(ctx
, s
, "//","/");
296 /* Remove leading ./ characters */
297 if(strncmp(str
, "./", 2) == 0) {
298 trim_string(str
, "./", NULL
);
300 str
= talloc_strdup(ctx
, "./");
307 while ((p
= strstr_m(str
,"/../")) != NULL
) {
313 if ((p
=strrchr_m(str
,'/')) != NULL
) {
318 str
= talloc_asprintf(ctx
,
327 trim_string(str
,NULL
,"/..");
328 return talloc_all_string_sub(ctx
, str
, "/./", "/");
331 char *clean_name(TALLOC_CTX
*ctx
, const char *s
)
333 char *str
= dos_clean_name(ctx
, s
);
337 return unix_clean_name(ctx
, str
);
340 /*******************************************************************
341 Write data into an fd at a given offset. Ignore seek errors.
342 ********************************************************************/
344 ssize_t
write_data_at_offset(int fd
, const char *buffer
, size_t N
, off_t pos
)
349 if (pos
== (off_t
)-1) {
350 return write_data(fd
, buffer
, N
);
352 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
354 ret
= sys_pwrite(fd
,buffer
+ total
,N
- total
, pos
);
355 if (ret
== -1 && errno
== ESPIPE
) {
356 return write_data(fd
, buffer
+ total
,N
- total
);
359 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno
) ));
368 return (ssize_t
)total
;
370 /* Use lseek and write_data. */
371 if (lseek(fd
, pos
, SEEK_SET
) == -1) {
372 if (errno
!= ESPIPE
) {
376 return write_data(fd
, buffer
, N
);
380 static int reinit_after_fork_pipe
[2] = { -1, -1 };
382 NTSTATUS
init_before_fork(void)
386 ret
= pipe(reinit_after_fork_pipe
);
390 status
= map_nt_error_from_unix_common(errno
);
392 DEBUG(0, ("Error creating child_pipe: %s\n",
402 * @brief Get a fd to watch for our parent process to exit
404 * Samba parent processes open a pipe that naturally closes when the
405 * parent exits. Child processes can watch the read end of the pipe
406 * for readability: Readability with 0 bytes to read means the parent
407 * has exited and the child process might also want to exit.
410 int parent_watch_fd(void)
412 return reinit_after_fork_pipe
[0];
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
431 (void)kill(getpid(), SIGTERM
);
436 NTSTATUS
reinit_after_fork(struct messaging_context
*msg_ctx
,
437 struct tevent_context
*ev_ctx
,
438 bool parent_longlived
)
440 NTSTATUS status
= NT_STATUS_OK
;
444 * The main process thread should never
445 * allow per_thread_cwd_enable() to be
448 per_thread_cwd_disable();
450 if (reinit_after_fork_pipe
[1] != -1) {
451 close(reinit_after_fork_pipe
[1]);
452 reinit_after_fork_pipe
[1] = -1;
455 /* tdb needs special fork handling */
456 if (tdb_reopen_all(parent_longlived
? 1 : 0) != 0) {
457 DEBUG(0,("tdb_reopen_all failed.\n"));
458 status
= NT_STATUS_OPEN_FAILED
;
462 if (ev_ctx
!= NULL
) {
464 * The parent can have different private data for the callbacks,
465 * which are gone in the child. Reset the callbacks to be safe.
467 tevent_set_trace_callback(ev_ctx
, NULL
, NULL
);
468 tevent_set_trace_fd_callback(ev_ctx
, NULL
, NULL
);
469 tevent_set_trace_signal_callback(ev_ctx
, NULL
, NULL
);
470 tevent_set_trace_timer_callback(ev_ctx
, NULL
, NULL
);
471 tevent_set_trace_immediate_callback(ev_ctx
, NULL
, NULL
);
472 tevent_set_trace_queue_callback(ev_ctx
, NULL
, NULL
);
473 if (tevent_re_initialise(ev_ctx
) != 0) {
474 smb_panic(__location__
": Failed to re-initialise event context");
478 if (reinit_after_fork_pipe
[0] != -1) {
479 struct tevent_fd
*fde
;
481 fde
= tevent_add_fd(ev_ctx
, ev_ctx
/* TALLOC_CTX */,
482 reinit_after_fork_pipe
[0], TEVENT_FD_READ
,
483 reinit_after_fork_pipe_handler
, NULL
);
485 smb_panic(__location__
": Failed to add reinit_after_fork pipe event");
491 * For clustering, we need to re-init our ctdbd connection after the
494 status
= messaging_reinit(msg_ctx
);
495 if (!NT_STATUS_IS_OK(status
)) {
496 DEBUG(0,("messaging_reinit() failed: %s\n",
501 if (lp_clustering()) {
502 ret
= ctdb_async_ctx_reinit(
503 NULL
, messaging_tevent_context(msg_ctx
));
505 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
507 return map_nt_error_from_unix(ret
);
516 /****************************************************************************
517 (Hopefully) efficient array append.
518 ****************************************************************************/
520 void add_to_large_array(TALLOC_CTX
*mem_ctx
, size_t element_size
,
521 void *element
, void *_array
, uint32_t *num_elements
,
524 void **array
= (void **)_array
;
526 if (*array_size
< 0) {
530 if (*array
== NULL
) {
531 if (*array_size
== 0) {
535 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
539 *array
= TALLOC(mem_ctx
, element_size
* (*array_size
));
540 if (*array
== NULL
) {
545 if (*num_elements
== *array_size
) {
548 if (*array_size
>= MAX_ALLOC_SIZE
/element_size
) {
552 *array
= TALLOC_REALLOC(mem_ctx
, *array
,
553 element_size
* (*array_size
));
555 if (*array
== NULL
) {
560 memcpy((char *)(*array
) + element_size
*(*num_elements
),
561 element
, element_size
);
571 /****************************************************************************
572 Get my own domain name, or "" if we have none.
573 ****************************************************************************/
575 char *get_mydnsdomname(TALLOC_CTX
*ctx
)
580 domname
= get_mydnsfullname();
585 p
= strchr_m(domname
, '.');
588 return talloc_strdup(ctx
, p
);
590 return talloc_strdup(ctx
, "");
594 bool process_exists(const struct server_id pid
)
596 return serverid_exists(&pid
);
599 /*******************************************************************
600 Convert a uid into a user name.
601 ********************************************************************/
603 const char *uidtoname(uid_t uid
)
605 TALLOC_CTX
*ctx
= talloc_tos();
607 struct passwd
*pass
= NULL
;
609 pass
= getpwuid_alloc(ctx
,uid
);
611 name
= talloc_strdup(ctx
,pass
->pw_name
);
614 name
= talloc_asprintf(ctx
,
621 /*******************************************************************
622 Convert a gid into a group name.
623 ********************************************************************/
625 char *gidtoname(gid_t gid
)
631 return talloc_strdup(talloc_tos(), grp
->gr_name
);
634 return talloc_asprintf(talloc_tos(),
640 /*******************************************************************
641 Convert a user name into a uid.
642 ********************************************************************/
644 uid_t
nametouid(const char *name
)
650 pass
= Get_Pwnam_alloc(talloc_tos(), name
);
657 u
= (uid_t
)strtol(name
, &p
, 0);
658 if ((p
!= name
) && (*p
== '\0'))
664 /*******************************************************************
665 Convert a name to a gid_t if possible. Return -1 if not a group.
666 ********************************************************************/
668 gid_t
nametogid(const char *name
)
674 g
= (gid_t
)strtol(name
, &p
, 0);
675 if ((p
!= name
) && (*p
== '\0'))
678 grp
= getgrnam(name
);
684 /*******************************************************************
685 Something really nasty happened - panic !
686 ********************************************************************/
688 static void call_panic_action(const char *why
, bool as_root
)
690 const struct loadparm_substitution
*lp_sub
=
691 loadparm_s3_global_substitution();
695 cmd
= lp_panic_action(talloc_tos(), lp_sub
);
696 if (cmd
== NULL
|| cmd
[0] == '\0') {
700 DBG_ERR("Calling panic action [%s]\n", cmd
);
702 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
704 * Make sure all children can attach a debugger.
706 prctl(PR_SET_PTRACER
, getpid(), 0, 0, 0);
713 result
= system(cmd
);
720 DBG_ERR("fork failed in panic action: %s\n",
723 DBG_ERR("action returned status %d\n",
724 WEXITSTATUS(result
));
727 void smb_panic_s3(const char *why
)
729 call_panic_action(why
, false);
733 void log_panic_action(const char *msg
)
736 call_panic_action(msg
, true);
739 /*******************************************************************
740 A readdir wrapper which just returns the file name.
741 ********************************************************************/
743 const char *readdirname(DIR *p
)
751 ptr
= (struct dirent
*)readdir(p
);
757 return talloc_strdup(talloc_tos(), dname
);
760 /*******************************************************************
761 Utility function used to decide if the last component
762 of a path matches a (possibly wildcarded) entry in a namelist.
763 ********************************************************************/
765 bool is_in_path(const char *name
,
766 struct name_compare_entry
*namelist
,
769 const char *last_component
;
771 /* if we have no list it's obviously not in the path */
772 if ((namelist
== NULL
) || (namelist
[0].name
== NULL
)) {
776 /* Do not reject path components if namelist is set to '.*' */
777 if (ISDOT(name
) || ISDOTDOT(name
)) {
781 DEBUG(8, ("is_in_path: %s\n", name
));
783 /* Get the last component of the unix name. */
784 last_component
= strrchr_m(name
, '/');
785 if (!last_component
) {
786 last_component
= name
;
788 last_component
++; /* Go past '/' */
791 for(; namelist
->name
!= NULL
; namelist
++) {
792 if(namelist
->is_wild
) {
793 if (mask_match(last_component
, namelist
->name
, case_sensitive
)) {
794 DEBUG(8,("is_in_path: mask match succeeded\n"));
798 if((case_sensitive
&& (strcmp(last_component
, namelist
->name
) == 0))||
799 (!case_sensitive
&& (strcasecmp_m(last_component
, namelist
->name
) == 0))) {
800 DEBUG(8,("is_in_path: match succeeded\n"));
805 DEBUG(8,("is_in_path: match not found\n"));
810 #define DBGC_CLASS DBGC_LOCKING
812 /****************************************************************************
813 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
814 is dealt with in posix.c
815 Returns True if we have information regarding this lock region (and returns
816 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
817 ****************************************************************************/
819 bool fcntl_getlock(int fd
, int op
, off_t
*poffset
, off_t
*pcount
, int *ptype
, pid_t
*ppid
)
824 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
825 fd
,op
,(double)*poffset
,(double)*pcount
,*ptype
));
827 lock
.l_type
= *ptype
;
828 lock
.l_whence
= SEEK_SET
;
829 lock
.l_start
= *poffset
;
830 lock
.l_len
= *pcount
;
833 ret
= sys_fcntl_ptr(fd
,op
,&lock
);
836 int saved_errno
= errno
;
837 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
838 (double)*poffset
,(double)*pcount
,*ptype
,strerror(errno
)));
843 *ptype
= lock
.l_type
;
844 *poffset
= lock
.l_start
;
845 *pcount
= lock
.l_len
;
848 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
849 fd
, (int)lock
.l_type
, (unsigned int)lock
.l_pid
));
853 #if defined(HAVE_OFD_LOCKS)
854 int map_process_lock_to_ofd_lock(int op
)
874 #else /* HAVE_OFD_LOCKS */
875 int map_process_lock_to_ofd_lock(int op
)
879 #endif /* HAVE_OFD_LOCKS */
882 #define DBGC_CLASS DBGC_ALL
884 /*******************************************************************
885 Is the name specified one of my netbios names.
886 Returns true if it is equal, false otherwise.
887 ********************************************************************/
889 static bool nb_name_equal(const char *s1
, const char *s2
)
891 int cmp
= strncasecmp_m(s1
, s2
, MAX_NETBIOSNAME_LEN
-1);
895 bool is_myname(const char *s
)
897 const char **aliases
= NULL
;
900 ok
= nb_name_equal(lp_netbios_name(), s
);
905 aliases
= lp_netbios_aliases();
906 if (aliases
== NULL
) {
910 while (*aliases
!= NULL
) {
911 ok
= nb_name_equal(*aliases
, s
);
919 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s
, (int)ok
);
923 /*******************************************************************
924 we distinguish between 2K and XP by the "Native Lan Manager" string
925 WinXP => "Windows 2002 5.1"
926 WinXP 64bit => "Windows XP 5.2"
927 Win2k => "Windows 2000 5.0"
928 NT4 => "Windows NT 4.0"
929 Win9x => "Windows 4.0"
930 Windows 2003 doesn't set the native lan manager string but
931 they do set the domain to "Windows 2003 5.2" (probably a bug).
932 ********************************************************************/
934 void ra_lanman_string( const char *native_lanman
)
936 if ( strcmp( native_lanman
, "Windows 2002 5.1" ) == 0 )
937 set_remote_arch( RA_WINXP
);
938 else if ( strcmp( native_lanman
, "Windows XP 5.2" ) == 0 )
939 set_remote_arch( RA_WINXP64
);
940 else if ( strcmp( native_lanman
, "Windows Server 2003 5.2" ) == 0 )
941 set_remote_arch( RA_WIN2K3
);
944 static const char *remote_arch_strings
[] = {
945 [RA_UNKNOWN
] = "UNKNOWN",
948 [RA_WIN95
] = "Win95",
949 [RA_WINNT
] = "WinNT",
950 [RA_WIN2K
] = "Win2K",
951 [RA_WINXP
] = "WinXP",
952 [RA_WIN2K3
] = "Win2K3",
953 [RA_VISTA
] = "Vista",
954 [RA_SAMBA
] = "Samba",
955 [RA_CIFSFS
] = "CIFSFS",
956 [RA_WINXP64
] = "WinXP64",
960 const char *get_remote_arch_str(void)
962 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
964 * set_remote_arch() already checks this so ra_type
965 * should be in the allowed range, but anyway, let's
966 * do another bound check here.
968 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
969 ra_type
= RA_UNKNOWN
;
971 return remote_arch_strings
[ra_type
];
974 enum remote_arch_types
get_remote_arch_from_str(const char *remote_arch_string
)
978 for (i
= 0; i
< ARRAY_SIZE(remote_arch_strings
); i
++) {
979 if (strcmp(remote_arch_string
, remote_arch_strings
[i
]) == 0) {
986 /*******************************************************************
987 Set the horrid remote_arch string based on an enum.
988 ********************************************************************/
990 void set_remote_arch(enum remote_arch_types type
)
992 if (ra_type
>= ARRAY_SIZE(remote_arch_strings
)) {
994 * This protects against someone adding values to enum
995 * remote_arch_types without updating
996 * remote_arch_strings array.
998 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type
);
999 ra_type
= RA_UNKNOWN
;
1004 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1005 get_remote_arch_str()));
1008 /*******************************************************************
1009 Get the remote_arch type.
1010 ********************************************************************/
1012 enum remote_arch_types
get_remote_arch(void)
1017 #define RA_CACHE_TTL 7*24*3600
1019 static bool remote_arch_cache_key(const struct GUID
*client_guid
,
1022 struct GUID_txt_buf guid_buf
;
1023 const char *guid_string
= NULL
;
1025 guid_string
= GUID_buf_string(client_guid
, &guid_buf
);
1026 if (guid_string
== NULL
) {
1030 fstr_sprintf(key
, "RA/%s", guid_string
);
1034 struct ra_parser_state
{
1036 enum remote_arch_types ra
;
1039 static void ra_parser(const struct gencache_timeout
*t
,
1043 struct ra_parser_state
*state
= (struct ra_parser_state
*)priv_data
;
1044 const char *ra_str
= NULL
;
1046 if (gencache_timeout_expired(t
)) {
1050 if ((blob
.length
== 0) || (blob
.data
[blob
.length
-1] != '\0')) {
1051 DBG_ERR("Remote arch cache key not a string\n");
1055 ra_str
= (const char *)blob
.data
;
1056 DBG_INFO("Got remote arch [%s] from cache\n", ra_str
);
1058 state
->ra
= get_remote_arch_from_str(ra_str
);
1059 state
->found
= true;
1063 static bool remote_arch_cache_get(const struct GUID
*client_guid
)
1067 struct ra_parser_state state
= (struct ra_parser_state
) {
1072 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1077 ok
= gencache_parse(ra_key
, ra_parser
, &state
);
1078 if (!ok
|| !state
.found
) {
1082 if (state
.ra
== RA_UNKNOWN
) {
1086 set_remote_arch(state
.ra
);
1090 static bool remote_arch_cache_set(const struct GUID
*client_guid
)
1094 const char *ra_str
= NULL
;
1096 if (get_remote_arch() == RA_UNKNOWN
) {
1100 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1105 ra_str
= get_remote_arch_str();
1106 if (ra_str
== NULL
) {
1110 ok
= gencache_set(ra_key
, ra_str
, time(NULL
) + RA_CACHE_TTL
);
1118 bool remote_arch_cache_update(const struct GUID
*client_guid
)
1122 if (get_remote_arch() == RA_UNKNOWN
) {
1125 ok
= remote_arch_cache_get(client_guid
);
1132 ok
= remote_arch_cache_set(client_guid
);
1138 bool remote_arch_cache_delete(const struct GUID
*client_guid
)
1143 ok
= remote_arch_cache_key(client_guid
, ra_key
);
1149 ok
= gencache_del(ra_key
);
1160 /*****************************************************************************
1161 Provide a checksum on a string
1163 Input: s - the null-terminated character string for which the checksum
1166 Output: The checksum value calculated for s.
1167 *****************************************************************************/
1169 int str_checksum(const char *s
)
1175 key
= (TDB_DATA
) { .dptr
= discard_const_p(uint8_t, s
),
1176 .dsize
= strlen(s
) };
1178 return tdb_jenkins_hash(&key
);
1181 /*****************************************************************
1182 Zero a memory area then free it. Used to catch bugs faster.
1183 *****************************************************************/
1185 void zero_free(void *p
, size_t size
)
1191 /*****************************************************************
1192 Set our open file limit to a requested max and return the limit.
1193 *****************************************************************/
1195 int set_maxfiles(int requested_max
)
1197 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1199 int saved_current_limit
;
1201 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1202 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1205 return requested_max
;
1209 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1210 * account for the extra fd we need
1211 * as well as the log files and standard
1212 * handles etc. Save the limit we want to set in case
1213 * we are running on an OS that doesn't support this limit (AIX)
1214 * which always returns RLIM_INFINITY for rlp.rlim_max.
1217 /* Try raising the hard (max) limit to the requested amount. */
1219 #if defined(RLIM_INFINITY)
1220 if (rlp
.rlim_max
!= RLIM_INFINITY
) {
1221 int orig_max
= rlp
.rlim_max
;
1223 if ( rlp
.rlim_max
< requested_max
)
1224 rlp
.rlim_max
= requested_max
;
1226 /* This failing is not an error - many systems (Linux) don't
1227 support our default request of 10,000 open files. JRA. */
1229 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1230 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1231 (int)rlp
.rlim_max
, strerror(errno
) ));
1233 /* Set failed - restore original value from get. */
1234 rlp
.rlim_max
= orig_max
;
1239 /* Now try setting the soft (current) limit. */
1241 saved_current_limit
= rlp
.rlim_cur
= MIN(requested_max
,rlp
.rlim_max
);
1243 if(setrlimit(RLIMIT_NOFILE
, &rlp
)) {
1244 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1245 (int)rlp
.rlim_cur
, strerror(errno
) ));
1247 return saved_current_limit
;
1250 if(getrlimit(RLIMIT_NOFILE
, &rlp
)) {
1251 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1254 return saved_current_limit
;
1257 #if defined(RLIM_INFINITY)
1258 if(rlp
.rlim_cur
== RLIM_INFINITY
)
1259 return saved_current_limit
;
1262 if((int)rlp
.rlim_cur
> saved_current_limit
)
1263 return saved_current_limit
;
1265 return rlp
.rlim_cur
;
1266 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1268 * No way to know - just guess...
1270 return requested_max
;
1274 /*****************************************************************
1275 malloc that aborts with smb_panic on fail or zero size.
1276 *****************************************************************/
1278 void *smb_xmalloc_array(size_t size
, unsigned int count
)
1282 smb_panic("smb_xmalloc_array: called with zero size");
1284 if (count
>= MAX_ALLOC_SIZE
/size
) {
1285 smb_panic("smb_xmalloc_array: alloc size too large");
1287 if ((p
= SMB_MALLOC(size
*count
)) == NULL
) {
1288 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1289 (unsigned long)size
, (unsigned long)count
));
1290 smb_panic("smb_xmalloc_array: malloc failed");
1295 /*****************************************************************
1296 Get local hostname and cache result.
1297 *****************************************************************/
1299 char *myhostname(void)
1303 ret
= get_myname(NULL
);
1308 /*****************************************************************
1309 Get local hostname and cache result.
1310 *****************************************************************/
1312 char *myhostname_upper(void)
1316 char *name
= get_myname(NULL
);
1320 ret
= strupper_talloc(NULL
, name
);
1326 /*******************************************************************
1327 Given a filename - get its directory name
1328 ********************************************************************/
1330 bool parent_dirname(TALLOC_CTX
*mem_ctx
, const char *dir
, char **parent
,
1336 p
= strrchr_m(dir
, '/'); /* Find final '/', if any */
1339 if (!(*parent
= talloc_strdup(mem_ctx
, "."))) {
1350 *parent
= talloc_strndup(mem_ctx
, dir
, len
);
1351 if (*parent
== NULL
) {
1361 /*******************************************************************
1362 Determine if a pattern contains any Microsoft wildcard characters.
1363 *******************************************************************/
1365 bool ms_has_wild(const char *s
)
1367 const char *found
= strpbrk(s
, "*?<>\"");
1368 return (found
!= NULL
);
1371 bool ms_has_wild_w(const smb_ucs2_t
*s
)
1374 if (!s
) return False
;
1375 while ((c
= *s
++)) {
1377 case UCS2_CHAR('*'):
1378 case UCS2_CHAR('?'):
1379 case UCS2_CHAR('<'):
1380 case UCS2_CHAR('>'):
1381 case UCS2_CHAR('"'):
1388 /*******************************************************************
1389 A wrapper that handles case sensitivity and the special handling
1391 *******************************************************************/
1393 bool mask_match(const char *string
, const char *pattern
, bool is_case_sensitive
)
1395 if (ISDOTDOT(string
))
1400 return ms_fnmatch_protocol(pattern
, string
, Protocol
, is_case_sensitive
) == 0;
1403 /*******************************************************************
1404 A wrapper that handles a list of patterns and calls mask_match()
1405 on each. Returns True if any of the patterns match.
1406 *******************************************************************/
1408 bool mask_match_list(const char *string
, char **list
, int listLen
, bool is_case_sensitive
)
1410 while (listLen
-- > 0) {
1411 if (mask_match(string
, *list
++, is_case_sensitive
))
1417 struct server_id
interpret_pid(const char *pid_string
)
1419 return server_id_from_string(get_my_vnn(), pid_string
);
1422 /****************************************************************
1423 Check if an offset into a buffer is safe.
1424 If this returns True it's safe to indirect into the byte at
1426 ****************************************************************/
1428 bool is_offset_safe(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1430 const char *end_base
= buf_base
+ buf_len
;
1431 char *end_ptr
= ptr
+ off
;
1433 if (!buf_base
|| !ptr
) {
1437 if (end_base
< buf_base
|| end_ptr
< ptr
) {
1438 return False
; /* wrap. */
1441 if (end_ptr
< end_base
) {
1447 /****************************************************************
1448 Return a safe pointer into a string within a buffer, or NULL.
1449 ****************************************************************/
1451 char *get_safe_str_ptr(const char *buf_base
, size_t buf_len
, char *ptr
, size_t off
)
1453 if (!is_offset_safe(buf_base
, buf_len
, ptr
, off
)) {
1456 /* Check if a valid string exists at this offset. */
1457 if (skip_string(buf_base
,buf_len
, ptr
+ off
) == NULL
) {
1464 /****************************************************************
1465 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1466 call (they take care of winbind separator and other winbind specific settings).
1467 ****************************************************************/
1469 bool split_domain_user(TALLOC_CTX
*mem_ctx
,
1470 const char *full_name
,
1474 const char *p
= NULL
;
1476 p
= strchr_m(full_name
, '\\');
1479 *domain
= talloc_strndup(mem_ctx
, full_name
,
1480 PTR_DIFF(p
, full_name
));
1481 if (*domain
== NULL
) {
1484 *user
= talloc_strdup(mem_ctx
, p
+1);
1485 if (*user
== NULL
) {
1486 TALLOC_FREE(*domain
);
1491 *user
= talloc_strdup(mem_ctx
, full_name
);
1492 if (*user
== NULL
) {
1500 /****************************************************************
1501 strip off leading '\\' from a hostname
1502 ****************************************************************/
1504 const char *strip_hostname(const char *s
)
1510 if (strlen_m(s
) < 3) {
1514 if (s
[0] == '\\') s
++;
1515 if (s
[0] == '\\') s
++;
1520 bool any_nt_status_not_ok(NTSTATUS err1
, NTSTATUS err2
, NTSTATUS
*result
)
1522 if (!NT_STATUS_IS_OK(err1
)) {
1526 if (!NT_STATUS_IS_OK(err2
)) {
1533 int timeval_to_msec(struct timeval t
)
1535 return t
.tv_sec
* 1000 + (t
.tv_usec
+999) / 1000;
1538 /*******************************************************************
1539 Check a given DOS pathname is valid for a share.
1540 ********************************************************************/
1542 char *valid_share_pathname(TALLOC_CTX
*ctx
, const char *dos_pathname
)
1546 if (!dos_pathname
) {
1550 ptr
= talloc_strdup(ctx
, dos_pathname
);
1554 /* Convert any '\' paths to '/' */
1556 ptr
= unix_clean_name(ctx
, ptr
);
1561 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1562 if (strlen(ptr
) > 2 && ptr
[1] == ':' && ptr
[0] != '/')
1565 /* Only absolute paths allowed. */
1572 /*******************************************************************
1573 Return True if the filename is one of the special executable types.
1574 ********************************************************************/
1576 bool is_executable(const char *fname
)
1578 if ((fname
= strrchr_m(fname
,'.'))) {
1579 if (strequal(fname
,".com") ||
1580 strequal(fname
,".dll") ||
1581 strequal(fname
,".exe") ||
1582 strequal(fname
,".sym")) {
1589 /****************************************************************************
1590 Open a file with a share mode - old openX method - map into NTCreate.
1591 ****************************************************************************/
1593 bool map_open_params_to_ntcreate(const char *smb_base_fname
,
1594 int deny_mode
, int open_func
,
1595 uint32_t *paccess_mask
,
1596 uint32_t *pshare_mode
,
1597 uint32_t *pcreate_disposition
,
1598 uint32_t *pcreate_options
,
1599 uint32_t *pprivate_flags
)
1601 uint32_t access_mask
;
1602 uint32_t share_mode
;
1603 uint32_t create_disposition
;
1604 uint32_t create_options
= FILE_NON_DIRECTORY_FILE
;
1605 uint32_t private_flags
= 0;
1607 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1608 "open_func = 0x%x\n",
1609 smb_base_fname
, (unsigned int)deny_mode
,
1610 (unsigned int)open_func
));
1612 /* Create the NT compatible access_mask. */
1613 switch (GET_OPENX_MODE(deny_mode
)) {
1614 case DOS_OPEN_EXEC
: /* Implies read-only - used to be FILE_READ_DATA */
1615 case DOS_OPEN_RDONLY
:
1616 access_mask
= FILE_GENERIC_READ
;
1618 case DOS_OPEN_WRONLY
:
1619 access_mask
= FILE_GENERIC_WRITE
;
1623 access_mask
= FILE_GENERIC_READ
|FILE_GENERIC_WRITE
;
1626 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1627 (unsigned int)GET_OPENX_MODE(deny_mode
)));
1631 /* Create the NT compatible create_disposition. */
1632 switch (open_func
) {
1633 case OPENX_FILE_EXISTS_FAIL
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1634 create_disposition
= FILE_CREATE
;
1637 case OPENX_FILE_EXISTS_OPEN
:
1638 create_disposition
= FILE_OPEN
;
1641 case OPENX_FILE_EXISTS_OPEN
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1642 create_disposition
= FILE_OPEN_IF
;
1645 case OPENX_FILE_EXISTS_TRUNCATE
:
1646 create_disposition
= FILE_OVERWRITE
;
1649 case OPENX_FILE_EXISTS_TRUNCATE
|OPENX_FILE_CREATE_IF_NOT_EXIST
:
1650 create_disposition
= FILE_OVERWRITE_IF
;
1654 /* From samba4 - to be confirmed. */
1655 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_EXEC
) {
1656 create_disposition
= FILE_CREATE
;
1659 DEBUG(10,("map_open_params_to_ntcreate: bad "
1660 "open_func 0x%x\n", (unsigned int)open_func
));
1664 /* Create the NT compatible share modes. */
1665 switch (GET_DENY_MODE(deny_mode
)) {
1667 share_mode
= FILE_SHARE_NONE
;
1671 share_mode
= FILE_SHARE_READ
;
1675 share_mode
= FILE_SHARE_WRITE
;
1679 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
1683 private_flags
|= NTCREATEX_FLAG_DENY_DOS
;
1684 if (is_executable(smb_base_fname
)) {
1685 share_mode
= FILE_SHARE_READ
|FILE_SHARE_WRITE
;
1687 if (GET_OPENX_MODE(deny_mode
) == DOS_OPEN_RDONLY
) {
1688 share_mode
= FILE_SHARE_READ
;
1690 share_mode
= FILE_SHARE_NONE
;
1696 private_flags
|= NTCREATEX_FLAG_DENY_FCB
;
1697 share_mode
= FILE_SHARE_NONE
;
1701 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1702 (unsigned int)GET_DENY_MODE(deny_mode
) ));
1706 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1707 "share_mode = 0x%x, create_disposition = 0x%x, "
1708 "create_options = 0x%x private_flags = 0x%x\n",
1710 (unsigned int)access_mask
,
1711 (unsigned int)share_mode
,
1712 (unsigned int)create_disposition
,
1713 (unsigned int)create_options
,
1714 (unsigned int)private_flags
));
1717 *paccess_mask
= access_mask
;
1720 *pshare_mode
= share_mode
;
1722 if (pcreate_disposition
) {
1723 *pcreate_disposition
= create_disposition
;
1725 if (pcreate_options
) {
1726 *pcreate_options
= create_options
;
1728 if (pprivate_flags
) {
1729 *pprivate_flags
= private_flags
;
1736 /*************************************************************************
1737 Return a talloced copy of a struct security_unix_token. NULL on fail.
1738 *************************************************************************/
1740 struct security_unix_token
*copy_unix_token(TALLOC_CTX
*ctx
, const struct security_unix_token
*tok
)
1742 struct security_unix_token
*cpy
;
1744 cpy
= talloc(ctx
, struct security_unix_token
);
1749 *cpy
= (struct security_unix_token
){
1752 .ngroups
= tok
->ngroups
,
1756 /* Make this a talloc child of cpy. */
1757 cpy
->groups
= (gid_t
*)talloc_memdup(
1758 cpy
, tok
->groups
, tok
->ngroups
* sizeof(gid_t
));
1767 /****************************************************************************
1769 ****************************************************************************/
1771 struct security_unix_token
*root_unix_token(TALLOC_CTX
*mem_ctx
)
1773 struct security_unix_token
*t
= NULL
;
1775 t
= talloc_zero(mem_ctx
, struct security_unix_token
);
1781 * This is not needed, but lets make it explicit, not implicit.
1783 *t
= (struct security_unix_token
) {
1793 char *utok_string(TALLOC_CTX
*mem_ctx
, const struct security_unix_token
*tok
)
1798 str
= talloc_asprintf(
1800 "uid=%ju, gid=%ju, %"PRIu32
" groups:",
1801 (uintmax_t)(tok
->uid
),
1802 (uintmax_t)(tok
->gid
),
1805 for (i
=0; i
<tok
->ngroups
; i
++) {
1806 talloc_asprintf_addbuf(
1807 &str
, " %ju", (uintmax_t)tok
->groups
[i
]);
1813 /****************************************************************************
1814 Check that a file matches a particular file type.
1815 ****************************************************************************/
1817 bool dir_check_ftype(uint32_t mode
, uint32_t dirtype
)
1821 /* Check the "may have" search bits. */
1822 if (((mode
& ~dirtype
) &
1823 (FILE_ATTRIBUTE_HIDDEN
|
1824 FILE_ATTRIBUTE_SYSTEM
|
1825 FILE_ATTRIBUTE_DIRECTORY
)) != 0) {
1829 /* Check the "must have" bits,
1830 which are the may have bits shifted eight */
1831 /* If must have bit is set, the file/dir can
1832 not be returned in search unless the matching
1833 file attribute is set */
1834 mask
= ((dirtype
>> 8) & (FILE_ATTRIBUTE_DIRECTORY
|
1835 FILE_ATTRIBUTE_ARCHIVE
|
1836 FILE_ATTRIBUTE_READONLY
|
1837 FILE_ATTRIBUTE_HIDDEN
|
1838 FILE_ATTRIBUTE_SYSTEM
)); /* & 0x37 */
1840 if((mask
& (mode
& (FILE_ATTRIBUTE_DIRECTORY
|
1841 FILE_ATTRIBUTE_ARCHIVE
|
1842 FILE_ATTRIBUTE_READONLY
|
1843 FILE_ATTRIBUTE_HIDDEN
|
1844 FILE_ATTRIBUTE_SYSTEM
))) == mask
) {
1845 /* check if matching attribute present */