s4:rpc_server/lsa: prepare dcesrv_lsa_LookupSids* for async processing
[Samba.git] / source3 / lib / util.c
blobae9fe71c97495be65e1d45b02ff74392c1b30ab8
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 #include "includes.h"
25 #include "system/passwd.h"
26 #include "system/filesys.h"
27 #include "lib/util/server_id.h"
28 #include "util_tdb.h"
29 #include "ctdbd_conn.h"
30 #include "../lib/util/util_pw.h"
31 #include "messages.h"
32 #include "messages_dgm.h"
33 #include "libcli/security/security.h"
34 #include "serverid.h"
35 #include "lib/util/sys_rw.h"
36 #include "lib/util/sys_rw_data.h"
37 #include "lib/util/util_process.h"
38 #include "lib/dbwrap/dbwrap_ctdb.h"
40 #ifdef HAVE_SYS_PRCTL_H
41 #include <sys/prctl.h>
42 #endif
44 /* Max allowable allococation - 256mb - 0x10000000 */
45 #define MAX_ALLOC_SIZE (1024*1024*256)
47 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
48 /* rpc/xdr.h uses TRUE and FALSE */
49 #ifdef TRUE
50 #undef TRUE
51 #endif
53 #ifdef FALSE
54 #undef FALSE
55 #endif
57 #include "system/nis.h"
59 #ifdef WITH_NISPLUS_HOME
60 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
62 * The following lines are needed due to buggy include files
63 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
64 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
65 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
66 * an enum in /usr/include/rpcsvc/nis.h.
69 #if defined(GROUP)
70 #undef GROUP
71 #endif
73 #if defined(GROUP_OBJ)
74 #undef GROUP_OBJ
75 #endif
77 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
79 #include <rpcsvc/nis.h>
81 #endif /* WITH_NISPLUS_HOME */
82 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
84 static enum protocol_types Protocol = PROTOCOL_COREPLUS;
86 enum protocol_types get_Protocol(void)
88 return Protocol;
91 void set_Protocol(enum protocol_types p)
93 Protocol = p;
96 static enum remote_arch_types ra_type = RA_UNKNOWN;
98 void gfree_all( void )
100 gfree_names();
101 gfree_loadparm();
102 gfree_charcnv();
103 gfree_interfaces();
104 gfree_debugsyms();
107 /*******************************************************************
108 Check if a file exists - call vfs_file_exist for samba files.
109 ********************************************************************/
111 bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
112 bool fake_dir_create_times)
114 SMB_STRUCT_STAT st;
115 if (!sbuf)
116 sbuf = &st;
118 if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
119 return(False);
121 return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
124 /*******************************************************************
125 Check if a unix domain socket exists - call vfs_file_exist for samba files.
126 ********************************************************************/
128 bool socket_exist(const char *fname)
130 SMB_STRUCT_STAT st;
131 if (sys_stat(fname, &st, false) != 0)
132 return(False);
134 return S_ISSOCK(st.st_ex_mode);
137 /*******************************************************************
138 Returns the size in bytes of the named given the stat struct.
139 ********************************************************************/
141 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
143 return sbuf->st_ex_size;
146 /****************************************************************************
147 Check two stats have identical dev and ino fields.
148 ****************************************************************************/
150 bool check_same_dev_ino(const SMB_STRUCT_STAT *sbuf1,
151 const SMB_STRUCT_STAT *sbuf2)
153 if (sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
154 sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
155 return false;
157 return true;
160 /****************************************************************************
161 Check if a stat struct is identical for use.
162 ****************************************************************************/
164 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
165 const SMB_STRUCT_STAT *sbuf2)
167 if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
168 sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
169 !check_same_dev_ino(sbuf1, sbuf2)) {
170 return false;
172 return true;
175 /*******************************************************************
176 Show a smb message structure.
177 ********************************************************************/
179 void show_msg(const char *buf)
181 int i;
182 int bcc=0;
184 if (!DEBUGLVL(5))
185 return;
187 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
188 smb_len(buf),
189 (int)CVAL(buf,smb_com),
190 (int)CVAL(buf,smb_rcls),
191 (int)CVAL(buf,smb_reh),
192 (int)SVAL(buf,smb_err),
193 (int)CVAL(buf,smb_flg),
194 (int)SVAL(buf,smb_flg2)));
195 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
196 (int)SVAL(buf,smb_tid),
197 (int)SVAL(buf,smb_pid),
198 (int)SVAL(buf,smb_uid),
199 (int)SVAL(buf,smb_mid)));
200 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
202 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
203 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
204 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
206 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
208 DEBUGADD(5,("smb_bcc=%d\n",bcc));
210 if (DEBUGLEVEL < 10)
211 return;
213 if (DEBUGLEVEL < 50)
214 bcc = MIN(bcc, 512);
216 dump_data(10, (const uint8_t *)smb_buf_const(buf), bcc);
219 /*******************************************************************
220 Setup only the byte count for a smb message.
221 ********************************************************************/
223 int set_message_bcc(char *buf,int num_bytes)
225 int num_words = CVAL(buf,smb_wct);
226 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
227 _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
228 return (smb_size + num_words*2 + num_bytes);
231 /*******************************************************************
232 Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
233 Return the bytes added
234 ********************************************************************/
236 ssize_t message_push_blob(uint8_t **outbuf, DATA_BLOB blob)
238 size_t newlen = smb_len(*outbuf) + 4 + blob.length;
239 uint8_t *tmp;
241 if (!(tmp = talloc_realloc(NULL, *outbuf, uint8_t, newlen))) {
242 DEBUG(0, ("talloc failed\n"));
243 return -1;
245 *outbuf = tmp;
247 memcpy(tmp + smb_len(tmp) + 4, blob.data, blob.length);
248 set_message_bcc((char *)tmp, smb_buflen(tmp) + blob.length);
249 return blob.length;
252 /*******************************************************************
253 Reduce a file name, removing .. elements.
254 ********************************************************************/
256 static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
258 char *p = NULL;
259 char *str = NULL;
261 DEBUG(3,("dos_clean_name [%s]\n",s));
263 /* remove any double slashes */
264 str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
265 if (!str) {
266 return NULL;
269 /* Remove leading .\\ characters */
270 if(strncmp(str, ".\\", 2) == 0) {
271 trim_string(str, ".\\", NULL);
272 if(*str == 0) {
273 str = talloc_strdup(ctx, ".\\");
274 if (!str) {
275 return NULL;
280 while ((p = strstr_m(str,"\\..\\")) != NULL) {
281 char *s1;
283 *p = 0;
284 s1 = p+3;
286 if ((p=strrchr_m(str,'\\')) != NULL) {
287 *p = 0;
288 } else {
289 *str = 0;
291 str = talloc_asprintf(ctx,
292 "%s%s",
293 str,
294 s1);
295 if (!str) {
296 return NULL;
300 trim_string(str,NULL,"\\..");
301 return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
304 /*******************************************************************
305 Reduce a file name, removing .. elements.
306 ********************************************************************/
308 char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
310 char *p = NULL;
311 char *str = NULL;
313 DEBUG(3,("unix_clean_name [%s]\n",s));
315 /* remove any double slashes */
316 str = talloc_all_string_sub(ctx, s, "//","/");
317 if (!str) {
318 return NULL;
321 /* Remove leading ./ characters */
322 if(strncmp(str, "./", 2) == 0) {
323 trim_string(str, "./", NULL);
324 if(*str == 0) {
325 str = talloc_strdup(ctx, "./");
326 if (!str) {
327 return NULL;
332 while ((p = strstr_m(str,"/../")) != NULL) {
333 char *s1;
335 *p = 0;
336 s1 = p+3;
338 if ((p=strrchr_m(str,'/')) != NULL) {
339 *p = 0;
340 } else {
341 *str = 0;
343 str = talloc_asprintf(ctx,
344 "%s%s",
345 str,
346 s1);
347 if (!str) {
348 return NULL;
352 trim_string(str,NULL,"/..");
353 return talloc_all_string_sub(ctx, str, "/./", "/");
356 char *clean_name(TALLOC_CTX *ctx, const char *s)
358 char *str = dos_clean_name(ctx, s);
359 if (!str) {
360 return NULL;
362 return unix_clean_name(ctx, str);
365 /*******************************************************************
366 Write data into an fd at a given offset. Ignore seek errors.
367 ********************************************************************/
369 ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, off_t pos)
371 size_t total=0;
372 ssize_t ret;
374 if (pos == (off_t)-1) {
375 return write_data(fd, buffer, N);
377 #if defined(HAVE_PWRITE) || defined(HAVE_PRWITE64)
378 while (total < N) {
379 ret = sys_pwrite(fd,buffer + total,N - total, pos);
380 if (ret == -1 && errno == ESPIPE) {
381 return write_data(fd, buffer + total,N - total);
383 if (ret == -1) {
384 DEBUG(0,("write_data_at_offset: write failure. Error = %s\n", strerror(errno) ));
385 return -1;
387 if (ret == 0) {
388 return total;
390 total += ret;
391 pos += ret;
393 return (ssize_t)total;
394 #else
395 /* Use lseek and write_data. */
396 if (lseek(fd, pos, SEEK_SET) == -1) {
397 if (errno != ESPIPE) {
398 return -1;
401 return write_data(fd, buffer, N);
402 #endif
405 static int reinit_after_fork_pipe[2] = { -1, -1 };
407 NTSTATUS init_before_fork(void)
409 int ret;
411 ret = pipe(reinit_after_fork_pipe);
412 if (ret == -1) {
413 NTSTATUS status;
415 status = map_nt_error_from_unix_common(errno);
417 DEBUG(0, ("Error creating child_pipe: %s\n",
418 nt_errstr(status)));
420 return status;
423 return NT_STATUS_OK;
427 * Detect died parent by detecting EOF on the pipe
429 static void reinit_after_fork_pipe_handler(struct tevent_context *ev,
430 struct tevent_fd *fde,
431 uint16_t flags,
432 void *private_data)
434 char c;
436 if (sys_read(reinit_after_fork_pipe[0], &c, 1) != 1) {
438 * we have reached EOF on stdin, which means the
439 * parent has exited. Shutdown the server
441 (void)kill(getpid(), SIGTERM);
446 NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
447 struct tevent_context *ev_ctx,
448 bool parent_longlived,
449 const char *comment)
451 NTSTATUS status = NT_STATUS_OK;
452 int ret;
454 if (reinit_after_fork_pipe[1] != -1) {
455 close(reinit_after_fork_pipe[1]);
456 reinit_after_fork_pipe[1] = -1;
459 /* tdb needs special fork handling */
460 if (tdb_reopen_all(parent_longlived ? 1 : 0) != 0) {
461 DEBUG(0,("tdb_reopen_all failed.\n"));
462 status = NT_STATUS_OPEN_FAILED;
463 goto done;
466 if (ev_ctx != NULL) {
467 tevent_set_trace_callback(ev_ctx, NULL, NULL);
468 if (tevent_re_initialise(ev_ctx) != 0) {
469 smb_panic(__location__ ": Failed to re-initialise event context");
473 if (reinit_after_fork_pipe[0] != -1) {
474 struct tevent_fd *fde;
476 fde = tevent_add_fd(ev_ctx, ev_ctx /* TALLOC_CTX */,
477 reinit_after_fork_pipe[0], TEVENT_FD_READ,
478 reinit_after_fork_pipe_handler, NULL);
479 if (fde == NULL) {
480 smb_panic(__location__ ": Failed to add reinit_after_fork pipe event");
484 if (msg_ctx) {
486 * For clustering, we need to re-init our ctdbd connection after the
487 * fork
489 status = messaging_reinit(msg_ctx);
490 if (!NT_STATUS_IS_OK(status)) {
491 DEBUG(0,("messaging_reinit() failed: %s\n",
492 nt_errstr(status)));
495 if (lp_clustering()) {
496 ret = ctdb_async_ctx_reinit(
497 NULL, messaging_tevent_context(msg_ctx));
498 if (ret != 0) {
499 DBG_ERR("db_ctdb_async_ctx_reinit failed: %s\n",
500 strerror(errno));
501 return map_nt_error_from_unix(ret);
506 if (comment) {
507 prctl_set_comment(comment);
510 done:
511 return status;
514 /****************************************************************************
515 (Hopefully) efficient array append.
516 ****************************************************************************/
518 void add_to_large_array(TALLOC_CTX *mem_ctx, size_t element_size,
519 void *element, void *_array, uint32_t *num_elements,
520 ssize_t *array_size)
522 void **array = (void **)_array;
524 if (*array_size < 0) {
525 return;
528 if (*array == NULL) {
529 if (*array_size == 0) {
530 *array_size = 128;
533 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
534 goto error;
537 *array = TALLOC(mem_ctx, element_size * (*array_size));
538 if (*array == NULL) {
539 goto error;
543 if (*num_elements == *array_size) {
544 *array_size *= 2;
546 if (*array_size >= MAX_ALLOC_SIZE/element_size) {
547 goto error;
550 *array = TALLOC_REALLOC(mem_ctx, *array,
551 element_size * (*array_size));
553 if (*array == NULL) {
554 goto error;
558 memcpy((char *)(*array) + element_size*(*num_elements),
559 element, element_size);
560 *num_elements += 1;
562 return;
564 error:
565 *num_elements = 0;
566 *array_size = -1;
569 /****************************************************************************
570 Get my own domain name, or "" if we have none.
571 ****************************************************************************/
573 char *get_mydnsdomname(TALLOC_CTX *ctx)
575 const char *domname;
576 char *p;
578 domname = get_mydnsfullname();
579 if (!domname) {
580 return NULL;
583 p = strchr_m(domname, '.');
584 if (p) {
585 p++;
586 return talloc_strdup(ctx, p);
587 } else {
588 return talloc_strdup(ctx, "");
592 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
593 /******************************************************************
594 Remove any mount options such as -rsize=2048,wsize=2048 etc.
595 Based on a fix from <Thomas.Hepper@icem.de>.
596 Returns a malloc'ed string.
597 *******************************************************************/
599 static char *strip_mount_options(TALLOC_CTX *ctx, const char *str)
601 if (*str == '-') {
602 const char *p = str;
603 while(*p && !isspace(*p))
604 p++;
605 while(*p && isspace(*p))
606 p++;
607 if(*p) {
608 return talloc_strdup(ctx, p);
611 return NULL;
614 /*******************************************************************
615 Patch from jkf@soton.ac.uk
616 Split Luke's automount_server into YP lookup and string splitter
617 so can easily implement automount_path().
618 Returns a malloc'ed string.
619 *******************************************************************/
621 #ifdef WITH_NISPLUS_HOME
622 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
624 char *value = NULL;
626 char *nis_map = (char *)lp_homedir_map();
628 char buffer[NIS_MAXATTRVAL + 1];
629 nis_result *result;
630 nis_object *object;
631 entry_obj *entry;
633 snprintf(buffer, sizeof(buffer), "[key=%s],%s", user_name, nis_map);
634 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
636 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
637 if (result->status != NIS_SUCCESS) {
638 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
639 } else {
640 object = result->objects.objects_val;
641 if (object->zo_data.zo_type == ENTRY_OBJ) {
642 entry = &object->zo_data.objdata_u.en_data;
643 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
644 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
646 value = talloc_strdup(ctx,
647 entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
648 if (!value) {
649 nis_freeresult(result);
650 return NULL;
652 value = talloc_string_sub(ctx,
653 value,
654 "&",
655 user_name);
659 nis_freeresult(result);
661 if (value) {
662 value = strip_mount_options(ctx, value);
663 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
664 user_name, value));
666 return value;
668 #else /* WITH_NISPLUS_HOME */
670 char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
672 char *value = NULL;
674 int nis_error; /* returned by yp all functions */
675 char *nis_result; /* yp_match inits this */
676 int nis_result_len; /* and set this */
677 char *nis_domain; /* yp_get_default_domain inits this */
678 char *nis_map = lp_homedir_map(talloc_tos());
680 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
681 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
682 return NULL;
685 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
687 if ((nis_error = yp_match(nis_domain, nis_map, user_name,
688 strlen(user_name), &nis_result,
689 &nis_result_len)) == 0) {
690 if (nis_result_len > 0 && nis_result[nis_result_len] == '\n') {
691 nis_result[nis_result_len] = '\0';
693 value = talloc_strdup(ctx, nis_result);
694 if (!value) {
695 return NULL;
697 value = strip_mount_options(ctx, value);
698 } else if(nis_error == YPERR_KEY) {
699 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
700 user_name, nis_map));
701 DEBUG(3, ("using defaults for server and home directory\n"));
702 } else {
703 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
704 yperr_string(nis_error), user_name, nis_map));
707 if (value) {
708 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, value));
710 return value;
712 #endif /* WITH_NISPLUS_HOME */
713 #endif
715 bool process_exists(const struct server_id pid)
717 return serverid_exists(&pid);
720 /*******************************************************************
721 Convert a uid into a user name.
722 ********************************************************************/
724 const char *uidtoname(uid_t uid)
726 TALLOC_CTX *ctx = talloc_tos();
727 char *name = NULL;
728 struct passwd *pass = NULL;
730 pass = getpwuid_alloc(ctx,uid);
731 if (pass) {
732 name = talloc_strdup(ctx,pass->pw_name);
733 TALLOC_FREE(pass);
734 } else {
735 name = talloc_asprintf(ctx,
736 "%ld",
737 (long int)uid);
739 return name;
742 /*******************************************************************
743 Convert a gid into a group name.
744 ********************************************************************/
746 char *gidtoname(gid_t gid)
748 struct group *grp;
750 grp = getgrgid(gid);
751 if (grp) {
752 return talloc_strdup(talloc_tos(), grp->gr_name);
754 else {
755 return talloc_asprintf(talloc_tos(),
756 "%d",
757 (int)gid);
761 /*******************************************************************
762 Convert a user name into a uid.
763 ********************************************************************/
765 uid_t nametouid(const char *name)
767 struct passwd *pass;
768 char *p;
769 uid_t u;
771 pass = Get_Pwnam_alloc(talloc_tos(), name);
772 if (pass) {
773 u = pass->pw_uid;
774 TALLOC_FREE(pass);
775 return u;
778 u = (uid_t)strtol(name, &p, 0);
779 if ((p != name) && (*p == '\0'))
780 return u;
782 return (uid_t)-1;
785 /*******************************************************************
786 Convert a name to a gid_t if possible. Return -1 if not a group.
787 ********************************************************************/
789 gid_t nametogid(const char *name)
791 struct group *grp;
792 char *p;
793 gid_t g;
795 g = (gid_t)strtol(name, &p, 0);
796 if ((p != name) && (*p == '\0'))
797 return g;
799 grp = getgrnam(name);
800 if (grp)
801 return(grp->gr_gid);
802 return (gid_t)-1;
805 /*******************************************************************
806 Something really nasty happened - panic !
807 ********************************************************************/
809 void smb_panic_s3(const char *why)
811 char *cmd;
812 int result;
814 DEBUG(0,("PANIC (pid %llu): %s\n",
815 (unsigned long long)getpid(), why));
816 log_stack_trace();
818 #if defined(HAVE_PRCTL) && defined(PR_SET_PTRACER)
820 * Make sure all children can attach a debugger.
822 prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
823 #endif
825 cmd = lp_panic_action(talloc_tos());
826 if (cmd && *cmd) {
827 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
828 result = system(cmd);
830 if (result == -1)
831 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
832 strerror(errno)));
833 else
834 DEBUG(0, ("smb_panic(): action returned status %d\n",
835 WEXITSTATUS(result)));
838 dump_core();
841 /*******************************************************************
842 Print a backtrace of the stack to the debug log. This function
843 DELIBERATELY LEAKS MEMORY. The expectation is that you should
844 exit shortly after calling it.
845 ********************************************************************/
847 #ifdef HAVE_LIBUNWIND_H
848 #include <libunwind.h>
849 #endif
851 #ifdef HAVE_EXECINFO_H
852 #include <execinfo.h>
853 #endif
855 #ifdef HAVE_LIBEXC_H
856 #include <libexc.h>
857 #endif
859 void log_stack_trace(void)
861 #ifdef HAVE_LIBUNWIND
862 /* Try to use libunwind before any other technique since on ia64
863 * libunwind correctly walks the stack in more circumstances than
864 * backtrace.
866 unw_cursor_t cursor;
867 unw_context_t uc;
868 unsigned i = 0;
870 char procname[256];
871 unw_word_t ip, sp, off;
873 procname[sizeof(procname) - 1] = '\0';
875 if (unw_getcontext(&uc) != 0) {
876 goto libunwind_failed;
879 if (unw_init_local(&cursor, &uc) != 0) {
880 goto libunwind_failed;
883 DEBUG(0, ("BACKTRACE:\n"));
885 do {
886 ip = sp = 0;
887 unw_get_reg(&cursor, UNW_REG_IP, &ip);
888 unw_get_reg(&cursor, UNW_REG_SP, &sp);
890 switch (unw_get_proc_name(&cursor,
891 procname, sizeof(procname) - 1, &off) ) {
892 case 0:
893 /* Name found. */
894 case -UNW_ENOMEM:
895 /* Name truncated. */
896 DEBUGADD(0, (" #%u %s + %#llx [ip=%#llx] [sp=%#llx]\n",
897 i, procname, (long long)off,
898 (long long)ip, (long long) sp));
899 break;
900 default:
901 /* case -UNW_ENOINFO: */
902 /* case -UNW_EUNSPEC: */
903 /* No symbol name found. */
904 DEBUGADD(0, (" #%u %s [ip=%#llx] [sp=%#llx]\n",
905 i, "<unknown symbol>",
906 (long long)ip, (long long) sp));
908 ++i;
909 } while (unw_step(&cursor) > 0);
911 return;
913 libunwind_failed:
914 DEBUG(0, ("unable to produce a stack trace with libunwind\n"));
916 #elif HAVE_BACKTRACE_SYMBOLS
917 void *backtrace_stack[BACKTRACE_STACK_SIZE];
918 size_t backtrace_size;
919 char **backtrace_strings;
921 /* get the backtrace (stack frames) */
922 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
923 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
925 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
926 (unsigned long)backtrace_size));
928 if (backtrace_strings) {
929 int i;
931 for (i = 0; i < backtrace_size; i++)
932 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
934 /* Leak the backtrace_strings, rather than risk what free() might do */
937 #elif HAVE_LIBEXC
939 /* The IRIX libexc library provides an API for unwinding the stack. See
940 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
941 * since we are about to abort anyway, it hardly matters.
944 #define NAMESIZE 32 /* Arbitrary */
946 __uint64_t addrs[BACKTRACE_STACK_SIZE];
947 char * names[BACKTRACE_STACK_SIZE];
948 char namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
950 int i;
951 int levels;
953 ZERO_ARRAY(addrs);
954 ZERO_ARRAY(names);
955 ZERO_ARRAY(namebuf);
957 /* We need to be root so we can open our /proc entry to walk
958 * our stack. It also helps when we want to dump core.
960 become_root();
962 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
963 names[i] = namebuf + (i * NAMESIZE);
966 levels = trace_back_stack(0, addrs, names,
967 BACKTRACE_STACK_SIZE, NAMESIZE - 1);
969 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
970 for (i = 0; i < levels; i++) {
971 DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
973 #undef NAMESIZE
975 #else
976 DEBUG(0, ("unable to produce a stack trace on this platform\n"));
977 #endif
980 /*******************************************************************
981 A readdir wrapper which just returns the file name.
982 ********************************************************************/
984 const char *readdirname(DIR *p)
986 struct dirent *ptr;
987 char *dname;
989 if (!p)
990 return(NULL);
992 ptr = (struct dirent *)readdir(p);
993 if (!ptr)
994 return(NULL);
996 dname = ptr->d_name;
998 #ifdef NEXT2
999 if (telldir(p) < 0)
1000 return(NULL);
1001 #endif
1003 #ifdef HAVE_BROKEN_READDIR_NAME
1004 /* using /usr/ucb/cc is BAD */
1005 dname = dname - 2;
1006 #endif
1008 return talloc_strdup(talloc_tos(), dname);
1011 /*******************************************************************
1012 Utility function used to decide if the last component
1013 of a path matches a (possibly wildcarded) entry in a namelist.
1014 ********************************************************************/
1016 bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
1018 const char *last_component;
1020 /* if we have no list it's obviously not in the path */
1021 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1022 return False;
1025 DEBUG(8, ("is_in_path: %s\n", name));
1027 /* Get the last component of the unix name. */
1028 last_component = strrchr_m(name, '/');
1029 if (!last_component) {
1030 last_component = name;
1031 } else {
1032 last_component++; /* Go past '/' */
1035 for(; namelist->name != NULL; namelist++) {
1036 if(namelist->is_wild) {
1037 if (mask_match(last_component, namelist->name, case_sensitive)) {
1038 DEBUG(8,("is_in_path: mask match succeeded\n"));
1039 return True;
1041 } else {
1042 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1043 (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
1044 DEBUG(8,("is_in_path: match succeeded\n"));
1045 return True;
1049 DEBUG(8,("is_in_path: match not found\n"));
1050 return False;
1053 /*******************************************************************
1054 Strip a '/' separated list into an array of
1055 name_compare_enties structures suitable for
1056 passing to is_in_path(). We do this for
1057 speed so we can pre-parse all the names in the list
1058 and don't do it for each call to is_in_path().
1059 We also check if the entry contains a wildcard to
1060 remove a potentially expensive call to mask_match
1061 if possible.
1062 ********************************************************************/
1064 void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
1066 char *name_end;
1067 char *namelist;
1068 char *namelist_end;
1069 char *nameptr;
1070 int num_entries = 0;
1071 int i;
1073 (*ppname_array) = NULL;
1075 if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0')))
1076 return;
1078 namelist = talloc_strdup(talloc_tos(), namelist_in);
1079 if (namelist == NULL) {
1080 DEBUG(0,("set_namearray: talloc fail\n"));
1081 return;
1083 nameptr = namelist;
1085 namelist_end = &namelist[strlen(namelist)];
1087 /* We need to make two passes over the string. The
1088 first to count the number of elements, the second
1089 to split it.
1092 while(nameptr <= namelist_end) {
1093 if ( *nameptr == '/' ) {
1094 /* cope with multiple (useless) /s) */
1095 nameptr++;
1096 continue;
1098 /* anything left? */
1099 if ( *nameptr == '\0' )
1100 break;
1102 /* find the next '/' or consume remaining */
1103 name_end = strchr_m(nameptr, '/');
1104 if (name_end == NULL) {
1105 /* Point nameptr at the terminating '\0' */
1106 nameptr += strlen(nameptr);
1107 } else {
1108 /* next segment please */
1109 nameptr = name_end + 1;
1111 num_entries++;
1114 if(num_entries == 0) {
1115 talloc_free(namelist);
1116 return;
1119 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
1120 DEBUG(0,("set_namearray: malloc fail\n"));
1121 talloc_free(namelist);
1122 return;
1125 /* Now copy out the names */
1126 nameptr = namelist;
1127 i = 0;
1128 while(nameptr <= namelist_end) {
1129 if ( *nameptr == '/' ) {
1130 /* cope with multiple (useless) /s) */
1131 nameptr++;
1132 continue;
1134 /* anything left? */
1135 if ( *nameptr == '\0' )
1136 break;
1138 /* find the next '/' or consume remaining */
1139 name_end = strchr_m(nameptr, '/');
1140 if (name_end != NULL) {
1141 *name_end = '\0';
1144 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1145 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1146 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1147 talloc_free(namelist);
1148 return;
1151 if (name_end == NULL) {
1152 /* Point nameptr at the terminating '\0' */
1153 nameptr += strlen(nameptr);
1154 } else {
1155 /* next segment please */
1156 nameptr = name_end + 1;
1158 i++;
1161 (*ppname_array)[i].name = NULL;
1163 talloc_free(namelist);
1164 return;
1167 #undef DBGC_CLASS
1168 #define DBGC_CLASS DBGC_LOCKING
1170 /****************************************************************************
1171 Simple routine to query existing file locks. Cruft in NFS and 64->32 bit mapping
1172 is dealt with in posix.c
1173 Returns True if we have information regarding this lock region (and returns
1174 F_UNLCK in *ptype if the region is unlocked). False if the call failed.
1175 ****************************************************************************/
1177 bool fcntl_getlock(int fd, int op, off_t *poffset, off_t *pcount, int *ptype, pid_t *ppid)
1179 struct flock lock;
1180 int ret;
1182 DEBUG(8,("fcntl_getlock fd=%d op=%d offset=%.0f count=%.0f type=%d\n",
1183 fd,op,(double)*poffset,(double)*pcount,*ptype));
1185 lock.l_type = *ptype;
1186 lock.l_whence = SEEK_SET;
1187 lock.l_start = *poffset;
1188 lock.l_len = *pcount;
1189 lock.l_pid = 0;
1191 ret = sys_fcntl_ptr(fd,op,&lock);
1193 if (ret == -1) {
1194 int sav = errno;
1195 DEBUG(3,("fcntl_getlock: lock request failed at offset %.0f count %.0f type %d (%s)\n",
1196 (double)*poffset,(double)*pcount,*ptype,strerror(errno)));
1197 errno = sav;
1198 return False;
1201 *ptype = lock.l_type;
1202 *poffset = lock.l_start;
1203 *pcount = lock.l_len;
1204 *ppid = lock.l_pid;
1206 DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
1207 fd, (int)lock.l_type, (unsigned int)lock.l_pid));
1208 return True;
1211 #if defined(HAVE_OFD_LOCKS)
1212 int map_process_lock_to_ofd_lock(int op, bool *use_ofd_locks)
1214 switch (op) {
1215 case F_GETLK:
1216 case F_OFD_GETLK:
1217 op = F_OFD_GETLK;
1218 break;
1219 case F_SETLK:
1220 case F_OFD_SETLK:
1221 op = F_OFD_SETLK;
1222 break;
1223 case F_SETLKW:
1224 case F_OFD_SETLKW:
1225 op = F_OFD_SETLKW;
1226 break;
1227 default:
1228 *use_ofd_locks = false;
1229 return -1;
1231 *use_ofd_locks = true;
1232 return op;
1234 #else /* HAVE_OFD_LOCKS */
1235 int map_process_lock_to_ofd_lock(int op, bool *use_ofd_locks)
1237 *use_ofd_locks = false;
1238 return op;
1240 #endif /* HAVE_OFD_LOCKS */
1242 #undef DBGC_CLASS
1243 #define DBGC_CLASS DBGC_ALL
1245 /*******************************************************************
1246 Is the name specified one of my netbios names.
1247 Returns true if it is equal, false otherwise.
1248 ********************************************************************/
1250 bool is_myname(const char *s)
1252 int n;
1253 bool ret = False;
1255 for (n=0; my_netbios_names(n); n++) {
1256 const char *nbt_name = my_netbios_names(n);
1258 if (strncasecmp_m(nbt_name, s, MAX_NETBIOSNAME_LEN-1) == 0) {
1259 ret=True;
1260 break;
1263 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1264 return(ret);
1267 /*******************************************************************
1268 we distinguish between 2K and XP by the "Native Lan Manager" string
1269 WinXP => "Windows 2002 5.1"
1270 WinXP 64bit => "Windows XP 5.2"
1271 Win2k => "Windows 2000 5.0"
1272 NT4 => "Windows NT 4.0"
1273 Win9x => "Windows 4.0"
1274 Windows 2003 doesn't set the native lan manager string but
1275 they do set the domain to "Windows 2003 5.2" (probably a bug).
1276 ********************************************************************/
1278 void ra_lanman_string( const char *native_lanman )
1280 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1281 set_remote_arch( RA_WINXP );
1282 else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
1283 set_remote_arch( RA_WINXP64 );
1284 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1285 set_remote_arch( RA_WIN2K3 );
1288 static const char *remote_arch_strings[] = {
1289 [RA_UNKNOWN] = "UNKNOWN",
1290 [RA_WFWG] = "WfWg",
1291 [RA_OS2] = "OS2",
1292 [RA_WIN95] = "Win95",
1293 [RA_WINNT] = "WinNT",
1294 [RA_WIN2K] = "Win2K",
1295 [RA_WINXP] = "WinXP",
1296 [RA_WIN2K3] = "Win2K3",
1297 [RA_VISTA] = "Vista",
1298 [RA_SAMBA] = "Samba",
1299 [RA_CIFSFS] = "CIFSFS",
1300 [RA_WINXP64] = "WinXP64",
1301 [RA_OSX] = "OSX",
1304 const char *get_remote_arch_str(void)
1306 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1308 * set_remote_arch() already checks this so ra_type
1309 * should be in the allowed range, but anyway, let's
1310 * do another bound check here.
1312 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1313 ra_type = RA_UNKNOWN;
1315 return remote_arch_strings[ra_type];
1318 enum remote_arch_types get_remote_arch_from_str(const char *remote_arch_string)
1320 int i;
1322 for (i = 0; i < ARRAY_SIZE(remote_arch_strings); i++) {
1323 if (strcmp(remote_arch_string, remote_arch_strings[i]) == 0) {
1324 return i;
1327 return RA_UNKNOWN;
1330 /*******************************************************************
1331 Set the horrid remote_arch string based on an enum.
1332 ********************************************************************/
1334 void set_remote_arch(enum remote_arch_types type)
1336 if (ra_type >= ARRAY_SIZE(remote_arch_strings)) {
1338 * This protects against someone adding values to enum
1339 * remote_arch_types without updating
1340 * remote_arch_strings array.
1342 DBG_ERR("Remote arch info out of sync [%d] missing\n", ra_type);
1343 ra_type = RA_UNKNOWN;
1344 return;
1347 ra_type = type;
1348 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
1349 get_remote_arch_str()));
1352 /*******************************************************************
1353 Get the remote_arch type.
1354 ********************************************************************/
1356 enum remote_arch_types get_remote_arch(void)
1358 return ra_type;
1361 #define RA_CACHE_TTL 7*24*3600
1363 static bool remote_arch_cache_key(const struct GUID *client_guid,
1364 fstring key)
1366 struct GUID_txt_buf guid_buf;
1367 const char *guid_string = NULL;
1369 guid_string = GUID_buf_string(client_guid, &guid_buf);
1370 if (guid_string == NULL) {
1371 return false;
1374 fstr_sprintf(key, "RA/%s", guid_string);
1375 return true;
1378 struct ra_parser_state {
1379 bool found;
1380 enum remote_arch_types ra;
1383 static void ra_parser(time_t timeout, DATA_BLOB blob, void *priv_data)
1385 struct ra_parser_state *state = (struct ra_parser_state *)priv_data;
1386 const char *ra_str = NULL;
1388 if (timeout <= time(NULL)) {
1389 return;
1392 if ((blob.length == 0) || (blob.data[blob.length-1] != '\0')) {
1393 DBG_ERR("Remote arch cache key not a string\n");
1394 return;
1397 ra_str = (const char *)blob.data;
1398 DBG_INFO("Got remote arch [%s] from cache\n", ra_str);
1400 state->ra = get_remote_arch_from_str(ra_str);
1401 state->found = true;
1402 return;
1405 static bool remote_arch_cache_get(const struct GUID *client_guid)
1407 bool ok;
1408 fstring ra_key;
1409 struct ra_parser_state state = (struct ra_parser_state) {
1410 .found = false,
1411 .ra = RA_UNKNOWN,
1414 ok = remote_arch_cache_key(client_guid, ra_key);
1415 if (!ok) {
1416 return false;
1419 ok = gencache_parse(ra_key, ra_parser, &state);
1420 if (!ok || !state.found) {
1421 return true;
1424 if (state.ra == RA_UNKNOWN) {
1425 return true;
1428 set_remote_arch(state.ra);
1429 return true;
1432 static bool remote_arch_cache_set(const struct GUID *client_guid)
1434 bool ok;
1435 fstring ra_key;
1436 const char *ra_str = NULL;
1438 if (get_remote_arch() == RA_UNKNOWN) {
1439 return true;
1442 ok = remote_arch_cache_key(client_guid, ra_key);
1443 if (!ok) {
1444 return false;
1447 ra_str = get_remote_arch_str();
1448 if (ra_str == NULL) {
1449 return false;
1452 ok = gencache_set(ra_key, ra_str, time(NULL) + RA_CACHE_TTL);
1453 if (!ok) {
1454 return false;
1457 return true;
1460 bool remote_arch_cache_update(const struct GUID *client_guid)
1462 bool ok;
1464 if (get_remote_arch() == RA_UNKNOWN) {
1466 become_root();
1467 ok = remote_arch_cache_get(client_guid);
1468 unbecome_root();
1470 return ok;
1473 become_root();
1474 ok = remote_arch_cache_set(client_guid);
1475 unbecome_root();
1477 return ok;
1480 bool remote_arch_cache_delete(const struct GUID *client_guid)
1482 bool ok;
1483 fstring ra_key;
1485 ok = remote_arch_cache_key(client_guid, ra_key);
1486 if (!ok) {
1487 return false;
1490 become_root();
1491 ok = gencache_del(ra_key);
1492 unbecome_root();
1494 if (!ok) {
1495 return false;
1498 return true;
1501 const char *tab_depth(int level, int depth)
1503 if( CHECK_DEBUGLVL(level) ) {
1504 dbgtext("%*s", depth*4, "");
1506 return "";
1509 /*****************************************************************************
1510 Provide a checksum on a string
1512 Input: s - the null-terminated character string for which the checksum
1513 will be calculated.
1515 Output: The checksum value calculated for s.
1516 *****************************************************************************/
1518 int str_checksum(const char *s)
1520 TDB_DATA key;
1521 if (s == NULL)
1522 return 0;
1524 key = (TDB_DATA) { .dptr = discard_const_p(uint8_t, s),
1525 .dsize = strlen(s) };
1527 return tdb_jenkins_hash(&key);
1530 /*****************************************************************
1531 Zero a memory area then free it. Used to catch bugs faster.
1532 *****************************************************************/
1534 void zero_free(void *p, size_t size)
1536 memset(p, 0, size);
1537 SAFE_FREE(p);
1540 /*****************************************************************
1541 Set our open file limit to a requested max and return the limit.
1542 *****************************************************************/
1544 int set_maxfiles(int requested_max)
1546 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1547 struct rlimit rlp;
1548 int saved_current_limit;
1550 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1551 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1552 strerror(errno) ));
1553 /* just guess... */
1554 return requested_max;
1558 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1559 * account for the extra fd we need
1560 * as well as the log files and standard
1561 * handles etc. Save the limit we want to set in case
1562 * we are running on an OS that doesn't support this limit (AIX)
1563 * which always returns RLIM_INFINITY for rlp.rlim_max.
1566 /* Try raising the hard (max) limit to the requested amount. */
1568 #if defined(RLIM_INFINITY)
1569 if (rlp.rlim_max != RLIM_INFINITY) {
1570 int orig_max = rlp.rlim_max;
1572 if ( rlp.rlim_max < requested_max )
1573 rlp.rlim_max = requested_max;
1575 /* This failing is not an error - many systems (Linux) don't
1576 support our default request of 10,000 open files. JRA. */
1578 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1579 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1580 (int)rlp.rlim_max, strerror(errno) ));
1582 /* Set failed - restore original value from get. */
1583 rlp.rlim_max = orig_max;
1586 #endif
1588 /* Now try setting the soft (current) limit. */
1590 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1592 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1593 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1594 (int)rlp.rlim_cur, strerror(errno) ));
1595 /* just guess... */
1596 return saved_current_limit;
1599 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1600 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1601 strerror(errno) ));
1602 /* just guess... */
1603 return saved_current_limit;
1606 #if defined(RLIM_INFINITY)
1607 if(rlp.rlim_cur == RLIM_INFINITY)
1608 return saved_current_limit;
1609 #endif
1611 if((int)rlp.rlim_cur > saved_current_limit)
1612 return saved_current_limit;
1614 return rlp.rlim_cur;
1615 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1617 * No way to know - just guess...
1619 return requested_max;
1620 #endif
1623 /*****************************************************************
1624 malloc that aborts with smb_panic on fail or zero size.
1625 *****************************************************************/
1627 void *smb_xmalloc_array(size_t size, unsigned int count)
1629 void *p;
1630 if (size == 0) {
1631 smb_panic("smb_xmalloc_array: called with zero size");
1633 if (count >= MAX_ALLOC_SIZE/size) {
1634 smb_panic("smb_xmalloc_array: alloc size too large");
1636 if ((p = SMB_MALLOC(size*count)) == NULL) {
1637 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
1638 (unsigned long)size, (unsigned long)count));
1639 smb_panic("smb_xmalloc_array: malloc failed");
1641 return p;
1645 vasprintf that aborts on malloc fail
1648 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
1650 int n;
1651 va_list ap2;
1653 va_copy(ap2, ap);
1655 n = vasprintf(ptr, format, ap2);
1656 va_end(ap2);
1657 if (n == -1 || ! *ptr) {
1658 smb_panic("smb_xvasprintf: out of memory");
1660 return n;
1663 /*****************************************************************
1664 Get local hostname and cache result.
1665 *****************************************************************/
1667 char *myhostname(void)
1669 static char *ret;
1670 if (ret == NULL) {
1671 ret = get_myname(NULL);
1673 return ret;
1676 /*****************************************************************
1677 Get local hostname and cache result.
1678 *****************************************************************/
1680 char *myhostname_upper(void)
1682 static char *ret;
1683 if (ret == NULL) {
1684 char *name = get_myname(NULL);
1685 if (name == NULL) {
1686 return NULL;
1688 ret = strupper_talloc(NULL, name);
1689 talloc_free(name);
1691 return ret;
1694 /*******************************************************************
1695 Given a filename - get its directory name
1696 ********************************************************************/
1698 bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
1699 const char **name)
1701 char *p;
1702 ptrdiff_t len;
1704 p = strrchr_m(dir, '/'); /* Find final '/', if any */
1706 if (p == NULL) {
1707 if (!(*parent = talloc_strdup(mem_ctx, "."))) {
1708 return False;
1710 if (name) {
1711 *name = dir;
1713 return True;
1716 len = p-dir;
1718 if (!(*parent = (char *)talloc_memdup(mem_ctx, dir, len+1))) {
1719 return False;
1721 (*parent)[len] = '\0';
1723 if (name) {
1724 *name = p+1;
1726 return True;
1729 /*******************************************************************
1730 Determine if a pattern contains any Microsoft wildcard characters.
1731 *******************************************************************/
1733 bool ms_has_wild(const char *s)
1735 char c;
1737 while ((c = *s++)) {
1738 switch (c) {
1739 case '*':
1740 case '?':
1741 case '<':
1742 case '>':
1743 case '"':
1744 return True;
1747 return False;
1750 bool ms_has_wild_w(const smb_ucs2_t *s)
1752 smb_ucs2_t c;
1753 if (!s) return False;
1754 while ((c = *s++)) {
1755 switch (c) {
1756 case UCS2_CHAR('*'):
1757 case UCS2_CHAR('?'):
1758 case UCS2_CHAR('<'):
1759 case UCS2_CHAR('>'):
1760 case UCS2_CHAR('"'):
1761 return True;
1764 return False;
1767 /*******************************************************************
1768 A wrapper that handles case sensitivity and the special handling
1769 of the ".." name.
1770 *******************************************************************/
1772 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
1774 if (ISDOTDOT(string))
1775 string = ".";
1776 if (ISDOT(pattern))
1777 return False;
1779 return ms_fnmatch_protocol(pattern, string, Protocol, is_case_sensitive) == 0;
1782 /*******************************************************************
1783 A wrapper that handles case sensitivity and the special handling
1784 of the ".." name. Varient that is only called by old search code which requires
1785 pattern translation.
1786 *******************************************************************/
1788 bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
1790 if (ISDOTDOT(string))
1791 string = ".";
1792 if (ISDOT(pattern))
1793 return False;
1795 return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
1798 /*******************************************************************
1799 A wrapper that handles a list of patters and calls mask_match()
1800 on each. Returns True if any of the patterns match.
1801 *******************************************************************/
1803 bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
1805 while (listLen-- > 0) {
1806 if (mask_match(string, *list++, is_case_sensitive))
1807 return True;
1809 return False;
1812 /**********************************************************************
1813 Converts a name to a fully qualified domain name.
1814 Returns true if lookup succeeded, false if not (then fqdn is set to name)
1815 Uses getaddrinfo() with AI_CANONNAME flag to obtain the official
1816 canonical name of the host. getaddrinfo() may use a variety of sources
1817 including /etc/hosts to obtain the domainname. It expects aliases in
1818 /etc/hosts to NOT be the FQDN. The FQDN should come first.
1819 ************************************************************************/
1821 bool name_to_fqdn(fstring fqdn, const char *name)
1823 char *full = NULL;
1824 struct addrinfo hints;
1825 struct addrinfo *result;
1826 int s;
1828 /* Configure hints to obtain canonical name */
1830 memset(&hints, 0, sizeof(struct addrinfo));
1831 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1832 hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
1833 hints.ai_flags = AI_CANONNAME; /* Get host's FQDN */
1834 hints.ai_protocol = 0; /* Any protocol */
1836 s = getaddrinfo(name, NULL, &hints, &result);
1837 if (s != 0) {
1838 DEBUG(1, ("getaddrinfo: %s\n", gai_strerror(s)));
1839 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
1840 fstrcpy(fqdn, name);
1841 return false;
1843 full = result->ai_canonname;
1845 /* Find out if the FQDN is returned as an alias
1846 * to cope with /etc/hosts files where the first
1847 * name is not the FQDN but the short name.
1848 * getaddrinfo provides no easy way of handling aliases
1849 * in /etc/hosts. Users should make sure the FQDN
1850 * comes first in /etc/hosts. */
1851 if (full && (! strchr_m(full, '.'))) {
1852 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1853 DEBUGADD(1, (" Full qualified domain names (FQDNs) should not be specified\n"));
1854 DEBUGADD(1, (" as an alias in /etc/hosts. FQDN should be the first name\n"));
1855 DEBUGADD(1, (" prior to any aliases.\n"));
1857 if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
1858 DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
1859 DEBUGADD(1, (" Specifying the machine hostname for address 127.0.0.1 may lead\n"));
1860 DEBUGADD(1, (" to Kerberos authentication problems as localhost.localdomain\n"));
1861 DEBUGADD(1, (" may end up being used instead of the real machine FQDN.\n"));
1864 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, full));
1865 fstrcpy(fqdn, full);
1866 freeaddrinfo(result); /* No longer needed */
1867 return true;
1870 uint32_t map_share_mode_to_deny_mode(uint32_t share_access, uint32_t private_options)
1872 switch (share_access & ~FILE_SHARE_DELETE) {
1873 case FILE_SHARE_NONE:
1874 return DENY_ALL;
1875 case FILE_SHARE_READ:
1876 return DENY_WRITE;
1877 case FILE_SHARE_WRITE:
1878 return DENY_READ;
1879 case FILE_SHARE_READ|FILE_SHARE_WRITE:
1880 return DENY_NONE;
1882 if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) {
1883 return DENY_DOS;
1884 } else if (private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_FCB) {
1885 return DENY_FCB;
1888 return (uint32_t)-1;
1891 struct server_id interpret_pid(const char *pid_string)
1893 return server_id_from_string(get_my_vnn(), pid_string);
1896 /****************************************************************
1897 Check if an offset into a buffer is safe.
1898 If this returns True it's safe to indirect into the byte at
1899 pointer ptr+off.
1900 ****************************************************************/
1902 bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1904 const char *end_base = buf_base + buf_len;
1905 char *end_ptr = ptr + off;
1907 if (!buf_base || !ptr) {
1908 return False;
1911 if (end_base < buf_base || end_ptr < ptr) {
1912 return False; /* wrap. */
1915 if (end_ptr < end_base) {
1916 return True;
1918 return False;
1921 /****************************************************************
1922 Return a safe pointer into a buffer, or NULL.
1923 ****************************************************************/
1925 char *get_safe_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1927 return is_offset_safe(buf_base, buf_len, ptr, off) ?
1928 ptr + off : NULL;
1931 /****************************************************************
1932 Return a safe pointer into a string within a buffer, or NULL.
1933 ****************************************************************/
1935 char *get_safe_str_ptr(const char *buf_base, size_t buf_len, char *ptr, size_t off)
1937 if (!is_offset_safe(buf_base, buf_len, ptr, off)) {
1938 return NULL;
1940 /* Check if a valid string exists at this offset. */
1941 if (skip_string(buf_base,buf_len, ptr + off) == NULL) {
1942 return NULL;
1944 return ptr + off;
1947 /****************************************************************
1948 Return an SVAL at a pointer, or failval if beyond the end.
1949 ****************************************************************/
1951 int get_safe_SVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1954 * Note we use off+1 here, not off+2 as SVAL accesses ptr[0] and ptr[1],
1955 * NOT ptr[2].
1957 if (!is_offset_safe(buf_base, buf_len, ptr, off+1)) {
1958 return failval;
1960 return SVAL(ptr,off);
1963 /****************************************************************
1964 Return an IVAL at a pointer, or failval if beyond the end.
1965 ****************************************************************/
1967 int get_safe_IVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, int failval)
1970 * Note we use off+3 here, not off+4 as IVAL accesses
1971 * ptr[0] ptr[1] ptr[2] ptr[3] NOT ptr[4].
1973 if (!is_offset_safe(buf_base, buf_len, ptr, off+3)) {
1974 return failval;
1976 return IVAL(ptr,off);
1979 /****************************************************************
1980 Split DOM\user into DOM and user. Do not mix with winbind variants of that
1981 call (they take care of winbind separator and other winbind specific settings).
1982 ****************************************************************/
1984 bool split_domain_user(TALLOC_CTX *mem_ctx,
1985 const char *full_name,
1986 char **domain,
1987 char **user)
1989 const char *p = NULL;
1991 p = strchr_m(full_name, '\\');
1993 if (p != NULL) {
1994 *domain = talloc_strndup(mem_ctx, full_name,
1995 PTR_DIFF(p, full_name));
1996 if (*domain == NULL) {
1997 return false;
1999 *user = talloc_strdup(mem_ctx, p+1);
2000 if (*user == NULL) {
2001 TALLOC_FREE(*domain);
2002 return false;
2004 } else {
2005 *domain = NULL;
2006 *user = talloc_strdup(mem_ctx, full_name);
2007 if (*user == NULL) {
2008 return false;
2012 return true;
2015 /****************************************************************
2016 strip off leading '\\' from a hostname
2017 ****************************************************************/
2019 const char *strip_hostname(const char *s)
2021 if (!s) {
2022 return NULL;
2025 if (strlen_m(s) < 3) {
2026 return s;
2029 if (s[0] == '\\') s++;
2030 if (s[0] == '\\') s++;
2032 return s;
2035 bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
2037 if (!NT_STATUS_IS_OK(err1)) {
2038 *result = err1;
2039 return true;
2041 if (!NT_STATUS_IS_OK(err2)) {
2042 *result = err2;
2043 return true;
2045 return false;
2048 int timeval_to_msec(struct timeval t)
2050 return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
2053 /*******************************************************************
2054 Check a given DOS pathname is valid for a share.
2055 ********************************************************************/
2057 char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
2059 char *ptr = NULL;
2061 if (!dos_pathname) {
2062 return NULL;
2065 ptr = talloc_strdup(ctx, dos_pathname);
2066 if (!ptr) {
2067 return NULL;
2069 /* Convert any '\' paths to '/' */
2070 unix_format(ptr);
2071 ptr = unix_clean_name(ctx, ptr);
2072 if (!ptr) {
2073 return NULL;
2076 /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
2077 if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
2078 ptr += 2;
2080 /* Only absolute paths allowed. */
2081 if (*ptr != '/')
2082 return NULL;
2084 return ptr;
2087 /*******************************************************************
2088 Return True if the filename is one of the special executable types.
2089 ********************************************************************/
2091 bool is_executable(const char *fname)
2093 if ((fname = strrchr_m(fname,'.'))) {
2094 if (strequal(fname,".com") ||
2095 strequal(fname,".dll") ||
2096 strequal(fname,".exe") ||
2097 strequal(fname,".sym")) {
2098 return True;
2101 return False;
2104 /****************************************************************************
2105 Open a file with a share mode - old openX method - map into NTCreate.
2106 ****************************************************************************/
2108 bool map_open_params_to_ntcreate(const char *smb_base_fname,
2109 int deny_mode, int open_func,
2110 uint32_t *paccess_mask,
2111 uint32_t *pshare_mode,
2112 uint32_t *pcreate_disposition,
2113 uint32_t *pcreate_options,
2114 uint32_t *pprivate_flags)
2116 uint32_t access_mask;
2117 uint32_t share_mode;
2118 uint32_t create_disposition;
2119 uint32_t create_options = FILE_NON_DIRECTORY_FILE;
2120 uint32_t private_flags = 0;
2122 DEBUG(10,("map_open_params_to_ntcreate: fname = %s, deny_mode = 0x%x, "
2123 "open_func = 0x%x\n",
2124 smb_base_fname, (unsigned int)deny_mode,
2125 (unsigned int)open_func ));
2127 /* Create the NT compatible access_mask. */
2128 switch (GET_OPENX_MODE(deny_mode)) {
2129 case DOS_OPEN_EXEC: /* Implies read-only - used to be FILE_READ_DATA */
2130 case DOS_OPEN_RDONLY:
2131 access_mask = FILE_GENERIC_READ;
2132 break;
2133 case DOS_OPEN_WRONLY:
2134 access_mask = FILE_GENERIC_WRITE;
2135 break;
2136 case DOS_OPEN_RDWR:
2137 case DOS_OPEN_FCB:
2138 access_mask = FILE_GENERIC_READ|FILE_GENERIC_WRITE;
2139 break;
2140 default:
2141 DEBUG(10,("map_open_params_to_ntcreate: bad open mode = 0x%x\n",
2142 (unsigned int)GET_OPENX_MODE(deny_mode)));
2143 return False;
2146 /* Create the NT compatible create_disposition. */
2147 switch (open_func) {
2148 case OPENX_FILE_EXISTS_FAIL|OPENX_FILE_CREATE_IF_NOT_EXIST:
2149 create_disposition = FILE_CREATE;
2150 break;
2152 case OPENX_FILE_EXISTS_OPEN:
2153 create_disposition = FILE_OPEN;
2154 break;
2156 case OPENX_FILE_EXISTS_OPEN|OPENX_FILE_CREATE_IF_NOT_EXIST:
2157 create_disposition = FILE_OPEN_IF;
2158 break;
2160 case OPENX_FILE_EXISTS_TRUNCATE:
2161 create_disposition = FILE_OVERWRITE;
2162 break;
2164 case OPENX_FILE_EXISTS_TRUNCATE|OPENX_FILE_CREATE_IF_NOT_EXIST:
2165 create_disposition = FILE_OVERWRITE_IF;
2166 break;
2168 default:
2169 /* From samba4 - to be confirmed. */
2170 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_EXEC) {
2171 create_disposition = FILE_CREATE;
2172 break;
2174 DEBUG(10,("map_open_params_to_ntcreate: bad "
2175 "open_func 0x%x\n", (unsigned int)open_func));
2176 return False;
2179 /* Create the NT compatible share modes. */
2180 switch (GET_DENY_MODE(deny_mode)) {
2181 case DENY_ALL:
2182 share_mode = FILE_SHARE_NONE;
2183 break;
2185 case DENY_WRITE:
2186 share_mode = FILE_SHARE_READ;
2187 break;
2189 case DENY_READ:
2190 share_mode = FILE_SHARE_WRITE;
2191 break;
2193 case DENY_NONE:
2194 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2195 break;
2197 case DENY_DOS:
2198 private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_DOS;
2199 if (is_executable(smb_base_fname)) {
2200 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
2201 } else {
2202 if (GET_OPENX_MODE(deny_mode) == DOS_OPEN_RDONLY) {
2203 share_mode = FILE_SHARE_READ;
2204 } else {
2205 share_mode = FILE_SHARE_NONE;
2208 break;
2210 case DENY_FCB:
2211 private_flags |= NTCREATEX_OPTIONS_PRIVATE_DENY_FCB;
2212 share_mode = FILE_SHARE_NONE;
2213 break;
2215 default:
2216 DEBUG(10,("map_open_params_to_ntcreate: bad deny_mode 0x%x\n",
2217 (unsigned int)GET_DENY_MODE(deny_mode) ));
2218 return False;
2221 DEBUG(10,("map_open_params_to_ntcreate: file %s, access_mask = 0x%x, "
2222 "share_mode = 0x%x, create_disposition = 0x%x, "
2223 "create_options = 0x%x private_flags = 0x%x\n",
2224 smb_base_fname,
2225 (unsigned int)access_mask,
2226 (unsigned int)share_mode,
2227 (unsigned int)create_disposition,
2228 (unsigned int)create_options,
2229 (unsigned int)private_flags));
2231 if (paccess_mask) {
2232 *paccess_mask = access_mask;
2234 if (pshare_mode) {
2235 *pshare_mode = share_mode;
2237 if (pcreate_disposition) {
2238 *pcreate_disposition = create_disposition;
2240 if (pcreate_options) {
2241 *pcreate_options = create_options;
2243 if (pprivate_flags) {
2244 *pprivate_flags = private_flags;
2247 return True;
2251 /*************************************************************************
2252 Return a talloced copy of a struct security_unix_token. NULL on fail.
2253 *************************************************************************/
2255 struct security_unix_token *copy_unix_token(TALLOC_CTX *ctx, const struct security_unix_token *tok)
2257 struct security_unix_token *cpy;
2259 cpy = talloc(ctx, struct security_unix_token);
2260 if (!cpy) {
2261 return NULL;
2264 cpy->uid = tok->uid;
2265 cpy->gid = tok->gid;
2266 cpy->ngroups = tok->ngroups;
2267 if (tok->ngroups) {
2268 /* Make this a talloc child of cpy. */
2269 cpy->groups = (gid_t *)talloc_memdup(
2270 cpy, tok->groups, tok->ngroups * sizeof(gid_t));
2271 if (!cpy->groups) {
2272 TALLOC_FREE(cpy);
2273 return NULL;
2275 } else {
2276 cpy->groups = NULL;
2278 return cpy;
2281 /****************************************************************************
2282 Check that a file matches a particular file type.
2283 ****************************************************************************/
2285 bool dir_check_ftype(uint32_t mode, uint32_t dirtype)
2287 uint32_t mask;
2289 /* Check the "may have" search bits. */
2290 if (((mode & ~dirtype) &
2291 (FILE_ATTRIBUTE_HIDDEN |
2292 FILE_ATTRIBUTE_SYSTEM |
2293 FILE_ATTRIBUTE_DIRECTORY)) != 0) {
2294 return false;
2297 /* Check the "must have" bits,
2298 which are the may have bits shifted eight */
2299 /* If must have bit is set, the file/dir can
2300 not be returned in search unless the matching
2301 file attribute is set */
2302 mask = ((dirtype >> 8) & (FILE_ATTRIBUTE_DIRECTORY|
2303 FILE_ATTRIBUTE_ARCHIVE|
2304 FILE_ATTRIBUTE_READONLY|
2305 FILE_ATTRIBUTE_HIDDEN|
2306 FILE_ATTRIBUTE_SYSTEM)); /* & 0x37 */
2307 if(mask) {
2308 if((mask & (mode & (FILE_ATTRIBUTE_DIRECTORY|
2309 FILE_ATTRIBUTE_ARCHIVE|
2310 FILE_ATTRIBUTE_READONLY|
2311 FILE_ATTRIBUTE_HIDDEN|
2312 FILE_ATTRIBUTE_SYSTEM))) == mask) {
2313 /* check if matching attribute present */
2314 return true;
2315 } else {
2316 return false;
2320 return true;