ctdb-server: Remove duplicate logic
[samba4-gss.git] / source3 / lib / util.c
blob8f9b2ec424aad9d38a301b3cbb57d2d23b8319f3
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 "lib/util/memcache.h"
34 #include "util_tdb.h"
35 #include "ctdbd_conn.h"
36 #include "../lib/util/util_pw.h"
37 #include "messages.h"
38 #include "lib/messaging/messages_dgm.h"
39 #include "libcli/security/security.h"
40 #include "serverid.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>
51 #endif
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)
60 Protocol = p;
63 static enum remote_arch_types ra_type = RA_UNKNOWN;
65 void gfree_all( void )
67 gfree_loadparm();
68 gfree_charcnv();
69 gfree_interfaces();
70 gfree_debugsyms();
71 gfree_memcache();
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)
82 SMB_STRUCT_STAT st;
83 if (!sbuf)
84 sbuf = &st;
86 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
87 return(False);
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)
98 SMB_STRUCT_STAT st;
99 if (sys_stat(fname, &st, false) != 0)
100 return(False);
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)
143 char *msg = NULL;
144 int i;
145 int bcc=0;
147 if (!DEBUGLVL(5))
148 return;
150 msg = talloc_asprintf(
151 talloc_tos(),
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"
155 "smt_wct=%d\n",
156 smb_len(buf),
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) {
183 bcc = MIN(bcc, 512);
185 dump_data_addbuf((const uint8_t *)smb_buf_const(buf),
186 bcc,
187 &msg);
190 DEBUG(5, ("%s", msg));
191 TALLOC_FREE(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;
214 uint8_t *tmp;
216 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
217 DEBUG(0, ("talloc failed\n"));
218 return -1;
220 *outbuf = tmp;
222 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
223 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
224 return blob.length;
227 /*******************************************************************
228 Reduce a file name, removing .. elements.
229 ********************************************************************/
231 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
233 char *p = NULL;
234 char *str = NULL;
236 DEBUG(3,("dos_clean_name [%s]\n",s));
238 /* remove any double slashes */
239 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
240 if (!str) {
241 return NULL;
244 /* Remove leading .\\ characters */
245 if(strncmp(str, ".\\", 2) == 0) {
246 trim_string(str, ".\\", NULL);
247 if(*str == 0) {
248 str = talloc_strdup(ctx, ".\\");
249 if (!str) {
250 return NULL;
255 while ((p = strstr_m(str,"\\..\\")) != NULL) {
256 char *s1;
258 *p = 0;
259 s1 = p+3;
261 if ((p=strrchr_m(str,'\\')) != NULL) {
262 *p = 0;
263 } else {
264 *str = 0;
266 str = talloc_asprintf(ctx,
267 "%s%s",
268 str,
269 s1);
270 if (!str) {
271 return NULL;
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)
285 char *p = NULL;
286 char *str = NULL;
288 DEBUG(3,("unix_clean_name [%s]\n",s));
290 /* remove any double slashes */
291 str = talloc_all_string_sub(ctx, s, "//","/");
292 if (!str) {
293 return NULL;
296 /* Remove leading ./ characters */
297 if(strncmp(str, "./", 2) == 0) {
298 trim_string(str, "./", NULL);
299 if(*str == 0) {
300 str = talloc_strdup(ctx, "./");
301 if (!str) {
302 return NULL;
307 while ((p = strstr_m(str,"/../")) != NULL) {
308 char *s1;
310 *p = 0;
311 s1 = p+3;
313 if ((p=strrchr_m(str,'/')) != NULL) {
314 *p = 0;
315 } else {
316 *str = 0;
318 str = talloc_asprintf(ctx,
319 "%s%s",
320 str,
321 s1);
322 if (!str) {
323 return NULL;
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);
334 if (!str) {
335 return NULL;
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)
346 size_t total=0;
347 ssize_t ret;
349 if (pos == (off_t)-1) {
350 return write_data(fd, buffer, N);
352 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
353 while (total < N) {
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);
358 if (ret == -1) {
359 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
360 return -1;
362 if (ret == 0) {
363 return total;
365 total += ret;
366 pos += ret;
368 return (ssize_t)total;
369 #else
370 /* Use lseek and write_data. */
371 if (lseek(fd, pos, SEEK_SET) == -1) {
372 if (errno != ESPIPE) {
373 return -1;
376 return write_data(fd, buffer, N);
377 #endif
380 static int reinit_after_fork_pipe[2] = { -1, -1 };
382 NTSTATUS init_before_fork(void)
384 int ret;
386 ret = pipe(reinit_after_fork_pipe);
387 if (ret == -1) {
388 NTSTATUS status;
390 status = map_nt_error_from_unix_common(errno);
392 DEBUG(0, ("Error creating child_pipe: %s\n",
393 nt_errstr(status)));
395 return status;
398 return NT_STATUS_OK;
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,
420 uint16_t flags,
421 void *private_data)
423 char c;
425 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
427 * we have reached EOF on stdin, which means the
428 * parent has exited. Shutdown the server
430 TALLOC_FREE(fde);
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;
441 int ret;
444 * The main process thread should never
445 * allow per_thread_cwd_enable() to be
446 * called.
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;
459 goto done;
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);
484 if (fde == NULL) {
485 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
489 if (msg_ctx) {
491 * For clustering, we need to re-init our ctdbd connection after the
492 * fork
494 status = messaging_reinit(msg_ctx);
495 if (!NT_STATUS_IS_OK(status)) {
496 DEBUG(0,("messaging_reinit() failed: %s\n",
497 nt_errstr(status)));
498 goto done;
501 if (lp_clustering()) {
502 ret = ctdb_async_ctx_reinit(
503 NULL, messaging_tevent_context(msg_ctx));
504 if (ret != 0) {
505 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
506 strerror(errno));
507 return map_nt_error_from_unix(ret);
512 done:
513 return status;
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,
522 ssize_t *array_size)
524 void **array = (void **)_array;
526 if (*array_size < 0) {
527 return;
530 if (*array == NULL) {
531 if (*array_size == 0) {
532 *array_size = 128;
535 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
536 goto error;
539 *array = TALLOC(mem_ctx, element_size * (*array_size));
540 if (*array == NULL) {
541 goto error;
545 if (*num_elements == *array_size) {
546 *array_size *= 2;
548 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
549 goto error;
552 *array = TALLOC_REALLOC(mem_ctx, *array,
553 element_size * (*array_size));
555 if (*array == NULL) {
556 goto error;
560 memcpy((char *)(*array) + element_size*(*num_elements),
561 element, element_size);
562 *num_elements += 1;
564 return;
566 error:
567 *num_elements = 0;
568 *array_size = -1;
571 /****************************************************************************
572 Get my own domain name, or "" if we have none.
573 ****************************************************************************/
575 char *get_mydnsdomname(TALLOC_CTX *ctx)
577 const char *domname;
578 char *p;
580 domname = get_mydnsfullname();
581 if (!domname) {
582 return NULL;
585 p = strchr_m(domname, '.');
586 if (p) {
587 p++;
588 return talloc_strdup(ctx, p);
589 } else {
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();
606 char *name = NULL;
607 struct passwd *pass = NULL;
609 pass = getpwuid_alloc(ctx,uid);
610 if (pass) {
611 name = talloc_strdup(ctx,pass->pw_name);
612 TALLOC_FREE(pass);
613 } else {
614 name = talloc_asprintf(ctx,
615 "%ld",
616 (long int)uid);
618 return name;
621 /*******************************************************************
622 Convert a gid into a group name.
623 ********************************************************************/
625 char *gidtoname(gid_t gid)
627 struct group *grp;
629 grp = getgrgid(gid);
630 if (grp) {
631 return talloc_strdup(talloc_tos(), grp->gr_name);
633 else {
634 return talloc_asprintf(talloc_tos(),
635 "%d",
636 (int)gid);
640 /*******************************************************************
641 Convert a user name into a uid.
642 ********************************************************************/
644 uid_t nametouid(const char *name)
646 struct passwd *pass;
647 char *p;
648 uid_t u;
650 pass = Get_Pwnam_alloc(talloc_tos(), name);
651 if (pass) {
652 u = pass->pw_uid;
653 TALLOC_FREE(pass);
654 return u;
657 u = (uid_t)strtol(name, &p, 0);
658 if ((p != name) && (*p == '\0'))
659 return u;
661 return (uid_t)-1;
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)
670 struct group *grp;
671 char *p;
672 gid_t g;
674 g = (gid_t)strtol(name, &p, 0);
675 if ((p != name) && (*p == '\0'))
676 return g;
678 grp = getgrnam(name);
679 if (grp)
680 return(grp->gr_gid);
681 return (gid_t)-1;
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();
692 char *cmd;
693 int result;
695 cmd = lp_panic_action(talloc_tos(), lp_sub);
696 if (cmd == NULL || cmd[0] == '\0') {
697 return;
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);
707 #endif
709 if (as_root) {
710 become_root();
713 result = system(cmd);
715 if (as_root) {
716 unbecome_root();
719 if (result == -1)
720 DBG_ERR("fork failed in panic action: %s\n",
721 strerror(errno));
722 else
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);
730 dump_core();
733 void log_panic_action(const char *msg)
735 DBG_ERR("%s", 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)
745 struct dirent *ptr;
746 char *dname;
748 if (!p)
749 return(NULL);
751 ptr = (struct dirent *)readdir(p);
752 if (!ptr)
753 return(NULL);
755 dname = ptr->d_name;
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,
767 bool case_sensitive)
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)) {
773 return False;
776 /* Do not reject path components if namelist is set to '.*' */
777 if (ISDOT(name) || ISDOTDOT(name)) {
778 return false;
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;
787 } else {
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"));
795 return True;
797 } else {
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"));
801 return True;
805 DEBUG(8,("is_in_path: match not found\n"));
806 return False;
809 #undef DBGC_CLASS
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)
821 struct flock lock;
822 int ret;
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;
831 lock.l_pid = 0;
833 ret = sys_fcntl_ptr(fd,op,&lock);
835 if (ret == -1) {
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)));
839 errno = saved_errno;
840 return False;
843 *ptype = lock.l_type;
844 *poffset = lock.l_start;
845 *pcount = lock.l_len;
846 *ppid = lock.l_pid;
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));
850 return True;
853 #if defined(HAVE_OFD_LOCKS)
854 int map_process_lock_to_ofd_lock(int op)
856 switch (op) {
857 case F_GETLK:
858 case F_OFD_GETLK:
859 op = F_OFD_GETLK;
860 break;
861 case F_SETLK:
862 case F_OFD_SETLK:
863 op = F_OFD_SETLK;
864 break;
865 case F_SETLKW:
866 case F_OFD_SETLKW:
867 op = F_OFD_SETLKW;
868 break;
869 default:
870 return -1;
872 return op;
874 #else /* HAVE_OFD_LOCKS */
875 int map_process_lock_to_ofd_lock(int op)
877 return op;
879 #endif /* HAVE_OFD_LOCKS */
881 #undef DBGC_CLASS
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);
892 return (cmp == 0);
895 bool is_myname(const char *s)
897 const char **aliases = NULL;
898 bool ok = false;
900 ok = nb_name_equal(lp_netbios_name(), s);
901 if (ok) {
902 goto done;
905 aliases = lp_netbios_aliases();
906 if (aliases == NULL) {
907 goto done;
910 while (*aliases != NULL) {
911 ok = nb_name_equal(*aliases, s);
912 if (ok) {
913 goto done;
915 aliases += 1;
918 done:
919 DBG_DEBUG("is_myname(\"%s\") returns %d\n", s, (int)ok);
920 return 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",
946 [RA_WFWG] = "WfWg",
947 [RA_OS2] = "OS2",
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",
957 [RA_OSX] = "OSX",
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)
976 size_t i;
978 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
979 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
980 return i;
983 return RA_UNKNOWN;
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;
1000 return;
1003 ra_type = type;
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)
1014 return ra_type;
1017 #define RA_CACHE_TTL 7*24*3600
1019 static bool remote_arch_cache_key(const struct GUID *client_guid,
1020 fstring key)
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) {
1027 return false;
1030 fstr_sprintf(key, "RA/%s", guid_string);
1031 return true;
1034 struct ra_parser_state {
1035 bool found;
1036 enum remote_arch_types ra;
1039 static void ra_parser(const struct gencache_timeout *t,
1040 DATA_BLOB blob,
1041 void *priv_data)
1043 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1044 const char *ra_str = NULL;
1046 if (gencache_timeout_expired(t)) {
1047 return;
1050 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1051 DBG_ERR("Remote arch cache key not a string\n");
1052 return;
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;
1060 return;
1063 static bool remote_arch_cache_get(const struct GUID *client_guid)
1065 bool ok;
1066 fstring ra_key;
1067 struct ra_parser_state state = (struct ra_parser_state) {
1068 .found = false,
1069 .ra = RA_UNKNOWN,
1072 ok = remote_arch_cache_key(client_guid, ra_key);
1073 if (!ok) {
1074 return false;
1077 ok = gencache_parse(ra_key, ra_parser, &state);
1078 if (!ok || !state.found) {
1079 return true;
1082 if (state.ra == RA_UNKNOWN) {
1083 return true;
1086 set_remote_arch(state.ra);
1087 return true;
1090 static bool remote_arch_cache_set(const struct GUID *client_guid)
1092 bool ok;
1093 fstring ra_key;
1094 const char *ra_str = NULL;
1096 if (get_remote_arch() == RA_UNKNOWN) {
1097 return true;
1100 ok = remote_arch_cache_key(client_guid, ra_key);
1101 if (!ok) {
1102 return false;
1105 ra_str = get_remote_arch_str();
1106 if (ra_str == NULL) {
1107 return false;
1110 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1111 if (!ok) {
1112 return false;
1115 return true;
1118 bool remote_arch_cache_update(const struct GUID *client_guid)
1120 bool ok;
1122 if (get_remote_arch() == RA_UNKNOWN) {
1124 become_root();
1125 ok = remote_arch_cache_get(client_guid);
1126 unbecome_root();
1128 return ok;
1131 become_root();
1132 ok = remote_arch_cache_set(client_guid);
1133 unbecome_root();
1135 return ok;
1138 bool remote_arch_cache_delete(const struct GUID *client_guid)
1140 bool ok;
1141 fstring ra_key;
1143 ok = remote_arch_cache_key(client_guid, ra_key);
1144 if (!ok) {
1145 return false;
1148 become_root();
1149 ok = gencache_del(ra_key);
1150 unbecome_root();
1152 if (!ok) {
1153 return false;
1156 return true;
1160 /*****************************************************************************
1161 Provide a checksum on a string
1163 Input: s - the null-terminated character string for which the checksum
1164 will be calculated.
1166 Output: The checksum value calculated for s.
1167 *****************************************************************************/
1169 int str_checksum(const char *s)
1171 TDB_DATA key;
1172 if (s == NULL)
1173 return 0;
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)
1187 memset(p, 0, size);
1188 SAFE_FREE(p);
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))
1198 struct rlimit rlp;
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",
1203 strerror(errno) ));
1204 /* just guess... */
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;
1237 #endif
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) ));
1246 /* just guess... */
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",
1252 strerror(errno) ));
1253 /* just guess... */
1254 return saved_current_limit;
1257 #if defined(RLIM_INFINITY)
1258 if(rlp.rlim_cur == RLIM_INFINITY)
1259 return saved_current_limit;
1260 #endif
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;
1271 #endif
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)
1280 void *p;
1281 if (size == 0) {
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");
1292 return p;
1295 /*****************************************************************
1296 Get local hostname and cache result.
1297 *****************************************************************/
1299 char *myhostname(void)
1301 static char *ret;
1302 if (ret == NULL) {
1303 ret = get_myname(NULL);
1305 return ret;
1308 /*****************************************************************
1309 Get local hostname and cache result.
1310 *****************************************************************/
1312 char *myhostname_upper(void)
1314 static char *ret;
1315 if (ret == NULL) {
1316 char *name = get_myname(NULL);
1317 if (name == NULL) {
1318 return NULL;
1320 ret = strupper_talloc(NULL, name);
1321 talloc_free(name);
1323 return ret;
1326 /*******************************************************************
1327 Given a filename - get its directory name
1328 ********************************************************************/
1330 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1331 const char **name)
1333 char *p;
1334 ptrdiff_t len;
1336 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1338 if (p == NULL) {
1339 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1340 return False;
1342 if (name) {
1343 *name = dir;
1345 return True;
1348 len = p-dir;
1350 *parent = talloc_strndup(mem_ctx, dir, len);
1351 if (*parent == NULL) {
1352 return False;
1355 if (name) {
1356 *name = p+1;
1358 return True;
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)
1373 smb_ucs2_t c;
1374 if (!s) return False;
1375 while ((c = *s++)) {
1376 switch (c) {
1377 case UCS2_CHAR('*'):
1378 case UCS2_CHAR('?'):
1379 case UCS2_CHAR('<'):
1380 case UCS2_CHAR('>'):
1381 case UCS2_CHAR('"'):
1382 return True;
1385 return False;
1388 /*******************************************************************
1389 A wrapper that handles case sensitivity and the special handling
1390 of the ".." name.
1391 *******************************************************************/
1393 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1395 if (ISDOTDOT(string))
1396 string = ".";
1397 if (ISDOT(pattern))
1398 return False;
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))
1412 return True;
1414 return False;
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
1425 pointer ptr+off.
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) {
1434 return False;
1437 if (end_base < buf_base || end_ptr < ptr) {
1438 return False; /* wrap. */
1441 if (end_ptr < end_base) {
1442 return True;
1444 return False;
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)) {
1454 return NULL;
1456 /* Check if a valid string exists at this offset. */
1457 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1458 return NULL;
1460 return ptr + off;
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,
1471 char **domain,
1472 char **user)
1474 const char *p = NULL;
1476 p = strchr_m(full_name, '\\');
1478 if (p != NULL) {
1479 *domain = talloc_strndup(mem_ctx, full_name,
1480 PTR_DIFF(p, full_name));
1481 if (*domain == NULL) {
1482 return false;
1484 *user = talloc_strdup(mem_ctx, p+1);
1485 if (*user == NULL) {
1486 TALLOC_FREE(*domain);
1487 return false;
1489 } else {
1490 *domain = NULL;
1491 *user = talloc_strdup(mem_ctx, full_name);
1492 if (*user == NULL) {
1493 return false;
1497 return true;
1500 /****************************************************************
1501 strip off leading '\\' from a hostname
1502 ****************************************************************/
1504 const char *strip_hostname(const char *s)
1506 if (!s) {
1507 return NULL;
1510 if (strlen_m(s) < 3) {
1511 return s;
1514 if (s[0] == '\\') s++;
1515 if (s[0] == '\\') s++;
1517 return s;
1520 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
1522 if (!NT_STATUS_IS_OK(err1)) {
1523 *result = err1;
1524 return true;
1526 if (!NT_STATUS_IS_OK(err2)) {
1527 *result = err2;
1528 return true;
1530 return false;
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)
1544 char *ptr = NULL;
1546 if (!dos_pathname) {
1547 return NULL;
1550 ptr = talloc_strdup(ctx, dos_pathname);
1551 if (!ptr) {
1552 return NULL;
1554 /* Convert any '\' paths to '/' */
1555 unix_format(ptr);
1556 ptr = unix_clean_name(ctx, ptr);
1557 if (!ptr) {
1558 return NULL;
1561 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
1562 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
1563 ptr += 2;
1565 /* Only absolute paths allowed. */
1566 if (*ptr != '/')
1567 return NULL;
1569 return ptr;
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")) {
1583 return True;
1586 return False;
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;
1617 break;
1618 case DOS_OPEN_WRONLY:
1619 access_mask = FILE_GENERIC_WRITE;
1620 break;
1621 case DOS_OPEN_RDWR:
1622 case DOS_OPEN_FCB:
1623 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
1624 break;
1625 default:
1626 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
1627 (unsigned int)GET_OPENX_MODE(deny_mode)));
1628 return False;
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;
1635 break;
1637 case OPENX_FILE_EXISTS_OPEN:
1638 create_disposition = FILE_OPEN;
1639 break;
1641 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
1642 create_disposition = FILE_OPEN_IF;
1643 break;
1645 case OPENX_FILE_EXISTS_TRUNCATE:
1646 create_disposition = FILE_OVERWRITE;
1647 break;
1649 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
1650 create_disposition = FILE_OVERWRITE_IF;
1651 break;
1653 default:
1654 /* From samba4 - to be confirmed. */
1655 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
1656 create_disposition = FILE_CREATE;
1657 break;
1659 DEBUG(10,("map_open_params_to_ntcreate: bad "
1660 "open_func 0x%x\n", (unsigned int)open_func));
1661 return False;
1664 /* Create the NT compatible share modes. */
1665 switch (GET_DENY_MODE(deny_mode)) {
1666 case DENY_ALL:
1667 share_mode = FILE_SHARE_NONE;
1668 break;
1670 case DENY_WRITE:
1671 share_mode = FILE_SHARE_READ;
1672 break;
1674 case DENY_READ:
1675 share_mode = FILE_SHARE_WRITE;
1676 break;
1678 case DENY_NONE:
1679 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1680 break;
1682 case DENY_DOS:
1683 private_flags |= NTCREATEX_FLAG_DENY_DOS;
1684 if (is_executable(smb_base_fname)) {
1685 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1686 } else {
1687 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
1688 share_mode = FILE_SHARE_READ;
1689 } else {
1690 share_mode = FILE_SHARE_NONE;
1693 break;
1695 case DENY_FCB:
1696 private_flags |= NTCREATEX_FLAG_DENY_FCB;
1697 share_mode = FILE_SHARE_NONE;
1698 break;
1700 default:
1701 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
1702 (unsigned int)GET_DENY_MODE(deny_mode) ));
1703 return False;
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",
1709 smb_base_fname,
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));
1716 if (paccess_mask) {
1717 *paccess_mask = access_mask;
1719 if (pshare_mode) {
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;
1732 return True;
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);
1745 if (!cpy) {
1746 return NULL;
1749 *cpy = (struct security_unix_token){
1750 .uid = tok->uid,
1751 .gid = tok->gid,
1752 .ngroups = tok->ngroups,
1755 if (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));
1759 if (!cpy->groups) {
1760 TALLOC_FREE(cpy);
1761 return NULL;
1764 return cpy;
1767 /****************************************************************************
1768 Return a root token
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);
1776 if (t == NULL) {
1777 return NULL;
1781 * This is not needed, but lets make it explicit, not implicit.
1783 *t = (struct security_unix_token) {
1784 .uid = 0,
1785 .gid = 0,
1786 .ngroups = 0,
1787 .groups = NULL
1790 return t;
1793 char *utok_string(TALLOC_CTX *mem_ctx, const struct security_unix_token *tok)
1795 char *str;
1796 uint32_t i;
1798 str = talloc_asprintf(
1799 mem_ctx,
1800 "uid=%ju, gid=%ju, %"PRIu32" groups:",
1801 (uintmax_t)(tok->uid),
1802 (uintmax_t)(tok->gid),
1803 tok->ngroups);
1805 for (i=0; i<tok->ngroups; i++) {
1806 talloc_asprintf_addbuf(
1807 &str, " %ju", (uintmax_t)tok->groups[i]);
1810 return str;
1813 /****************************************************************************
1814 Check that a file matches a particular file type.
1815 ****************************************************************************/
1817 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
1819 uint32_t mask;
1821 /* Check the "may have" search bits. */
1822 if (((mode & ~dirtype) &
1823 (FILE_ATTRIBUTE_HIDDEN |
1824 FILE_ATTRIBUTE_SYSTEM |
1825 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
1826 return false;
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 */
1839 if(mask) {
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 */
1846 return true;
1847 } else {
1848 return false;
1852 return true;