s3:lib: Fix code spelling
[Samba.git] / source3 / lib / util.c
blob93c01b862b35c02b438edd31d7e659a37b4e747f
1 /*
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/>.
24 /**
25 * @brief Small functions that don't fit anywhere else
26 * @file util.c
29 #include "includes.h"
30 #include "system/passwd.h"
31 #include "system/filesys.h"
32 #include "lib/util/server_id.h"
33 #include "util_tdb.h"
34 #include "ctdbd_conn.h"
35 #include "../lib/util/util_pw.h"
36 #include "messages.h"
37 #include "lib/messaging/messages_dgm.h"
38 #include "libcli/security/security.h"
39 #include "serverid.h"
40 #include "lib/util/sys_rw.h"
41 #include "lib/util/sys_rw_data.h"
42 #include "lib/util/util_process.h"
43 #include "lib/dbwrap/dbwrap_ctdb.h"
44 #include "lib/gencache.h"
45 #include "lib/util/string_wrappers.h"
47 #ifdef HAVE_SYS_PRCTL_H
48 #include <sys/prctl.h>
49 #endif
51 /* Max allowable allococation - 256mb - 0x10000000 */
52 #define MAX_ALLOC_SIZE (1024*1024*256)
54 static enum protocol_types Protocol = PROTOCOL_COREPLUS;
56 enum protocol_types get_Protocol(void)
58 return Protocol;
61 void set_Protocol(enum protocol_types p)
63 Protocol = p;
66 static enum remote_arch_types ra_type = RA_UNKNOWN;
68 void gfree_all( void )
70 gfree_loadparm();
71 gfree_charcnv();
72 gfree_interfaces();
73 gfree_debugsyms();
76 /*******************************************************************
77 Check if a file exists - call vfs_file_exist for samba files.
78 ********************************************************************/
80 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
81 bool fake_dir_create_times)
83 SMB_STRUCT_STAT st;
84 if (!sbuf)
85 sbuf = &st;
87 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
88 return(False);
90 return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
93 /*******************************************************************
94 Check if a unix domain socket exists - call vfs_file_exist for samba files.
95 ********************************************************************/
97 bool socket_exist(const char *fname)
99 SMB_STRUCT_STAT st;
100 if (sys_stat(fname, &st, false) != 0)
101 return(False);
103 return S_ISSOCK(st.st_ex_mode);
106 /*******************************************************************
107 Returns the size in bytes of the named given the stat struct.
108 ********************************************************************/
110 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
112 return sbuf->st_ex_size;
115 /****************************************************************************
116 Check two stats have identical dev and ino fields.
117 ****************************************************************************/
119 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
120 const SMB_STRUCT_STAT *sbuf2)
122 return ((sbuf1->st_ex_dev == sbuf2->st_ex_dev) &&
123 (sbuf1->st_ex_ino == sbuf2->st_ex_ino));
126 /****************************************************************************
127 Check if a stat struct is identical for use.
128 ****************************************************************************/
130 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
131 const SMB_STRUCT_STAT *sbuf2)
133 return ((sbuf1->st_ex_uid == sbuf2->st_ex_uid) &&
134 (sbuf1->st_ex_gid == sbuf2->st_ex_gid) &&
135 check_same_dev_ino(sbuf1, sbuf2));
138 /*******************************************************************
139 Show a smb message structure.
140 ********************************************************************/
142 void show_msg(const char *buf)
144 int i;
145 int bcc=0;
147 if (!DEBUGLVL(5))
148 return;
150 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
151 smb_len(buf),
152 (int)CVAL(buf,smb_com),
153 (int)CVAL(buf,smb_rcls),
154 (int)CVAL(buf,smb_reh),
155 (int)SVAL(buf,smb_err),
156 (int)CVAL(buf,smb_flg),
157 (int)SVAL(buf,smb_flg2)));
158 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
159 (int)SVAL(buf,smb_tid),
160 (int)SVAL(buf,smb_pid),
161 (int)SVAL(buf,smb_uid),
162 (int)SVAL(buf,smb_mid)));
163 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
165 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
166 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
167 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
169 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
171 DEBUGADD(5,("smb_bcc=%d\n",bcc));
173 if (DEBUGLEVEL < 10)
174 return;
176 if (DEBUGLEVEL < 50)
177 bcc = MIN(bcc, 512);
179 dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
182 /*******************************************************************
183 Setup only the byte count for a smb message.
184 ********************************************************************/
186 int set_message_bcc(char *buf,int num_bytes)
188 int num_words = CVAL(buf,smb_wct);
189 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
190 _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
191 return (smb_size + num_words*2 + num_bytes);
194 /*******************************************************************
195 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
196 Return the bytes added
197 ********************************************************************/
199 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
201 size_t newlen = smb_len(*outbuf) + 4 + blob.length;
202 uint8_t *tmp;
204 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
205 DEBUG(0, ("talloc failed\n"));
206 return -1;
208 *outbuf = tmp;
210 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
211 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
212 return blob.length;
215 /*******************************************************************
216 Reduce a file name, removing .. elements.
217 ********************************************************************/
219 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
221 char *p = NULL;
222 char *str = NULL;
224 DEBUG(3,("dos_clean_name [%s]\n",s));
226 /* remove any double slashes */
227 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
228 if (!str) {
229 return NULL;
232 /* Remove leading .\\ characters */
233 if(strncmp(str, ".\\", 2) == 0) {
234 trim_string(str, ".\\", NULL);
235 if(*str == 0) {
236 str = talloc_strdup(ctx, ".\\");
237 if (!str) {
238 return NULL;
243 while ((p = strstr_m(str,"\\..\\")) != NULL) {
244 char *s1;
246 *p = 0;
247 s1 = p+3;
249 if ((p=strrchr_m(str,'\\')) != NULL) {
250 *p = 0;
251 } else {
252 *str = 0;
254 str = talloc_asprintf(ctx,
255 "%s%s",
256 str,
257 s1);
258 if (!str) {
259 return NULL;
263 trim_string(str,NULL,"\\..");
264 return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
267 /*******************************************************************
268 Reduce a file name, removing .. elements.
269 ********************************************************************/
271 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
273 char *p = NULL;
274 char *str = NULL;
276 DEBUG(3,("unix_clean_name [%s]\n",s));
278 /* remove any double slashes */
279 str = talloc_all_string_sub(ctx, s, "//","/");
280 if (!str) {
281 return NULL;
284 /* Remove leading ./ characters */
285 if(strncmp(str, "./", 2) == 0) {
286 trim_string(str, "./", NULL);
287 if(*str == 0) {
288 str = talloc_strdup(ctx, "./");
289 if (!str) {
290 return NULL;
295 while ((p = strstr_m(str,"/../")) != NULL) {
296 char *s1;
298 *p = 0;
299 s1 = p+3;
301 if ((p=strrchr_m(str,'/')) != NULL) {
302 *p = 0;
303 } else {
304 *str = 0;
306 str = talloc_asprintf(ctx,
307 "%s%s",
308 str,
309 s1);
310 if (!str) {
311 return NULL;
315 trim_string(str,NULL,"/..");
316 return talloc_all_string_sub(ctx, str, "/./", "/");
319 char *clean_name(TALLOC_CTX *ctx, const char *s)
321 char *str = dos_clean_name(ctx, s);
322 if (!str) {
323 return NULL;
325 return unix_clean_name(ctx, str);
328 /*******************************************************************
329 Write data into an fd at a given offset. Ignore seek errors.
330 ********************************************************************/
332 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
334 size_t total=0;
335 ssize_t ret;
337 if (pos == (off_t)-1) {
338 return write_data(fd, buffer, N);
340 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
341 while (total < N) {
342 ret = sys_pwrite(fd,buffer + total,N - total, pos);
343 if (ret == -1 && errno == ESPIPE) {
344 return write_data(fd, buffer + total,N - total);
346 if (ret == -1) {
347 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
348 return -1;
350 if (ret == 0) {
351 return total;
353 total += ret;
354 pos += ret;
356 return (ssize_t)total;
357 #else
358 /* Use lseek and write_data. */
359 if (lseek(fd, pos, SEEK_SET) == -1) {
360 if (errno != ESPIPE) {
361 return -1;
364 return write_data(fd, buffer, N);
365 #endif
368 static int reinit_after_fork_pipe[2] = { -1, -1 };
370 NTSTATUS init_before_fork(void)
372 int ret;
374 ret = pipe(reinit_after_fork_pipe);
375 if (ret == -1) {
376 NTSTATUS status;
378 status = map_nt_error_from_unix_common(errno);
380 DEBUG(0, ("Error creating child_pipe: %s\n",
381 nt_errstr(status)));
383 return status;
386 return NT_STATUS_OK;
390 * @brief Get a fd to watch for our parent process to exit
392 * Samba parent processes open a pipe that naturally closes when the
393 * parent exits. Child processes can watch the read end of the pipe
394 * for readability: Readability with 0 bytes to read means the parent
395 * has exited and the child process might also want to exit.
398 int parent_watch_fd(void)
400 return reinit_after_fork_pipe[0];
404 * Detect died parent by detecting EOF on the pipe
406 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
407 struct tevent_fd *fde,
408 uint16_t flags,
409 void *private_data)
411 char c;
413 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
415 * we have reached EOF on stdin, which means the
416 * parent has exited. Shutdown the server
418 TALLOC_FREE(fde);
419 (void)kill(getpid(), SIGTERM);
424 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
425 struct tevent_context *ev_ctx,
426 bool parent_longlived)
428 NTSTATUS status = NT_STATUS_OK;
429 int ret;
432 * The main process thread should never
433 * allow per_thread_cwd_enable() to be
434 * called.
436 per_thread_cwd_disable();
438 if (reinit_after_fork_pipe[1] != -1) {
439 close(reinit_after_fork_pipe[1]);
440 reinit_after_fork_pipe[1] = -1;
443 /* tdb needs special fork handling */
444 if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
445 DEBUG(0,("tdb_reopen_all failed.\n"));
446 status = NT_STATUS_OPEN_FAILED;
447 goto done;
450 if (ev_ctx != NULL) {
452 * The parent can have different private data for the callbacks,
453 * which are gone in the child. Reset the callbacks to be safe.
455 tevent_set_trace_callback(ev_ctx, NULL, NULL);
456 tevent_set_trace_fd_callback(ev_ctx, NULL, NULL);
457 tevent_set_trace_signal_callback(ev_ctx, NULL, NULL);
458 tevent_set_trace_timer_callback(ev_ctx, NULL, NULL);
459 tevent_set_trace_immediate_callback(ev_ctx, NULL, NULL);
460 tevent_set_trace_queue_callback(ev_ctx, NULL, NULL);
461 if (tevent_re_initialise(ev_ctx) != 0) {
462 smb_panic(__location__ ": Failed to re-initialise event context");
466 if (reinit_after_fork_pipe[0] != -1) {
467 struct tevent_fd *fde;
469 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
470 reinit_after_fork_pipe[0], TEVENT_FD_READ,
471 reinit_after_fork_pipe_handler, NULL);
472 if (fde == NULL) {
473 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
477 if (msg_ctx) {
479 * For clustering, we need to re-init our ctdbd connection after the
480 * fork
482 status = messaging_reinit(msg_ctx);
483 if (!NT_STATUS_IS_OK(status)) {
484 DEBUG(0,("messaging_reinit() failed: %s\n",
485 nt_errstr(status)));
488 if (lp_clustering()) {
489 ret = ctdb_async_ctx_reinit(
490 NULL, messaging_tevent_context(msg_ctx));
491 if (ret != 0) {
492 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
493 strerror(errno));
494 return map_nt_error_from_unix(ret);
499 done:
500 return status;
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,
509 ssize_t *array_size)
511 void **array = (void **)_array;
513 if (*array_size < 0) {
514 return;
517 if (*array == NULL) {
518 if (*array_size == 0) {
519 *array_size = 128;
522 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
523 goto error;
526 *array = TALLOC(mem_ctx, element_size * (*array_size));
527 if (*array == NULL) {
528 goto error;
532 if (*num_elements == *array_size) {
533 *array_size *= 2;
535 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
536 goto error;
539 *array = TALLOC_REALLOC(mem_ctx, *array,
540 element_size * (*array_size));
542 if (*array == NULL) {
543 goto error;
547 memcpy((char *)(*array) + element_size*(*num_elements),
548 element, element_size);
549 *num_elements += 1;
551 return;
553 error:
554 *num_elements = 0;
555 *array_size = -1;
558 /****************************************************************************
559 Get my own domain name, or "" if we have none.
560 ****************************************************************************/
562 char *get_mydnsdomname(TALLOC_CTX *ctx)
564 const char *domname;
565 char *p;
567 domname = get_mydnsfullname();
568 if (!domname) {
569 return NULL;
572 p = strchr_m(domname, '.');
573 if (p) {
574 p++;
575 return talloc_strdup(ctx, p);
576 } else {
577 return talloc_strdup(ctx, "");
581 bool process_exists(const struct server_id pid)
583 return serverid_exists(&pid);
586 /*******************************************************************
587 Convert a uid into a user name.
588 ********************************************************************/
590 const char *uidtoname(uid_t uid)
592 TALLOC_CTX *ctx = talloc_tos();
593 char *name = NULL;
594 struct passwd *pass = NULL;
596 pass = getpwuid_alloc(ctx,uid);
597 if (pass) {
598 name = talloc_strdup(ctx,pass->pw_name);
599 TALLOC_FREE(pass);
600 } else {
601 name = talloc_asprintf(ctx,
602 "%ld",
603 (long int)uid);
605 return name;
608 /*******************************************************************
609 Convert a gid into a group name.
610 ********************************************************************/
612 char *gidtoname(gid_t gid)
614 struct group *grp;
616 grp = getgrgid(gid);
617 if (grp) {
618 return talloc_strdup(talloc_tos(), grp->gr_name);
620 else {
621 return talloc_asprintf(talloc_tos(),
622 "%d",
623 (int)gid);
627 /*******************************************************************
628 Convert a user name into a uid.
629 ********************************************************************/
631 uid_t nametouid(const char *name)
633 struct passwd *pass;
634 char *p;
635 uid_t u;
637 pass = Get_Pwnam_alloc(talloc_tos(), name);
638 if (pass) {
639 u = pass->pw_uid;
640 TALLOC_FREE(pass);
641 return u;
644 u = (uid_t)strtol(name, &p, 0);
645 if ((p != name) && (*p == '\0'))
646 return u;
648 return (uid_t)-1;
651 /*******************************************************************
652 Convert a name to a gid_t if possible. Return -1 if not a group.
653 ********************************************************************/
655 gid_t nametogid(const char *name)
657 struct group *grp;
658 char *p;
659 gid_t g;
661 g = (gid_t)strtol(name, &p, 0);
662 if ((p != name) && (*p == '\0'))
663 return g;
665 grp = getgrnam(name);
666 if (grp)
667 return(grp->gr_gid);
668 return (gid_t)-1;
671 /*******************************************************************
672 Something really nasty happened - panic !
673 ********************************************************************/
675 void smb_panic_s3(const char *why)
677 const struct loadparm_substitution *lp_sub =
678 loadparm_s3_global_substitution();
679 char *cmd;
680 int result;
682 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
684 * Make sure all children can attach a debugger.
686 prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
687 #endif
689 cmd = lp_panic_action(talloc_tos(), lp_sub);
690 if (cmd && *cmd) {
691 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
692 result = system(cmd);
694 if (result == -1)
695 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
696 strerror(errno)));
697 else
698 DEBUG(0, ("smb_panic(): action returned status %d\n",
699 WEXITSTATUS(result)));
702 dump_core();
705 /*******************************************************************
706 A readdir wrapper which just returns the file name.
707 ********************************************************************/
709 const char *readdirname(DIR *p)
711 struct dirent *ptr;
712 char *dname;
714 if (!p)
715 return(NULL);
717 ptr = (struct dirent *)readdir(p);
718 if (!ptr)
719 return(NULL);
721 dname = ptr->d_name;
723 return talloc_strdup(talloc_tos(), dname);
726 /*******************************************************************
727 Utility function used to decide if the last component
728 of a path matches a (possibly wildcarded) entry in a namelist.
729 ********************************************************************/
731 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
733 const char *last_component;
735 /* if we have no list it's obviously not in the path */
736 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
737 return False;
740 /* Do not reject path components if namelist is set to '.*' */
741 if (ISDOT(name) || ISDOTDOT(name)) {
742 return false;
745 DEBUG(8, ("is_in_path: %s\n", name));
747 /* Get the last component of the unix name. */
748 last_component = strrchr_m(name, '/');
749 if (!last_component) {
750 last_component = name;
751 } else {
752 last_component++; /* Go past '/' */
755 for(; namelist->name != NULL; namelist++) {
756 if(namelist->is_wild) {
757 if (mask_match(last_component, namelist->name, case_sensitive)) {
758 DEBUG(8,("is_in_path: mask match succeeded\n"));
759 return True;
761 } else {
762 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
763 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
764 DEBUG(8,("is_in_path: match succeeded\n"));
765 return True;
769 DEBUG(8,("is_in_path: match not found\n"));
770 return False;
773 /*******************************************************************
774 Strip a '/' separated list into an array of
775 name_compare_enties structures suitable for
776 passing to is_in_path(). We do this for
777 speed so we can pre-parse all the names in the list
778 and don't do it for each call to is_in_path().
779 We also check if the entry contains a wildcard to
780 remove a potentially expensive call to mask_match
781 if possible.
782 ********************************************************************/
784 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
786 char *name_end;
787 char *namelist;
788 char *namelist_end;
789 char *nameptr;
790 int num_entries = 0;
791 int i;
793 (*ppname_array) = NULL;
795 if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
796 return;
798 namelist = talloc_strdup(talloc_tos(), namelist_in);
799 if (namelist == NULL) {
800 DEBUG(0,("set_namearray: talloc fail\n"));
801 return;
803 nameptr = namelist;
805 namelist_end = &namelist[strlen(namelist)];
807 /* We need to make two passes over the string. The
808 first to count the number of elements, the second
809 to split it.
812 while(nameptr <= namelist_end) {
813 if ( *nameptr == '/' ) {
814 /* cope with multiple (useless) /s) */
815 nameptr++;
816 continue;
818 /* anything left? */
819 if ( *nameptr == '\0' )
820 break;
822 /* find the next '/' or consume remaining */
823 name_end = strchr_m(nameptr, '/');
824 if (name_end == NULL) {
825 /* Point nameptr at the terminating '\0' */
826 nameptr += strlen(nameptr);
827 } else {
828 /* next segment please */
829 nameptr = name_end + 1;
831 num_entries++;
834 if(num_entries == 0) {
835 talloc_free(namelist);
836 return;
839 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
840 DEBUG(0,("set_namearray: malloc fail\n"));
841 talloc_free(namelist);
842 return;
845 /* Now copy out the names */
846 nameptr = namelist;
847 i = 0;
848 while(nameptr <= namelist_end) {
849 if ( *nameptr == '/' ) {
850 /* cope with multiple (useless) /s) */
851 nameptr++;
852 continue;
854 /* anything left? */
855 if ( *nameptr == '\0' )
856 break;
858 /* find the next '/' or consume remaining */
859 name_end = strchr_m(nameptr, '/');
860 if (name_end != NULL) {
861 *name_end = '\0';
864 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
865 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
866 DEBUG(0,("set_namearray: malloc fail (1)\n"));
867 talloc_free(namelist);
868 return;
871 if (name_end == NULL) {
872 /* Point nameptr at the terminating '\0' */
873 nameptr += strlen(nameptr);
874 } else {
875 /* next segment please */
876 nameptr = name_end + 1;
878 i++;
881 (*ppname_array)[i].name = NULL;
883 talloc_free(namelist);
884 return;
887 #undef DBGC_CLASS
888 #define DBGC_CLASS DBGC_LOCKING
890 /****************************************************************************
891 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
892 is dealt with in posix.c
893 Returns True if we have information regarding this lock region (and returns
894 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
895 ****************************************************************************/
897 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
899 struct flock lock;
900 int ret;
902 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
903 fd,op,(double)*poffset,(double)*pcount,*ptype));
905 lock.l_type = *ptype;
906 lock.l_whence = SEEK_SET;
907 lock.l_start = *poffset;
908 lock.l_len = *pcount;
909 lock.l_pid = 0;
911 ret = sys_fcntl_ptr(fd,op,&lock);
913 if (ret == -1) {
914 int saved_errno = errno;
915 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
916 (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
917 errno = saved_errno;
918 return False;
921 *ptype = lock.l_type;
922 *poffset = lock.l_start;
923 *pcount = lock.l_len;
924 *ppid = lock.l_pid;
926 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
927 fd, (int)lock.l_type, (unsigned int)lock.l_pid));
928 return True;
931 #if defined(HAVE_OFD_LOCKS)
932 int map_process_lock_to_ofd_lock(int op)
934 switch (op) {
935 case F_GETLK:
936 case F_OFD_GETLK:
937 op = F_OFD_GETLK;
938 break;
939 case F_SETLK:
940 case F_OFD_SETLK:
941 op = F_OFD_SETLK;
942 break;
943 case F_SETLKW:
944 case F_OFD_SETLKW:
945 op = F_OFD_SETLKW;
946 break;
947 default:
948 return -1;
950 return op;
952 #else /* HAVE_OFD_LOCKS */
953 int map_process_lock_to_ofd_lock(int op)
955 return op;
957 #endif /* HAVE_OFD_LOCKS */
959 #undef DBGC_CLASS
960 #define DBGC_CLASS DBGC_ALL
962 /*******************************************************************
963 Is the name specified one of my netbios names.
964 Returns true if it is equal, false otherwise.
965 ********************************************************************/
967 static bool nb_name_equal(const char *s1, const char *s2)
969 int cmp = strncasecmp_m(s1, s2, MAX_NETBIOSNAME_LEN-1);
970 return (cmp == 0);
973 bool is_myname(const char *s)
975 const char **aliases = NULL;
976 bool ok = false;
978 ok = nb_name_equal(lp_netbios_name(), s);
979 if (ok) {
980 goto done;
983 aliases = lp_netbios_aliases();
984 if (aliases == NULL) {
985 goto done;
988 while (*aliases != NULL) {
989 ok = nb_name_equal(*aliases, s);
990 if (ok) {
991 goto done;
993 aliases += 1;
996 done:
997 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s, (int)ok);
998 return ok;
1001 /*******************************************************************
1002 we distinguish between 2K and XP by the "Native Lan Manager" string
1003 WinXP => "Windows 2002 5.1"
1004 WinXP 64bit => "Windows XP 5.2"
1005 Win2k => "Windows 2000 5.0"
1006 NT4 => "Windows NT 4.0"
1007 Win9x => "Windows 4.0"
1008 Windows 2003 doesn't set the native lan manager string but
1009 they do set the domain to "Windows 2003 5.2" (probably a bug).
1010 ********************************************************************/
1012 void ra_lanman_string( const char *native_lanman )
1014 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1015 set_remote_arch( RA_WINXP );
1016 else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1017 set_remote_arch( RA_WINXP64 );
1018 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1019 set_remote_arch( RA_WIN2K3 );
1022 static const char *remote_arch_strings[] = {
1023 [RA_UNKNOWN] = "UNKNOWN",
1024 [RA_WFWG] = "WfWg",
1025 [RA_OS2] = "OS2",
1026 [RA_WIN95] = "Win95",
1027 [RA_WINNT] = "WinNT",
1028 [RA_WIN2K] = "Win2K",
1029 [RA_WINXP] = "WinXP",
1030 [RA_WIN2K3] = "Win2K3",
1031 [RA_VISTA] = "Vista",
1032 [RA_SAMBA] = "Samba",
1033 [RA_CIFSFS] = "CIFSFS",
1034 [RA_WINXP64] = "WinXP64",
1035 [RA_OSX] = "OSX",
1038 const char *get_remote_arch_str(void)
1040 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1042 * set_remote_arch() already checks this so ra_type
1043 * should be in the allowed range, but anyway, let's
1044 * do another bound check here.
1046 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1047 ra_type = RA_UNKNOWN;
1049 return remote_arch_strings[ra_type];
1052 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1054 int i;
1056 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1057 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1058 return i;
1061 return RA_UNKNOWN;
1064 /*******************************************************************
1065 Set the horrid remote_arch string based on an enum.
1066 ********************************************************************/
1068 void set_remote_arch(enum remote_arch_types type)
1070 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1072 * This protects against someone adding values to enum
1073 * remote_arch_types without updating
1074 * remote_arch_strings array.
1076 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1077 ra_type = RA_UNKNOWN;
1078 return;
1081 ra_type = type;
1082 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1083 get_remote_arch_str()));
1086 /*******************************************************************
1087 Get the remote_arch type.
1088 ********************************************************************/
1090 enum remote_arch_types get_remote_arch(void)
1092 return ra_type;
1095 #define RA_CACHE_TTL 7*24*3600
1097 static bool remote_arch_cache_key(const struct GUID *client_guid,
1098 fstring key)
1100 struct GUID_txt_buf guid_buf;
1101 const char *guid_string = NULL;
1103 guid_string = GUID_buf_string(client_guid, &guid_buf);
1104 if (guid_string == NULL) {
1105 return false;
1108 fstr_sprintf(key, "RA/%s", guid_string);
1109 return true;
1112 struct ra_parser_state {
1113 bool found;
1114 enum remote_arch_types ra;
1117 static void ra_parser(const struct gencache_timeout *t,
1118 DATA_BLOB blob,
1119 void *priv_data)
1121 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1122 const char *ra_str = NULL;
1124 if (gencache_timeout_expired(t)) {
1125 return;
1128 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1129 DBG_ERR("Remote arch cache key not a string\n");
1130 return;
1133 ra_str = (const char *)blob.data;
1134 DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1136 state->ra = get_remote_arch_from_str(ra_str);
1137 state->found = true;
1138 return;
1141 static bool remote_arch_cache_get(const struct GUID *client_guid)
1143 bool ok;
1144 fstring ra_key;
1145 struct ra_parser_state state = (struct ra_parser_state) {
1146 .found = false,
1147 .ra = RA_UNKNOWN,
1150 ok = remote_arch_cache_key(client_guid, ra_key);
1151 if (!ok) {
1152 return false;
1155 ok = gencache_parse(ra_key, ra_parser, &state);
1156 if (!ok || !state.found) {
1157 return true;
1160 if (state.ra == RA_UNKNOWN) {
1161 return true;
1164 set_remote_arch(state.ra);
1165 return true;
1168 static bool remote_arch_cache_set(const struct GUID *client_guid)
1170 bool ok;
1171 fstring ra_key;
1172 const char *ra_str = NULL;
1174 if (get_remote_arch() == RA_UNKNOWN) {
1175 return true;
1178 ok = remote_arch_cache_key(client_guid, ra_key);
1179 if (!ok) {
1180 return false;
1183 ra_str = get_remote_arch_str();
1184 if (ra_str == NULL) {
1185 return false;
1188 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1189 if (!ok) {
1190 return false;
1193 return true;
1196 bool remote_arch_cache_update(const struct GUID *client_guid)
1198 bool ok;
1200 if (get_remote_arch() == RA_UNKNOWN) {
1202 become_root();
1203 ok = remote_arch_cache_get(client_guid);
1204 unbecome_root();
1206 return ok;
1209 become_root();
1210 ok = remote_arch_cache_set(client_guid);
1211 unbecome_root();
1213 return ok;
1216 bool remote_arch_cache_delete(const struct GUID *client_guid)
1218 bool ok;
1219 fstring ra_key;
1221 ok = remote_arch_cache_key(client_guid, ra_key);
1222 if (!ok) {
1223 return false;
1226 become_root();
1227 ok = gencache_del(ra_key);
1228 unbecome_root();
1230 if (!ok) {
1231 return false;
1234 return true;
1238 /*****************************************************************************
1239 Provide a checksum on a string
1241 Input: s - the null-terminated character string for which the checksum
1242 will be calculated.
1244 Output: The checksum value calculated for s.
1245 *****************************************************************************/
1247 int str_checksum(const char *s)
1249 TDB_DATA key;
1250 if (s == NULL)
1251 return 0;
1253 key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1254 .dsize = strlen(s) };
1256 return tdb_jenkins_hash(&key);
1259 /*****************************************************************
1260 Zero a memory area then free it. Used to catch bugs faster.
1261 *****************************************************************/
1263 void zero_free(void *p, size_t size)
1265 memset(p, 0, size);
1266 SAFE_FREE(p);
1269 /*****************************************************************
1270 Set our open file limit to a requested max and return the limit.
1271 *****************************************************************/
1273 int set_maxfiles(int requested_max)
1275 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1276 struct rlimit rlp;
1277 int saved_current_limit;
1279 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1280 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1281 strerror(errno) ));
1282 /* just guess... */
1283 return requested_max;
1287 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1288 * account for the extra fd we need
1289 * as well as the log files and standard
1290 * handles etc. Save the limit we want to set in case
1291 * we are running on an OS that doesn't support this limit (AIX)
1292 * which always returns RLIM_INFINITY for rlp.rlim_max.
1295 /* Try raising the hard (max) limit to the requested amount. */
1297 #if defined(RLIM_INFINITY)
1298 if (rlp.rlim_max != RLIM_INFINITY) {
1299 int orig_max = rlp.rlim_max;
1301 if ( rlp.rlim_max < requested_max )
1302 rlp.rlim_max = requested_max;
1304 /* This failing is not an error - many systems (Linux) don't
1305 support our default request of 10,000 open files. JRA. */
1307 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1308 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1309 (int)rlp.rlim_max, strerror(errno) ));
1311 /* Set failed - restore original value from get. */
1312 rlp.rlim_max = orig_max;
1315 #endif
1317 /* Now try setting the soft (current) limit. */
1319 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1321 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1322 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1323 (int)rlp.rlim_cur, strerror(errno) ));
1324 /* just guess... */
1325 return saved_current_limit;
1328 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1329 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1330 strerror(errno) ));
1331 /* just guess... */
1332 return saved_current_limit;
1335 #if defined(RLIM_INFINITY)
1336 if(rlp.rlim_cur == RLIM_INFINITY)
1337 return saved_current_limit;
1338 #endif
1340 if((int)rlp.rlim_cur > saved_current_limit)
1341 return saved_current_limit;
1343 return rlp.rlim_cur;
1344 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1346 * No way to know - just guess...
1348 return requested_max;
1349 #endif
1352 /*****************************************************************
1353 malloc that aborts with smb_panic on fail or zero size.
1354 *****************************************************************/
1356 void *smb_xmalloc_array(size_t size, unsigned int count)
1358 void *p;
1359 if (size == 0) {
1360 smb_panic("smb_xmalloc_array: called with zero size");
1362 if (count >= MAX_ALLOC_SIZE/size) {
1363 smb_panic("smb_xmalloc_array: alloc size too large");
1365 if ((p = SMB_MALLOC(size*count)) == NULL) {
1366 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1367 (unsigned long)size, (unsigned long)count));
1368 smb_panic("smb_xmalloc_array: malloc failed");
1370 return p;
1373 /*****************************************************************
1374 Get local hostname and cache result.
1375 *****************************************************************/
1377 char *myhostname(void)
1379 static char *ret;
1380 if (ret == NULL) {
1381 ret = get_myname(NULL);
1383 return ret;
1386 /*****************************************************************
1387 Get local hostname and cache result.
1388 *****************************************************************/
1390 char *myhostname_upper(void)
1392 static char *ret;
1393 if (ret == NULL) {
1394 char *name = get_myname(NULL);
1395 if (name == NULL) {
1396 return NULL;
1398 ret = strupper_talloc(NULL, name);
1399 talloc_free(name);
1401 return ret;
1404 /*******************************************************************
1405 Given a filename - get its directory name
1406 ********************************************************************/
1408 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1409 const char **name)
1411 char *p;
1412 ptrdiff_t len;
1414 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1416 if (p == NULL) {
1417 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1418 return False;
1420 if (name) {
1421 *name = dir;
1423 return True;
1426 len = p-dir;
1428 *parent = talloc_strndup(mem_ctx, dir, len);
1429 if (*parent == NULL) {
1430 return False;
1433 if (name) {
1434 *name = p+1;
1436 return True;
1439 /*******************************************************************
1440 Determine if a pattern contains any Microsoft wildcard characters.
1441 *******************************************************************/
1443 bool ms_has_wild(const char *s)
1445 const char *found = strpbrk(s, "*?<>\"");
1446 return (found != NULL);
1449 bool ms_has_wild_w(const smb_ucs2_t *s)
1451 smb_ucs2_t c;
1452 if (!s) return False;
1453 while ((c = *s++)) {
1454 switch (c) {
1455 case UCS2_CHAR('*'):
1456 case UCS2_CHAR('?'):
1457 case UCS2_CHAR('<'):
1458 case UCS2_CHAR('>'):
1459 case UCS2_CHAR('"'):
1460 return True;
1463 return False;
1466 /*******************************************************************
1467 A wrapper that handles case sensitivity and the special handling
1468 of the ".." name.
1469 *******************************************************************/
1471 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1473 if (ISDOTDOT(string))
1474 string = ".";
1475 if (ISDOT(pattern))
1476 return False;
1478 return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1481 /*******************************************************************
1482 A wrapper that handles case sensitivity and the special handling
1483 of the ".." name. Variant that is only called by old search code which requires
1484 pattern translation.
1485 *******************************************************************/
1487 bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
1489 if (ISDOTDOT(string))
1490 string = ".";
1491 if (ISDOT(pattern))
1492 return False;
1494 return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
1497 /*******************************************************************
1498 A wrapper that handles a list of patterns and calls mask_match()
1499 on each. Returns True if any of the patterns match.
1500 *******************************************************************/
1502 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1504 while (listLen-- > 0) {
1505 if (mask_match(string, *list++, is_case_sensitive))
1506 return True;
1508 return False;
1511 /**********************************************************************
1512 Converts a name to a fully qualified domain name.
1513 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1514 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1515 canonical name of the host. getaddrinfo() may use a variety of sources
1516 including /etc/hosts to obtain the domainname. It expects aliases in
1517 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1518 ************************************************************************/
1520 bool name_to_fqdn(fstring fqdn, const char *name)
1522 char *full = NULL;
1523 struct addrinfo hints;
1524 struct addrinfo *result;
1525 int s;
1527 /* Configure hints to obtain canonical name */
1529 memset(&hints, 0, sizeof(struct addrinfo));
1530 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1531 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1532 hints.ai_flags = AI_CANONNAME; /* Get host's FQDN */
1533 hints.ai_protocol = 0; /* Any protocol */
1535 s = getaddrinfo(name, NULL, &hints, &result);
1536 if (s != 0) {
1537 DBG_WARNING("getaddrinfo lookup for %s failed: %s\n",
1538 name,
1539 gai_strerror(s));
1540 fstrcpy(fqdn, name);
1541 return false;
1543 full = result->ai_canonname;
1545 /* Find out if the FQDN is returned as an alias
1546 * to cope with /etc/hosts files where the first
1547 * name is not the FQDN but the short name.
1548 * getaddrinfo provides no easy way of handling aliases
1549 * in /etc/hosts. Users should make sure the FQDN
1550 * comes first in /etc/hosts. */
1551 if (full && (! strchr_m(full, '.'))) {
1552 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1553 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1554 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1555 DEBUGADD(1, (" prior to any aliases.\n"));
1557 if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1558 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1559 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1560 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1561 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1564 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1565 fstrcpy(fqdn, full);
1566 freeaddrinfo(result); /* No longer needed */
1567 return true;
1570 struct server_id interpret_pid(const char *pid_string)
1572 return server_id_from_string(get_my_vnn(), pid_string);
1575 /****************************************************************
1576 Check if an offset into a buffer is safe.
1577 If this returns True it's safe to indirect into the byte at
1578 pointer ptr+off.
1579 ****************************************************************/
1581 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1583 const char *end_base = buf_base + buf_len;
1584 char *end_ptr = ptr + off;
1586 if (!buf_base || !ptr) {
1587 return False;
1590 if (end_base < buf_base || end_ptr < ptr) {
1591 return False; /* wrap. */
1594 if (end_ptr < end_base) {
1595 return True;
1597 return False;
1600 /****************************************************************
1601 Return a safe pointer into a string within a buffer, or NULL.
1602 ****************************************************************/
1604 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1606 if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1607 return NULL;
1609 /* Check if a valid string exists at this offset. */
1610 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1611 return NULL;
1613 return ptr + off;
1617 /****************************************************************
1618 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1619 call (they take care of winbind separator and other winbind specific settings).
1620 ****************************************************************/
1622 bool split_domain_user(TALLOC_CTX *mem_ctx,
1623 const char *full_name,
1624 char **domain,
1625 char **user)
1627 const char *p = NULL;
1629 p = strchr_m(full_name, '\\');
1631 if (p != NULL) {
1632 *domain = talloc_strndup(mem_ctx, full_name,
1633 PTR_DIFF(p, full_name));
1634 if (*domain == NULL) {
1635 return false;
1637 *user = talloc_strdup(mem_ctx, p+1);
1638 if (*user == NULL) {
1639 TALLOC_FREE(*domain);
1640 return false;
1642 } else {
1643 *domain = NULL;
1644 *user = talloc_strdup(mem_ctx, full_name);
1645 if (*user == NULL) {
1646 return false;
1650 return true;
1653 /****************************************************************
1654 strip off leading '\\' from a hostname
1655 ****************************************************************/
1657 const char *strip_hostname(const char *s)
1659 if (!s) {
1660 return NULL;
1663 if (strlen_m(s) < 3) {
1664 return s;
1667 if (s[0] == '\\') s++;
1668 if (s[0] == '\\') s++;
1670 return s;
1673 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1675 if (!NT_STATUS_IS_OK(err1)) {
1676 *result = err1;
1677 return true;
1679 if (!NT_STATUS_IS_OK(err2)) {
1680 *result = err2;
1681 return true;
1683 return false;
1686 int timeval_to_msec(struct timeval t)
1688 return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
1691 /*******************************************************************
1692 Check a given DOS pathname is valid for a share.
1693 ********************************************************************/
1695 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
1697 char *ptr = NULL;
1699 if (!dos_pathname) {
1700 return NULL;
1703 ptr = talloc_strdup(ctx, dos_pathname);
1704 if (!ptr) {
1705 return NULL;
1707 /* Convert any '\' paths to '/' */
1708 unix_format(ptr);
1709 ptr = unix_clean_name(ctx, ptr);
1710 if (!ptr) {
1711 return NULL;
1714 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1715 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1716 ptr += 2;
1718 /* Only absolute paths allowed. */
1719 if (*ptr != '/')
1720 return NULL;
1722 return ptr;
1725 /*******************************************************************
1726 Return True if the filename is one of the special executable types.
1727 ********************************************************************/
1729 bool is_executable(const char *fname)
1731 if ((fname = strrchr_m(fname,'.'))) {
1732 if (strequal(fname,".com") ||
1733 strequal(fname,".dll") ||
1734 strequal(fname,".exe") ||
1735 strequal(fname,".sym")) {
1736 return True;
1739 return False;
1742 /****************************************************************************
1743 Open a file with a share mode - old openX method - map into NTCreate.
1744 ****************************************************************************/
1746 bool map_open_params_to_ntcreate(const char *smb_base_fname,
1747 int deny_mode, int open_func,
1748 uint32_t *paccess_mask,
1749 uint32_t *pshare_mode,
1750 uint32_t *pcreate_disposition,
1751 uint32_t *pcreate_options,
1752 uint32_t *pprivate_flags)
1754 uint32_t access_mask;
1755 uint32_t share_mode;
1756 uint32_t create_disposition;
1757 uint32_t create_options = FILE_NON_DIRECTORY_FILE;
1758 uint32_t private_flags = 0;
1760 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
1761 "open_func = 0x%x\n",
1762 smb_base_fname, (unsigned int)deny_mode,
1763 (unsigned int)open_func ));
1765 /* Create the NT compatible access_mask. */
1766 switch (GET_OPENX_MODE(deny_mode)) {
1767 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
1768 case DOS_OPEN_RDONLY:
1769 access_mask = FILE_GENERIC_READ;
1770 break;
1771 case DOS_OPEN_WRONLY:
1772 access_mask = FILE_GENERIC_WRITE;
1773 break;
1774 case DOS_OPEN_RDWR:
1775 case DOS_OPEN_FCB:
1776 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1777 break;
1778 default:
1779 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1780 (unsigned int)GET_OPENX_MODE(deny_mode)));
1781 return False;
1784 /* Create the NT compatible create_disposition. */
1785 switch (open_func) {
1786 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
1787 create_disposition = FILE_CREATE;
1788 break;
1790 case OPENX_FILE_EXISTS_OPEN:
1791 create_disposition = FILE_OPEN;
1792 break;
1794 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
1795 create_disposition = FILE_OPEN_IF;
1796 break;
1798 case OPENX_FILE_EXISTS_TRUNCATE:
1799 create_disposition = FILE_OVERWRITE;
1800 break;
1802 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1803 create_disposition = FILE_OVERWRITE_IF;
1804 break;
1806 default:
1807 /* From samba4 - to be confirmed. */
1808 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1809 create_disposition = FILE_CREATE;
1810 break;
1812 DEBUG(10,("map_open_params_to_ntcreate: bad "
1813 "open_func 0x%x\n", (unsigned int)open_func));
1814 return False;
1817 /* Create the NT compatible share modes. */
1818 switch (GET_DENY_MODE(deny_mode)) {
1819 case DENY_ALL:
1820 share_mode = FILE_SHARE_NONE;
1821 break;
1823 case DENY_WRITE:
1824 share_mode = FILE_SHARE_READ;
1825 break;
1827 case DENY_READ:
1828 share_mode = FILE_SHARE_WRITE;
1829 break;
1831 case DENY_NONE:
1832 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1833 break;
1835 case DENY_DOS:
1836 private_flags |= NTCREATEX_FLAG_DENY_DOS;
1837 if (is_executable(smb_base_fname)) {
1838 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1839 } else {
1840 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1841 share_mode = FILE_SHARE_READ;
1842 } else {
1843 share_mode = FILE_SHARE_NONE;
1846 break;
1848 case DENY_FCB:
1849 private_flags |= NTCREATEX_FLAG_DENY_FCB;
1850 share_mode = FILE_SHARE_NONE;
1851 break;
1853 default:
1854 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1855 (unsigned int)GET_DENY_MODE(deny_mode) ));
1856 return False;
1859 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
1860 "share_mode = 0x%x, create_disposition = 0x%x, "
1861 "create_options = 0x%x private_flags = 0x%x\n",
1862 smb_base_fname,
1863 (unsigned int)access_mask,
1864 (unsigned int)share_mode,
1865 (unsigned int)create_disposition,
1866 (unsigned int)create_options,
1867 (unsigned int)private_flags));
1869 if (paccess_mask) {
1870 *paccess_mask = access_mask;
1872 if (pshare_mode) {
1873 *pshare_mode = share_mode;
1875 if (pcreate_disposition) {
1876 *pcreate_disposition = create_disposition;
1878 if (pcreate_options) {
1879 *pcreate_options = create_options;
1881 if (pprivate_flags) {
1882 *pprivate_flags = private_flags;
1885 return True;
1889 /*************************************************************************
1890 Return a talloced copy of a struct security_unix_token. NULL on fail.
1891 *************************************************************************/
1893 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
1895 struct security_unix_token *cpy;
1897 cpy = talloc(ctx, struct security_unix_token);
1898 if (!cpy) {
1899 return NULL;
1902 cpy->uid = tok->uid;
1903 cpy->gid = tok->gid;
1904 cpy->ngroups = tok->ngroups;
1905 if (tok->ngroups) {
1906 /* Make this a talloc child of cpy. */
1907 cpy->groups = (gid_t *)talloc_memdup(
1908 cpy, tok->groups, tok->ngroups * sizeof(gid_t));
1909 if (!cpy->groups) {
1910 TALLOC_FREE(cpy);
1911 return NULL;
1913 } else {
1914 cpy->groups = NULL;
1916 return cpy;
1919 /****************************************************************************
1920 Return a root token
1921 ****************************************************************************/
1923 struct security_unix_token *root_unix_token(TALLOC_CTX *mem_ctx)
1925 struct security_unix_token *t = NULL;
1927 t = talloc_zero(mem_ctx, struct security_unix_token);
1928 if (t == NULL) {
1929 return NULL;
1933 * This is not needed, but lets make it explicit, not implicit.
1935 *t = (struct security_unix_token) {
1936 .uid = 0,
1937 .gid = 0,
1938 .ngroups = 0,
1939 .groups = NULL
1942 return t;
1945 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
1947 char *str;
1948 uint32_t i;
1950 str = talloc_asprintf(
1951 mem_ctx,
1952 "uid=%ju, gid=%ju, %"PRIu32" groups:",
1953 (uintmax_t)(tok->uid),
1954 (uintmax_t)(tok->gid),
1955 tok->ngroups);
1957 for (i=0; i<tok->ngroups; i++) {
1958 talloc_asprintf_addbuf(
1959 &str, " %ju", (uintmax_t)tok->groups[i]);
1962 return str;
1965 /****************************************************************************
1966 Check that a file matches a particular file type.
1967 ****************************************************************************/
1969 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
1971 uint32_t mask;
1973 /* Check the "may have" search bits. */
1974 if (((mode & ~dirtype) &
1975 (FILE_ATTRIBUTE_HIDDEN |
1976 FILE_ATTRIBUTE_SYSTEM |
1977 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
1978 return false;
1981 /* Check the "must have" bits,
1982 which are the may have bits shifted eight */
1983 /* If must have bit is set, the file/dir can
1984 not be returned in search unless the matching
1985 file attribute is set */
1986 mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
1987 FILE_ATTRIBUTE_ARCHIVE|
1988 FILE_ATTRIBUTE_READONLY|
1989 FILE_ATTRIBUTE_HIDDEN|
1990 FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
1991 if(mask) {
1992 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
1993 FILE_ATTRIBUTE_ARCHIVE|
1994 FILE_ATTRIBUTE_READONLY|
1995 FILE_ATTRIBUTE_HIDDEN|
1996 FILE_ATTRIBUTE_SYSTEM))) == mask) {
1997 /* check if matching attribute present */
1998 return true;
1999 } else {
2000 return false;
2004 return true;