skel_ -> cap_
[Samba/gebeck_regimport.git] / source3 / lib / util.c
blob5f4fae9baa2b62b3c0801ebd68dc62d13cb3c84b
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2002
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include "includes.h"
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
30 * The following lines are needed due to buggy include files
31 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
32 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
33 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
34 * an enum in /usr/include/rpcsvc/nis.h.
37 #if defined(GROUP)
38 #undef GROUP
39 #endif
41 #if defined(GROUP_OBJ)
42 #undef GROUP_OBJ
43 #endif
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
47 #include <rpcsvc/nis.h>
49 #else /* !WITH_NISPLUS_HOME */
51 #include "rpcsvc/ypclnt.h"
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
56 int Protocol = PROTOCOL_COREPLUS;
58 /* a default finfo structure to ensure all fields are sensible */
59 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
61 /* this is used by the chaining code */
62 int chain_size = 0;
64 int trans_num = 0;
67 case handling on filenames
69 int case_default = CASE_LOWER;
71 /* the following control case operations - they are put here so the
72 client can link easily */
73 BOOL case_sensitive;
74 BOOL case_preserve;
75 BOOL use_mangled_map = False;
76 BOOL short_case_preserve;
77 BOOL case_mangle;
79 static enum remote_arch_types ra_type = RA_UNKNOWN;
80 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
82 /***********************************************************************
83 Definitions for all names.
84 ***********************************************************************/
86 static char *smb_myname;
87 static char *smb_myworkgroup;
88 static char *smb_scope;
89 static int smb_num_netbios_names;
90 static char **smb_my_netbios_names;
92 /***********************************************************************
93 Allocate and set myname. Ensure upper case.
94 ***********************************************************************/
96 BOOL set_global_myname(const char *myname)
98 SAFE_FREE(smb_myname);
99 smb_myname = strdup(myname);
100 if (!smb_myname)
101 return False;
102 strupper_m(smb_myname);
103 return True;
106 const char *global_myname(void)
108 return smb_myname;
111 /***********************************************************************
112 Allocate and set myworkgroup. Ensure upper case.
113 ***********************************************************************/
115 BOOL set_global_myworkgroup(const char *myworkgroup)
117 SAFE_FREE(smb_myworkgroup);
118 smb_myworkgroup = strdup(myworkgroup);
119 if (!smb_myworkgroup)
120 return False;
121 strupper_m(smb_myworkgroup);
122 return True;
125 const char *lp_workgroup(void)
127 return smb_myworkgroup;
130 /***********************************************************************
131 Allocate and set scope. Ensure upper case.
132 ***********************************************************************/
134 BOOL set_global_scope(const char *scope)
136 SAFE_FREE(smb_scope);
137 smb_scope = strdup(scope);
138 if (!smb_scope)
139 return False;
140 strupper_m(smb_scope);
141 return True;
144 /*********************************************************************
145 Ensure scope is never null string.
146 *********************************************************************/
148 const char *global_scope(void)
150 if (!smb_scope)
151 set_global_scope("");
152 return smb_scope;
155 static void free_netbios_names_array(void)
157 int i;
159 for (i = 0; i < smb_num_netbios_names; i++)
160 SAFE_FREE(smb_my_netbios_names[i]);
162 SAFE_FREE(smb_my_netbios_names);
163 smb_num_netbios_names = 0;
166 static BOOL allocate_my_netbios_names_array(size_t number)
168 free_netbios_names_array();
170 smb_num_netbios_names = number + 1;
171 smb_my_netbios_names = (char **)malloc( sizeof(char *) * smb_num_netbios_names );
173 if (!smb_my_netbios_names)
174 return False;
176 memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
177 return True;
180 static BOOL set_my_netbios_names(const char *name, int i)
182 SAFE_FREE(smb_my_netbios_names[i]);
184 smb_my_netbios_names[i] = strdup(name);
185 if (!smb_my_netbios_names[i])
186 return False;
187 strupper_m(smb_my_netbios_names[i]);
188 return True;
191 const char *my_netbios_names(int i)
193 return smb_my_netbios_names[i];
196 BOOL set_netbios_aliases(const char **str_array)
198 size_t namecount;
200 /* Work out the max number of netbios aliases that we have */
201 for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
204 if ( global_myname() && *global_myname())
205 namecount++;
207 /* Allocate space for the netbios aliases */
208 if (!allocate_my_netbios_names_array(namecount))
209 return False;
211 /* Use the global_myname string first */
212 namecount=0;
213 if ( global_myname() && *global_myname()) {
214 set_my_netbios_names( global_myname(), namecount );
215 namecount++;
218 if (str_array) {
219 size_t i;
220 for ( i = 0; str_array[i] != NULL; i++) {
221 size_t n;
222 BOOL duplicate = False;
224 /* Look for duplicates */
225 for( n=0; n<namecount; n++ ) {
226 if( strequal( str_array[i], my_netbios_names(n) ) ) {
227 duplicate = True;
228 break;
231 if (!duplicate) {
232 if (!set_my_netbios_names(str_array[i], namecount))
233 return False;
234 namecount++;
238 return True;
241 /****************************************************************************
242 Common name initialization code.
243 ****************************************************************************/
245 BOOL init_names(void)
247 extern fstring local_machine;
248 char *p;
249 int n;
251 if (global_myname() == NULL || *global_myname() == '\0') {
252 if (!set_global_myname(myhostname())) {
253 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
254 return False;
258 if (!set_netbios_aliases(lp_netbios_aliases())) {
259 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
260 return False;
263 fstrcpy( local_machine, global_myname() );
264 trim_string( local_machine, " ", " " );
265 p = strchr( local_machine, ' ' );
266 if (p)
267 *p = 0;
268 strlower_m( local_machine );
270 DEBUG( 5, ("Netbios name list:-\n") );
271 for( n=0; my_netbios_names(n); n++ )
272 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
274 return( True );
277 /**************************************************************************n
278 Find a suitable temporary directory. The result should be copied immediately
279 as it may be overwritten by a subsequent call.
280 ****************************************************************************/
282 const char *tmpdir(void)
284 char *p;
285 if ((p = getenv("TMPDIR")))
286 return p;
287 return "/tmp";
290 /****************************************************************************
291 Determine whether we are in the specified group.
292 ****************************************************************************/
294 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
296 int i;
298 if (group == current_gid)
299 return(True);
301 for (i=0;i<ngroups;i++)
302 if (group == groups[i])
303 return(True);
305 return(False);
308 /****************************************************************************
309 Like atoi but gets the value up to the separator character.
310 ****************************************************************************/
312 static const char *Atoic(const char *p, int *n, const char *c)
314 if (!isdigit((int)*p)) {
315 DEBUG(5, ("Atoic: malformed number\n"));
316 return NULL;
319 (*n) = atoi(p);
321 while ((*p) && isdigit((int)*p))
322 p++;
324 if (strchr_m(c, *p) == NULL) {
325 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
326 return NULL;
329 return p;
332 /*************************************************************************
333 Reads a list of numbers.
334 *************************************************************************/
336 const char *get_numlist(const char *p, uint32 **num, int *count)
338 int val;
340 if (num == NULL || count == NULL)
341 return NULL;
343 (*count) = 0;
344 (*num ) = NULL;
346 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
347 uint32 *tn;
349 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
350 if (tn == NULL) {
351 SAFE_FREE(*num);
352 return NULL;
353 } else
354 (*num) = tn;
355 (*num)[(*count)] = val;
356 (*count)++;
357 p++;
360 return p;
363 /*******************************************************************
364 Check if a file exists - call vfs_file_exist for samba files.
365 ********************************************************************/
367 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
369 SMB_STRUCT_STAT st;
370 if (!sbuf)
371 sbuf = &st;
373 if (sys_stat(fname,sbuf) != 0)
374 return(False);
376 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
379 /*******************************************************************
380 Check a files mod time.
381 ********************************************************************/
383 time_t file_modtime(const char *fname)
385 SMB_STRUCT_STAT st;
387 if (sys_stat(fname,&st) != 0)
388 return(0);
390 return(st.st_mtime);
393 /*******************************************************************
394 Check if a directory exists.
395 ********************************************************************/
397 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
399 SMB_STRUCT_STAT st2;
400 BOOL ret;
402 if (!st)
403 st = &st2;
405 if (sys_stat(dname,st) != 0)
406 return(False);
408 ret = S_ISDIR(st->st_mode);
409 if(!ret)
410 errno = ENOTDIR;
411 return ret;
414 /*******************************************************************
415 Returns the size in bytes of the named file.
416 ********************************************************************/
418 SMB_OFF_T get_file_size(char *file_name)
420 SMB_STRUCT_STAT buf;
421 buf.st_size = 0;
422 if(sys_stat(file_name,&buf) != 0)
423 return (SMB_OFF_T)-1;
424 return(buf.st_size);
427 /*******************************************************************
428 Return a string representing an attribute for a file.
429 ********************************************************************/
431 char *attrib_string(uint16 mode)
433 static fstring attrstr;
435 attrstr[0] = 0;
437 if (mode & aVOLID) fstrcat(attrstr,"V");
438 if (mode & aDIR) fstrcat(attrstr,"D");
439 if (mode & aARCH) fstrcat(attrstr,"A");
440 if (mode & aHIDDEN) fstrcat(attrstr,"H");
441 if (mode & aSYSTEM) fstrcat(attrstr,"S");
442 if (mode & aRONLY) fstrcat(attrstr,"R");
444 return(attrstr);
447 /*******************************************************************
448 Show a smb message structure.
449 ********************************************************************/
451 void show_msg(char *buf)
453 int i;
454 int bcc=0;
456 if (!DEBUGLVL(5))
457 return;
459 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
460 smb_len(buf),
461 (int)CVAL(buf,smb_com),
462 (int)CVAL(buf,smb_rcls),
463 (int)CVAL(buf,smb_reh),
464 (int)SVAL(buf,smb_err),
465 (int)CVAL(buf,smb_flg),
466 (int)SVAL(buf,smb_flg2)));
467 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
468 (int)SVAL(buf,smb_tid),
469 (int)SVAL(buf,smb_pid),
470 (int)SVAL(buf,smb_uid),
471 (int)SVAL(buf,smb_mid)));
472 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
474 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
475 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
476 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
478 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
480 DEBUGADD(5,("smb_bcc=%d\n",bcc));
482 if (DEBUGLEVEL < 10)
483 return;
485 if (DEBUGLEVEL < 50)
486 bcc = MIN(bcc, 512);
488 dump_data(10, smb_buf(buf), bcc);
491 /*******************************************************************
492 Set the length and marker of an smb packet.
493 ********************************************************************/
495 void smb_setlen(char *buf,int len)
497 _smb_setlen(buf,len);
499 SCVAL(buf,4,0xFF);
500 SCVAL(buf,5,'S');
501 SCVAL(buf,6,'M');
502 SCVAL(buf,7,'B');
505 /*******************************************************************
506 Setup the word count and byte count for a smb message.
507 ********************************************************************/
509 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
511 if (zero)
512 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
513 SCVAL(buf,smb_wct,num_words);
514 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
515 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
516 return (smb_size + num_words*2 + num_bytes);
519 /*******************************************************************
520 Setup only the byte count for a smb message.
521 ********************************************************************/
523 int set_message_bcc(char *buf,int num_bytes)
525 int num_words = CVAL(buf,smb_wct);
526 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
527 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
528 return (smb_size + num_words*2 + num_bytes);
531 /*******************************************************************
532 Setup only the byte count for a smb message, using the end of the
533 message as a marker.
534 ********************************************************************/
536 int set_message_end(void *outbuf,void *end_ptr)
538 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
541 /*******************************************************************
542 Reduce a file name, removing .. elements.
543 ********************************************************************/
545 void dos_clean_name(char *s)
547 char *p=NULL;
549 DEBUG(3,("dos_clean_name [%s]\n",s));
551 /* remove any double slashes */
552 all_string_sub(s, "\\\\", "\\", 0);
554 while ((p = strstr(s,"\\..\\")) != NULL) {
555 pstring s1;
557 *p = 0;
558 pstrcpy(s1,p+3);
560 if ((p=strrchr_m(s,'\\')) != NULL)
561 *p = 0;
562 else
563 *s = 0;
564 pstrcat(s,s1);
567 trim_string(s,NULL,"\\..");
569 all_string_sub(s, "\\.\\", "\\", 0);
572 /*******************************************************************
573 Reduce a file name, removing .. elements.
574 ********************************************************************/
576 void unix_clean_name(char *s)
578 char *p=NULL;
580 DEBUG(3,("unix_clean_name [%s]\n",s));
582 /* remove any double slashes */
583 all_string_sub(s, "//","/", 0);
585 /* Remove leading ./ characters */
586 if(strncmp(s, "./", 2) == 0) {
587 trim_string(s, "./", NULL);
588 if(*s == 0)
589 pstrcpy(s,"./");
592 while ((p = strstr(s,"/../")) != NULL) {
593 pstring s1;
595 *p = 0;
596 pstrcpy(s1,p+3);
598 if ((p=strrchr_m(s,'/')) != NULL)
599 *p = 0;
600 else
601 *s = 0;
602 pstrcat(s,s1);
605 trim_string(s,NULL,"/..");
608 /*******************************************************************
609 Convert '\' to '/'.
610 Reduce a file name, removing or reducing /../ , /./ , // elements.
611 Remove also any trailing . and /
612 Return a new allocated string.
613 ********************************************************************/
615 smb_ucs2_t *unix_clean_path(const smb_ucs2_t *s)
617 smb_ucs2_t *ns;
618 smb_ucs2_t *p, *r, *t;
620 DEBUG(3, ("unix_clean_path\n")); /* [%unicode]\n")); */
621 if(!s)
622 return NULL;
624 /* convert '\' to '/' */
625 ns = strdup_w(s);
626 if (!ns)
627 return NULL;
628 unix_format_w(ns);
630 /* remove all double slashes */
631 p = ns;
632 ns = all_string_sub_wa(p, "//", "/");
633 SAFE_FREE(p);
634 if (!ns)
635 return NULL;
637 /* remove any /./ */
638 p = ns;
639 ns = all_string_sub_wa(p, "/./", "/");
640 SAFE_FREE(p);
641 if (!ns)
642 return NULL;
644 /* reduce any /../ */
645 t = ns;
646 while (*t && (r = strstr_wa(t, "/.."))) {
647 t = &(r[3]);
648 if (*t == UCS2_CHAR('/') || *t == 0) {
649 *r = 0;
650 p = strrchr_w(ns, UCS2_CHAR('/'));
651 if (!p)
652 p = ns;
653 if (*t == 0)
654 *p = 0;
655 else
656 memmove(p, t, (strlen_w(t) + 1) * sizeof(smb_ucs2_t));
657 t = p;
661 /* remove any leading ./ trailing /. */
662 trim_string_wa(ns, "./", "/.");
664 /* remove any leading and trailing / */
665 trim_string_wa(ns, "/", "/");
667 return ns;
670 /****************************************************************************
671 Make a dir struct.
672 ****************************************************************************/
674 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
676 char *p;
677 pstring mask2;
679 pstrcpy(mask2,mask);
681 if ((mode & aDIR) != 0)
682 size = 0;
684 memset(buf+1,' ',11);
685 if ((p = strchr_m(mask2,'.')) != NULL) {
686 *p = 0;
687 push_ascii(buf+1,mask2,8, 0);
688 push_ascii(buf+9,p+1,3, 0);
689 *p = '.';
690 } else
691 push_ascii(buf+1,mask2,11, 0);
693 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
694 SCVAL(buf,21,mode);
695 put_dos_date(buf,22,date);
696 SSVAL(buf,26,size & 0xFFFF);
697 SSVAL(buf,28,(size >> 16)&0xFFFF);
698 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
699 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
702 /*******************************************************************
703 Close the low 3 fd's and open dev/null in their place.
704 ********************************************************************/
706 void close_low_fds(BOOL stderr_too)
708 #ifndef VALGRIND
709 int fd;
710 int i;
712 close(0);
713 close(1);
715 if (stderr_too)
716 close(2);
718 /* try and use up these file descriptors, so silly
719 library routines writing to stdout etc won't cause havoc */
720 for (i=0;i<3;i++) {
721 if (i == 2 && !stderr_too)
722 continue;
724 fd = sys_open("/dev/null",O_RDWR,0);
725 if (fd < 0)
726 fd = sys_open("/dev/null",O_WRONLY,0);
727 if (fd < 0) {
728 DEBUG(0,("Can't open /dev/null\n"));
729 return;
731 if (fd != i) {
732 DEBUG(0,("Didn't get file descriptor %d\n",i));
733 return;
736 #endif
739 /****************************************************************************
740 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
741 else
742 if SYSV use O_NDELAY
743 if BSD use FNDELAY
744 ****************************************************************************/
746 int set_blocking(int fd, BOOL set)
748 int val;
749 #ifdef O_NONBLOCK
750 #define FLAG_TO_SET O_NONBLOCK
751 #else
752 #ifdef SYSV
753 #define FLAG_TO_SET O_NDELAY
754 #else /* BSD */
755 #define FLAG_TO_SET FNDELAY
756 #endif
757 #endif
759 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
760 return -1;
761 if(set) /* Turn blocking on - ie. clear nonblock flag */
762 val &= ~FLAG_TO_SET;
763 else
764 val |= FLAG_TO_SET;
765 return sys_fcntl_long( fd, F_SETFL, val);
766 #undef FLAG_TO_SET
769 /****************************************************************************
770 Transfer some data between two fd's.
771 ****************************************************************************/
773 #ifndef TRANSFER_BUF_SIZE
774 #define TRANSFER_BUF_SIZE 65536
775 #endif
777 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
778 ssize_t (*write_fn)(int, const void *, size_t))
780 char *buf;
781 size_t total = 0;
782 ssize_t read_ret;
783 ssize_t write_ret;
784 size_t num_to_read_thistime;
785 size_t num_written = 0;
787 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
788 return -1;
790 while (total < n) {
791 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
793 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
794 if (read_ret == -1) {
795 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
796 SAFE_FREE(buf);
797 return -1;
799 if (read_ret == 0)
800 break;
802 num_written = 0;
804 while (num_written < read_ret) {
805 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
807 if (write_ret == -1) {
808 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
809 SAFE_FREE(buf);
810 return -1;
812 if (write_ret == 0)
813 return (ssize_t)total;
815 num_written += (size_t)write_ret;
818 total += (size_t)read_ret;
821 SAFE_FREE(buf);
822 return (ssize_t)total;
825 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
827 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
830 /*******************************************************************
831 Sleep for a specified number of milliseconds.
832 ********************************************************************/
834 void msleep(unsigned int t)
836 unsigned int tdiff=0;
837 struct timeval tval,t1,t2;
838 fd_set fds;
840 GetTimeOfDay(&t1);
841 GetTimeOfDay(&t2);
843 while (tdiff < t) {
844 tval.tv_sec = (t-tdiff)/1000;
845 tval.tv_usec = 1000*((t-tdiff)%1000);
847 /* Never wait for more than 1 sec. */
848 if (tval.tv_sec > 1) {
849 tval.tv_sec = 1;
850 tval.tv_usec = 0;
853 FD_ZERO(&fds);
854 errno = 0;
855 sys_select_intr(0,&fds,NULL,NULL,&tval);
857 GetTimeOfDay(&t2);
858 if (t2.tv_sec < t1.tv_sec) {
859 /* Someone adjusted time... */
860 t1 = t2;
863 tdiff = TvalDiff(&t1,&t2);
867 /****************************************************************************
868 Become a daemon, discarding the controlling terminal.
869 ****************************************************************************/
871 void become_daemon(BOOL Fork)
873 if (Fork) {
874 if (sys_fork()) {
875 _exit(0);
879 /* detach from the terminal */
880 #ifdef HAVE_SETSID
881 setsid();
882 #elif defined(TIOCNOTTY)
884 int i = sys_open("/dev/tty", O_RDWR, 0);
885 if (i != -1) {
886 ioctl(i, (int) TIOCNOTTY, (char *)0);
887 close(i);
890 #endif /* HAVE_SETSID */
892 /* Close fd's 0,1,2. Needed if started by rsh */
893 close_low_fds(False); /* Don't close stderr, let the debug system
894 attach it to the logfile */
897 /****************************************************************************
898 Put up a yes/no prompt.
899 ****************************************************************************/
901 BOOL yesno(char *p)
903 pstring ans;
904 printf("%s",p);
906 if (!fgets(ans,sizeof(ans)-1,stdin))
907 return(False);
909 if (*ans == 'y' || *ans == 'Y')
910 return(True);
912 return(False);
915 /****************************************************************************
916 Expand a pointer to be a particular size.
917 ****************************************************************************/
919 void *Realloc(void *p,size_t size)
921 void *ret=NULL;
923 if (size == 0) {
924 SAFE_FREE(p);
925 DEBUG(5,("Realloc asked for 0 bytes\n"));
926 return NULL;
929 if (!p)
930 ret = (void *)malloc(size);
931 else
932 ret = (void *)realloc(p,size);
934 if (!ret)
935 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
937 return(ret);
940 void *Realloc_zero(void *ptr, size_t size)
942 void *tptr = NULL;
944 tptr = Realloc(ptr, size);
945 if(tptr == NULL)
946 return NULL;
948 memset((char *)tptr,'\0',size);
950 return tptr;
953 /****************************************************************************
954 Free memory, checks for NULL.
955 Use directly SAFE_FREE()
956 Exists only because we need to pass a function pointer somewhere --SSS
957 ****************************************************************************/
959 void safe_free(void *p)
961 SAFE_FREE(p);
964 /****************************************************************************
965 Get my own name and IP.
966 ****************************************************************************/
968 BOOL get_myname(char *my_name)
970 pstring hostname;
972 *hostname = 0;
974 /* get my host name */
975 if (gethostname(hostname, sizeof(hostname)) == -1) {
976 DEBUG(0,("gethostname failed\n"));
977 return False;
980 /* Ensure null termination. */
981 hostname[sizeof(hostname)-1] = '\0';
983 if (my_name) {
984 /* split off any parts after an initial . */
985 char *p = strchr_m(hostname,'.');
987 if (p)
988 *p = 0;
990 fstrcpy(my_name,hostname);
993 return(True);
996 /****************************************************************************
997 Get my own name, including domain.
998 ****************************************************************************/
1000 BOOL get_myfullname(char *my_name)
1002 pstring hostname;
1004 *hostname = 0;
1006 /* get my host name */
1007 if (gethostname(hostname, sizeof(hostname)) == -1) {
1008 DEBUG(0,("gethostname failed\n"));
1009 return False;
1012 /* Ensure null termination. */
1013 hostname[sizeof(hostname)-1] = '\0';
1015 if (my_name)
1016 fstrcpy(my_name, hostname);
1017 return True;
1020 /****************************************************************************
1021 Get my own domain name.
1022 ****************************************************************************/
1024 BOOL get_mydomname(fstring my_domname)
1026 pstring hostname;
1027 char *p;
1028 struct hostent *hp;
1030 *hostname = 0;
1031 /* get my host name */
1032 if (gethostname(hostname, sizeof(hostname)) == -1) {
1033 DEBUG(0,("gethostname failed\n"));
1034 return False;
1037 /* Ensure null termination. */
1038 hostname[sizeof(hostname)-1] = '\0';
1041 p = strchr_m(hostname, '.');
1043 if (p) {
1044 p++;
1046 if (my_domname)
1047 fstrcpy(my_domname, p);
1050 if (!(hp = sys_gethostbyname(hostname))) {
1051 return False;
1054 p = strchr_m(hp->h_name, '.');
1056 if (p) {
1057 p++;
1059 if (my_domname)
1060 fstrcpy(my_domname, p);
1061 return True;
1064 return False;
1067 /****************************************************************************
1068 Interpret a protocol description string, with a default.
1069 ****************************************************************************/
1071 int interpret_protocol(const char *str,int def)
1073 if (strequal(str,"NT1"))
1074 return(PROTOCOL_NT1);
1075 if (strequal(str,"LANMAN2"))
1076 return(PROTOCOL_LANMAN2);
1077 if (strequal(str,"LANMAN1"))
1078 return(PROTOCOL_LANMAN1);
1079 if (strequal(str,"CORE"))
1080 return(PROTOCOL_CORE);
1081 if (strequal(str,"COREPLUS"))
1082 return(PROTOCOL_COREPLUS);
1083 if (strequal(str,"CORE+"))
1084 return(PROTOCOL_COREPLUS);
1086 DEBUG(0,("Unrecognised protocol level %s\n",str));
1088 return(def);
1091 /****************************************************************************
1092 Return true if a string could be a pure IP address.
1093 ****************************************************************************/
1095 BOOL is_ipaddress(const char *str)
1097 BOOL pure_address = True;
1098 int i;
1100 for (i=0; pure_address && str[i]; i++)
1101 if (!(isdigit((int)str[i]) || str[i] == '.'))
1102 pure_address = False;
1104 /* Check that a pure number is not misinterpreted as an IP */
1105 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1107 return pure_address;
1110 /****************************************************************************
1111 Interpret an internet address or name into an IP address in 4 byte form.
1112 ****************************************************************************/
1114 uint32 interpret_addr(const char *str)
1116 struct hostent *hp;
1117 uint32 res;
1119 if (strcmp(str,"0.0.0.0") == 0)
1120 return(0);
1121 if (strcmp(str,"255.255.255.255") == 0)
1122 return(0xFFFFFFFF);
1124 /* if it's in the form of an IP address then get the lib to interpret it */
1125 if (is_ipaddress(str)) {
1126 res = inet_addr(str);
1127 } else {
1128 /* otherwise assume it's a network name of some sort and use
1129 sys_gethostbyname */
1130 if ((hp = sys_gethostbyname(str)) == 0) {
1131 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1132 return 0;
1135 if(hp->h_addr == NULL) {
1136 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1137 return 0;
1139 putip((char *)&res,(char *)hp->h_addr);
1142 if (res == (uint32)-1)
1143 return(0);
1145 return(res);
1148 /*******************************************************************
1149 A convenient addition to interpret_addr().
1150 ******************************************************************/
1152 struct in_addr *interpret_addr2(const char *str)
1154 static struct in_addr ret;
1155 uint32 a = interpret_addr(str);
1156 ret.s_addr = a;
1157 return(&ret);
1160 /*******************************************************************
1161 Check if an IP is the 0.0.0.0.
1162 ******************************************************************/
1164 BOOL is_zero_ip(struct in_addr ip)
1166 uint32 a;
1167 putip((char *)&a,(char *)&ip);
1168 return(a == 0);
1171 /*******************************************************************
1172 Set an IP to 0.0.0.0.
1173 ******************************************************************/
1175 void zero_ip(struct in_addr *ip)
1177 static BOOL init;
1178 static struct in_addr ipzero;
1180 if (!init) {
1181 ipzero = *interpret_addr2("0.0.0.0");
1182 init = True;
1185 *ip = ipzero;
1188 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1189 /******************************************************************
1190 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1191 Based on a fix from <Thomas.Hepper@icem.de>.
1192 *******************************************************************/
1194 static void strip_mount_options( pstring *str)
1196 if (**str == '-') {
1197 char *p = *str;
1198 while(*p && !isspace(*p))
1199 p++;
1200 while(*p && isspace(*p))
1201 p++;
1202 if(*p) {
1203 pstring tmp_str;
1205 pstrcpy(tmp_str, p);
1206 pstrcpy(*str, tmp_str);
1211 /*******************************************************************
1212 Patch from jkf@soton.ac.uk
1213 Split Luke's automount_server into YP lookup and string splitter
1214 so can easily implement automount_path().
1215 As we may end up doing both, cache the last YP result.
1216 *******************************************************************/
1218 #ifdef WITH_NISPLUS_HOME
1219 char *automount_lookup(const char *user_name)
1221 static fstring last_key = "";
1222 static pstring last_value = "";
1224 char *nis_map = (char *)lp_nis_home_map_name();
1226 char buffer[NIS_MAXATTRVAL + 1];
1227 nis_result *result;
1228 nis_object *object;
1229 entry_obj *entry;
1231 if (strcmp(user_name, last_key)) {
1232 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1233 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1235 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1236 if (result->status != NIS_SUCCESS) {
1237 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1238 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1239 } else {
1240 object = result->objects.objects_val;
1241 if (object->zo_data.zo_type == ENTRY_OBJ) {
1242 entry = &object->zo_data.objdata_u.en_data;
1243 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1244 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1246 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1247 pstring_sub(last_value, "&", user_name);
1248 fstrcpy(last_key, user_name);
1252 nis_freeresult(result);
1255 strip_mount_options(&last_value);
1257 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1258 return last_value;
1260 #else /* WITH_NISPLUS_HOME */
1262 char *automount_lookup(const char *user_name)
1264 static fstring last_key = "";
1265 static pstring last_value = "";
1267 int nis_error; /* returned by yp all functions */
1268 char *nis_result; /* yp_match inits this */
1269 int nis_result_len; /* and set this */
1270 char *nis_domain; /* yp_get_default_domain inits this */
1271 char *nis_map = (char *)lp_nis_home_map_name();
1273 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1274 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1275 return last_value;
1278 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1280 if (!strcmp(user_name, last_key)) {
1281 nis_result = last_value;
1282 nis_result_len = strlen(last_value);
1283 nis_error = 0;
1284 } else {
1285 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1286 &nis_result, &nis_result_len)) == 0) {
1287 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1288 nis_result_len = sizeof(pstring)-1;
1290 fstrcpy(last_key, user_name);
1291 strncpy(last_value, nis_result, nis_result_len);
1292 last_value[nis_result_len] = '\0';
1293 strip_mount_options(&last_value);
1295 } else if(nis_error == YPERR_KEY) {
1297 /* If Key lookup fails user home server is not in nis_map
1298 use default information for server, and home directory */
1299 last_value[0] = 0;
1300 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1301 user_name, nis_map));
1302 DEBUG(3, ("using defaults for server and home directory\n"));
1303 } else {
1304 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1305 yperr_string(nis_error), user_name, nis_map));
1309 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1310 return last_value;
1312 #endif /* WITH_NISPLUS_HOME */
1313 #endif
1315 /*******************************************************************
1316 Are two IPs on the same subnet?
1317 ********************************************************************/
1319 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1321 uint32 net1,net2,nmask;
1323 nmask = ntohl(mask.s_addr);
1324 net1 = ntohl(ip1.s_addr);
1325 net2 = ntohl(ip2.s_addr);
1327 return((net1 & nmask) == (net2 & nmask));
1331 /****************************************************************************
1332 Check if a process exists. Does this work on all unixes?
1333 ****************************************************************************/
1335 BOOL process_exists(pid_t pid)
1337 /* Doing kill with a non-positive pid causes messages to be
1338 * sent to places we don't want. */
1339 SMB_ASSERT(pid > 0);
1340 return(kill(pid,0) == 0 || errno != ESRCH);
1343 /*******************************************************************
1344 Convert a uid into a user name.
1345 ********************************************************************/
1347 const char *uidtoname(uid_t uid)
1349 static fstring name;
1350 struct passwd *pass;
1352 pass = getpwuid_alloc(uid);
1353 if (pass) {
1354 fstrcpy(name, pass->pw_name);
1355 passwd_free(&pass);
1356 } else {
1357 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1359 return name;
1363 /*******************************************************************
1364 Convert a gid into a group name.
1365 ********************************************************************/
1367 char *gidtoname(gid_t gid)
1369 static fstring name;
1370 struct group *grp;
1372 grp = getgrgid(gid);
1373 if (grp)
1374 return(grp->gr_name);
1375 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1376 return(name);
1379 /*******************************************************************
1380 Convert a user name into a uid.
1381 ********************************************************************/
1383 uid_t nametouid(const char *name)
1385 struct passwd *pass;
1386 char *p;
1387 uid_t u;
1389 pass = getpwnam_alloc(name);
1390 if (pass) {
1391 u = pass->pw_uid;
1392 passwd_free(&pass);
1393 return u;
1396 u = (uid_t)strtol(name, &p, 0);
1397 if ((p != name) && (*p == '\0'))
1398 return u;
1400 return (uid_t)-1;
1403 /*******************************************************************
1404 Convert a name to a gid_t if possible. Return -1 if not a group.
1405 ********************************************************************/
1407 gid_t nametogid(const char *name)
1409 struct group *grp;
1410 char *p;
1411 gid_t g;
1413 g = (gid_t)strtol(name, &p, 0);
1414 if ((p != name) && (*p == '\0'))
1415 return g;
1417 grp = sys_getgrnam(name);
1418 if (grp)
1419 return(grp->gr_gid);
1420 return (gid_t)-1;
1423 /*******************************************************************
1424 Something really nasty happened - panic !
1425 ********************************************************************/
1427 void smb_panic(const char *why)
1429 char *cmd;
1430 int result;
1431 #ifdef HAVE_BACKTRACE_SYMBOLS
1432 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1433 size_t backtrace_size;
1434 char **backtrace_strings;
1435 #endif
1437 #ifdef DEVELOPER
1439 extern char *global_clobber_region_function;
1440 extern unsigned int global_clobber_region_line;
1442 if (global_clobber_region_function) {
1443 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1444 global_clobber_region_function,
1445 global_clobber_region_line));
1448 #endif
1450 cmd = lp_panic_action();
1451 if (cmd && *cmd) {
1452 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1453 result = system(cmd);
1455 if (result == -1)
1456 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1457 strerror(errno)));
1458 else
1459 DEBUG(0, ("smb_panic(): action returned status %d\n",
1460 WEXITSTATUS(result)));
1462 DEBUG(0,("PANIC: %s\n", why));
1464 #ifdef HAVE_BACKTRACE_SYMBOLS
1465 /* get the backtrace (stack frames) */
1466 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1467 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1469 DEBUG(0, ("BACKTRACE: %d stack frames:\n", backtrace_size));
1471 if (backtrace_strings) {
1472 int i;
1474 for (i = 0; i < backtrace_size; i++)
1475 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1477 SAFE_FREE(backtrace_strings);
1480 #endif
1482 dbgflush();
1483 abort();
1486 /*******************************************************************
1487 A readdir wrapper which just returns the file name.
1488 ********************************************************************/
1490 const char *readdirname(DIR *p)
1492 SMB_STRUCT_DIRENT *ptr;
1493 char *dname;
1495 if (!p)
1496 return(NULL);
1498 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1499 if (!ptr)
1500 return(NULL);
1502 dname = ptr->d_name;
1504 #ifdef NEXT2
1505 if (telldir(p) < 0)
1506 return(NULL);
1507 #endif
1509 #ifdef HAVE_BROKEN_READDIR
1510 /* using /usr/ucb/cc is BAD */
1511 dname = dname - 2;
1512 #endif
1515 static pstring buf;
1516 int len = NAMLEN(ptr);
1517 memcpy(buf, dname, len);
1518 buf[len] = 0;
1519 dname = buf;
1522 return(dname);
1525 /*******************************************************************
1526 Utility function used to decide if the last component
1527 of a path matches a (possibly wildcarded) entry in a namelist.
1528 ********************************************************************/
1530 BOOL is_in_path(const char *name, name_compare_entry *namelist)
1532 pstring last_component;
1533 char *p;
1535 DEBUG(8, ("is_in_path: %s\n", name));
1537 /* if we have no list it's obviously not in the path */
1538 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1539 DEBUG(8,("is_in_path: no name list.\n"));
1540 return False;
1543 /* Get the last component of the unix name. */
1544 p = strrchr_m(name, '/');
1545 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1546 last_component[sizeof(last_component)-1] = '\0';
1548 for(; namelist->name != NULL; namelist++) {
1549 if(namelist->is_wild) {
1550 if (mask_match(last_component, namelist->name, case_sensitive)) {
1551 DEBUG(8,("is_in_path: mask match succeeded\n"));
1552 return True;
1554 } else {
1555 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1556 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1557 DEBUG(8,("is_in_path: match succeeded\n"));
1558 return True;
1562 DEBUG(8,("is_in_path: match not found\n"));
1564 return False;
1567 /*******************************************************************
1568 Strip a '/' separated list into an array of
1569 name_compare_enties structures suitable for
1570 passing to is_in_path(). We do this for
1571 speed so we can pre-parse all the names in the list
1572 and don't do it for each call to is_in_path().
1573 namelist is modified here and is assumed to be
1574 a copy owned by the caller.
1575 We also check if the entry contains a wildcard to
1576 remove a potentially expensive call to mask_match
1577 if possible.
1578 ********************************************************************/
1580 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1582 char *name_end;
1583 char *nameptr = namelist;
1584 int num_entries = 0;
1585 int i;
1587 (*ppname_array) = NULL;
1589 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1590 return;
1592 /* We need to make two passes over the string. The
1593 first to count the number of elements, the second
1594 to split it.
1597 while(*nameptr) {
1598 if ( *nameptr == '/' ) {
1599 /* cope with multiple (useless) /s) */
1600 nameptr++;
1601 continue;
1603 /* find the next / */
1604 name_end = strchr_m(nameptr, '/');
1606 /* oops - the last check for a / didn't find one. */
1607 if (name_end == NULL)
1608 break;
1610 /* next segment please */
1611 nameptr = name_end + 1;
1612 num_entries++;
1615 if(num_entries == 0)
1616 return;
1618 if(( (*ppname_array) = (name_compare_entry *)malloc(
1619 (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1620 DEBUG(0,("set_namearray: malloc fail\n"));
1621 return;
1624 /* Now copy out the names */
1625 nameptr = namelist;
1626 i = 0;
1627 while(*nameptr) {
1628 if ( *nameptr == '/' ) {
1629 /* cope with multiple (useless) /s) */
1630 nameptr++;
1631 continue;
1633 /* find the next / */
1634 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1635 *name_end = 0;
1637 /* oops - the last check for a / didn't find one. */
1638 if(name_end == NULL)
1639 break;
1641 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1642 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1643 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1644 return;
1647 /* next segment please */
1648 nameptr = name_end + 1;
1649 i++;
1652 (*ppname_array)[i].name = NULL;
1654 return;
1657 /****************************************************************************
1658 Routine to free a namearray.
1659 ****************************************************************************/
1661 void free_namearray(name_compare_entry *name_array)
1663 int i;
1665 if(name_array == NULL)
1666 return;
1668 for(i=0; name_array[i].name!=NULL; i++)
1669 SAFE_FREE(name_array[i].name);
1670 SAFE_FREE(name_array);
1673 /****************************************************************************
1674 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1675 is dealt with in posix.c
1676 ****************************************************************************/
1678 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1680 SMB_STRUCT_FLOCK lock;
1681 int ret;
1683 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1685 lock.l_type = type;
1686 lock.l_whence = SEEK_SET;
1687 lock.l_start = offset;
1688 lock.l_len = count;
1689 lock.l_pid = 0;
1691 ret = sys_fcntl_ptr(fd,op,&lock);
1693 if (ret == -1 && errno != 0)
1694 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1696 /* a lock query */
1697 if (op == SMB_F_GETLK) {
1698 if ((ret != -1) &&
1699 (lock.l_type != F_UNLCK) &&
1700 (lock.l_pid != 0) &&
1701 (lock.l_pid != sys_getpid())) {
1702 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1703 return(True);
1706 /* it must be not locked or locked by me */
1707 return(False);
1710 /* a lock set or unset */
1711 if (ret == -1) {
1712 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1713 (double)offset,(double)count,op,type,strerror(errno)));
1714 return(False);
1717 /* everything went OK */
1718 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1720 return(True);
1723 /*******************************************************************
1724 Is the name specified one of my netbios names.
1725 Returns true if it is equal, false otherwise.
1726 ********************************************************************/
1728 BOOL is_myname(const char *s)
1730 int n;
1731 BOOL ret = False;
1733 for (n=0; my_netbios_names(n); n++) {
1734 if (strequal(my_netbios_names(n), s)) {
1735 ret=True;
1736 break;
1739 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1740 return(ret);
1743 /********************************************************************
1744 Return only the first IP address of our configured interfaces
1745 as a string
1746 *******************************************************************/
1748 const char* get_my_primary_ip (void)
1750 static fstring ip_string;
1751 int n;
1752 struct iface_struct nics[MAX_INTERFACES];
1754 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1755 return NULL;
1757 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1758 return ip_string;
1761 BOOL is_myname_or_ipaddr(const char *s)
1763 /* optimize for the common case */
1764 if (strequal(s, global_myname()))
1765 return True;
1767 /* maybe its an IP address? */
1768 if (is_ipaddress(s)) {
1769 struct iface_struct nics[MAX_INTERFACES];
1770 int i, n;
1771 uint32 ip;
1773 ip = interpret_addr(s);
1774 if ((ip==0) || (ip==0xffffffff))
1775 return False;
1777 n = get_interfaces(nics, MAX_INTERFACES);
1778 for (i=0; i<n; i++) {
1779 if (ip == nics[i].ip.s_addr)
1780 return True;
1784 /* check for an alias */
1785 if (is_myname(s))
1786 return True;
1788 /* no match */
1789 return False;
1792 /*******************************************************************
1793 Is the name specified our workgroup/domain.
1794 Returns true if it is equal, false otherwise.
1795 ********************************************************************/
1797 BOOL is_myworkgroup(const char *s)
1799 BOOL ret = False;
1801 if (strequal(s, lp_workgroup())) {
1802 ret=True;
1805 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1806 return(ret);
1809 /*******************************************************************
1810 we distinguish between 2K and XP by the "Native Lan Manager" string
1811 WinXP => "Windows 2002 5.1"
1812 Win2k => "Windows 2000 5.0"
1813 NT4 => "Windows NT 4.0"
1814 Win9x => "Windows 4.0"
1815 ********************************************************************/
1817 void ra_lanman_string( const char *native_lanman )
1819 if ( 0 == strcmp( native_lanman, "Windows 2002 5.1" ) )
1820 set_remote_arch( RA_WINXP );
1821 else if ( 0 == strcmp( native_lanman, "Windows .NET 5.2" ) )
1822 set_remote_arch( RA_WIN2K3 );
1825 /*******************************************************************
1826 Set the horrid remote_arch string based on an enum.
1827 ********************************************************************/
1829 void set_remote_arch(enum remote_arch_types type)
1831 extern fstring remote_arch;
1832 ra_type = type;
1833 switch( type ) {
1834 case RA_WFWG:
1835 fstrcpy(remote_arch, "WfWg");
1836 return;
1837 case RA_OS2:
1838 fstrcpy(remote_arch, "OS2");
1839 return;
1840 case RA_WIN95:
1841 fstrcpy(remote_arch, "Win95");
1842 return;
1843 case RA_WINNT:
1844 fstrcpy(remote_arch, "WinNT");
1845 return;
1846 case RA_WIN2K:
1847 fstrcpy(remote_arch, "Win2K");
1848 return;
1849 case RA_WINXP:
1850 fstrcpy(remote_arch, "WinXP");
1851 return;
1852 case RA_WIN2K3:
1853 fstrcpy(remote_arch, "Win2K3");
1854 return;
1855 case RA_SAMBA:
1856 fstrcpy(remote_arch,"Samba");
1857 return;
1858 default:
1859 ra_type = RA_UNKNOWN;
1860 fstrcpy(remote_arch, "UNKNOWN");
1861 break;
1865 /*******************************************************************
1866 Get the remote_arch type.
1867 ********************************************************************/
1869 enum remote_arch_types get_remote_arch(void)
1871 return ra_type;
1874 void print_asc(int level, const unsigned char *buf,int len)
1876 int i;
1877 for (i=0;i<len;i++)
1878 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1881 void dump_data(int level, const char *buf1,int len)
1883 const unsigned char *buf = (const unsigned char *)buf1;
1884 int i=0;
1885 if (len<=0) return;
1887 if (!DEBUGLVL(level)) return;
1889 DEBUGADD(level,("[%03X] ",i));
1890 for (i=0;i<len;) {
1891 DEBUGADD(level,("%02X ",(int)buf[i]));
1892 i++;
1893 if (i%8 == 0) DEBUGADD(level,(" "));
1894 if (i%16 == 0) {
1895 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1896 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1897 if (i<len) DEBUGADD(level,("[%03X] ",i));
1900 if (i%16) {
1901 int n;
1902 n = 16 - (i%16);
1903 DEBUGADD(level,(" "));
1904 if (n>8) DEBUGADD(level,(" "));
1905 while (n--) DEBUGADD(level,(" "));
1906 n = MIN(8,i%16);
1907 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1908 n = (i%16) - n;
1909 if (n>0) print_asc(level,&buf[i-n],n);
1910 DEBUGADD(level,("\n"));
1914 void dump_data_pw(const char *msg, const uchar * data, size_t len)
1916 #ifdef DEBUG_PASSWORD
1917 DEBUG(11, ("%s", msg));
1918 if (data != NULL && len > 0)
1920 dump_data(11, data, len);
1922 #endif
1925 char *tab_depth(int depth)
1927 static pstring spaces;
1928 memset(spaces, ' ', depth * 4);
1929 spaces[depth * 4] = 0;
1930 return spaces;
1933 /*****************************************************************************
1934 Provide a checksum on a string
1936 Input: s - the null-terminated character string for which the checksum
1937 will be calculated.
1939 Output: The checksum value calculated for s.
1940 *****************************************************************************/
1942 int str_checksum(const char *s)
1944 int res = 0;
1945 int c;
1946 int i=0;
1948 while(*s) {
1949 c = *s;
1950 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1951 s++;
1952 i++;
1954 return(res);
1957 /*****************************************************************
1958 Zero a memory area then free it. Used to catch bugs faster.
1959 *****************************************************************/
1961 void zero_free(void *p, size_t size)
1963 memset(p, 0, size);
1964 SAFE_FREE(p);
1967 /*****************************************************************
1968 Set our open file limit to a requested max and return the limit.
1969 *****************************************************************/
1971 int set_maxfiles(int requested_max)
1973 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1974 struct rlimit rlp;
1975 int saved_current_limit;
1977 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1978 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1979 strerror(errno) ));
1980 /* just guess... */
1981 return requested_max;
1985 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1986 * account for the extra fd we need
1987 * as well as the log files and standard
1988 * handles etc. Save the limit we want to set in case
1989 * we are running on an OS that doesn't support this limit (AIX)
1990 * which always returns RLIM_INFINITY for rlp.rlim_max.
1993 /* Try raising the hard (max) limit to the requested amount. */
1995 #if defined(RLIM_INFINITY)
1996 if (rlp.rlim_max != RLIM_INFINITY) {
1997 int orig_max = rlp.rlim_max;
1999 if ( rlp.rlim_max < requested_max )
2000 rlp.rlim_max = requested_max;
2002 /* This failing is not an error - many systems (Linux) don't
2003 support our default request of 10,000 open files. JRA. */
2005 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2006 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
2007 (int)rlp.rlim_max, strerror(errno) ));
2009 /* Set failed - restore original value from get. */
2010 rlp.rlim_max = orig_max;
2013 #endif
2015 /* Now try setting the soft (current) limit. */
2017 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
2019 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2020 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
2021 (int)rlp.rlim_cur, strerror(errno) ));
2022 /* just guess... */
2023 return saved_current_limit;
2026 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2027 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2028 strerror(errno) ));
2029 /* just guess... */
2030 return saved_current_limit;
2033 #if defined(RLIM_INFINITY)
2034 if(rlp.rlim_cur == RLIM_INFINITY)
2035 return saved_current_limit;
2036 #endif
2038 if((int)rlp.rlim_cur > saved_current_limit)
2039 return saved_current_limit;
2041 return rlp.rlim_cur;
2042 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2044 * No way to know - just guess...
2046 return requested_max;
2047 #endif
2050 /*****************************************************************
2051 Splits out the start of the key (HKLM or HKU) and the rest of the key.
2052 *****************************************************************/
2054 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
2056 pstring tmp;
2058 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
2059 return False;
2061 (*reg_type) = 0;
2063 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2065 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2066 (*reg_type) = HKEY_LOCAL_MACHINE;
2067 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2068 (*reg_type) = HKEY_USERS;
2069 else {
2070 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2071 return False;
2074 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2075 fstrcpy(key_name, tmp);
2076 else
2077 key_name[0] = 0;
2079 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2081 return True;
2084 /*****************************************************************
2085 Possibly replace mkstemp if it is broken.
2086 *****************************************************************/
2088 int smb_mkstemp(char *template)
2090 #if HAVE_SECURE_MKSTEMP
2091 return mkstemp(template);
2092 #else
2093 /* have a reasonable go at emulating it. Hope that
2094 the system mktemp() isn't completly hopeless */
2095 char *p = mktemp(template);
2096 if (!p)
2097 return -1;
2098 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2099 #endif
2102 /*****************************************************************
2103 malloc that aborts with smb_panic on fail or zero size.
2104 *****************************************************************/
2106 void *smb_xmalloc(size_t size)
2108 void *p;
2109 if (size == 0)
2110 smb_panic("smb_xmalloc: called with zero size.\n");
2111 if ((p = malloc(size)) == NULL) {
2112 DEBUG(0, ("smb_xmalloc() failed to allocate %lu bytes\n", (unsigned long)size));
2113 smb_panic("smb_xmalloc: malloc fail.\n");
2115 return p;
2119 Memdup with smb_panic on fail.
2122 void *smb_xmemdup(const void *p, size_t size)
2124 void *p2;
2125 p2 = smb_xmalloc(size);
2126 memcpy(p2, p, size);
2127 return p2;
2131 strdup that aborts on malloc fail.
2134 char *smb_xstrdup(const char *s)
2136 char *s1 = strdup(s);
2137 if (!s1)
2138 smb_panic("smb_xstrdup: malloc fail\n");
2139 return s1;
2143 strndup that aborts on malloc fail.
2146 char *smb_xstrndup(const char *s, size_t n)
2148 char *s1 = strndup(s, n);
2149 if (!s1)
2150 smb_panic("smb_xstrndup: malloc fail\n");
2151 return s1;
2155 vasprintf that aborts on malloc fail
2158 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2160 int n;
2161 va_list ap2;
2163 VA_COPY(ap2, ap);
2165 n = vasprintf(ptr, format, ap2);
2166 if (n == -1 || ! *ptr)
2167 smb_panic("smb_xvasprintf: out of memory");
2168 return n;
2171 /*****************************************************************
2172 Like strdup but for memory.
2173 *****************************************************************/
2175 void *memdup(const void *p, size_t size)
2177 void *p2;
2178 if (size == 0)
2179 return NULL;
2180 p2 = malloc(size);
2181 if (!p2)
2182 return NULL;
2183 memcpy(p2, p, size);
2184 return p2;
2187 /*****************************************************************
2188 Get local hostname and cache result.
2189 *****************************************************************/
2191 char *myhostname(void)
2193 static pstring ret;
2194 if (ret[0] == 0)
2195 get_myname(ret);
2196 return ret;
2199 /*****************************************************************
2200 A useful function for returning a path in the Samba lock directory.
2201 *****************************************************************/
2203 char *lock_path(const char *name)
2205 static pstring fname;
2207 pstrcpy(fname,lp_lockdir());
2208 trim_string(fname,"","/");
2210 if (!directory_exist(fname,NULL))
2211 mkdir(fname,0755);
2213 pstrcat(fname,"/");
2214 pstrcat(fname,name);
2216 return fname;
2219 /*****************************************************************
2220 A useful function for returning a path in the Samba pid directory.
2221 *****************************************************************/
2223 char *pid_path(const char *name)
2225 static pstring fname;
2227 pstrcpy(fname,lp_piddir());
2228 trim_string(fname,"","/");
2230 if (!directory_exist(fname,NULL))
2231 mkdir(fname,0755);
2233 pstrcat(fname,"/");
2234 pstrcat(fname,name);
2236 return fname;
2240 * @brief Returns an absolute path to a file in the Samba lib directory.
2242 * @param name File to find, relative to LIBDIR.
2244 * @retval Pointer to a static #pstring containing the full path.
2247 char *lib_path(const char *name)
2249 static pstring fname;
2250 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2251 return fname;
2255 * @brief Returns the platform specific shared library extension.
2257 * @retval Pointer to a static #fstring containing the extension.
2260 const char *shlib_ext(void)
2262 return dyn_SHLIBEXT;
2265 /*******************************************************************
2266 Given a filename - get its directory name
2267 NB: Returned in static storage. Caveats:
2268 o Not safe in thread environment.
2269 o Caller must not free.
2270 o If caller wishes to preserve, they should copy.
2271 ********************************************************************/
2273 char *parent_dirname(const char *path)
2275 static pstring dirpath;
2276 char *p;
2278 if (!path)
2279 return(NULL);
2281 pstrcpy(dirpath, path);
2282 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2283 if (!p) {
2284 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2285 } else {
2286 if (p == dirpath)
2287 ++p; /* For root "/", leave "/" in place */
2288 *p = '\0';
2290 return dirpath;
2294 /*******************************************************************
2295 Determine if a pattern contains any Microsoft wildcard characters.
2296 *******************************************************************/
2298 BOOL ms_has_wild(char *s)
2300 char c;
2301 while ((c = *s++)) {
2302 switch (c) {
2303 case '*':
2304 case '?':
2305 case '<':
2306 case '>':
2307 case '"':
2308 return True;
2311 return False;
2314 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2316 smb_ucs2_t c;
2317 if (!s) return False;
2318 while ((c = *s++)) {
2319 switch (c) {
2320 case UCS2_CHAR('*'):
2321 case UCS2_CHAR('?'):
2322 case UCS2_CHAR('<'):
2323 case UCS2_CHAR('>'):
2324 case UCS2_CHAR('"'):
2325 return True;
2328 return False;
2331 /*******************************************************************
2332 A wrapper that handles case sensitivity and the special handling
2333 of the ".." name.
2334 *******************************************************************/
2336 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2338 if (strcmp(string,"..") == 0)
2339 string = ".";
2340 if (strcmp(pattern,".") == 0)
2341 return False;
2343 return ms_fnmatch(pattern, string, Protocol, is_case_sensitive) == 0;
2346 /*********************************************************
2347 Recursive routine that is called by unix_wild_match.
2348 *********************************************************/
2350 static BOOL unix_do_match(const char *regexp, const char *str)
2352 const char *p;
2354 for( p = regexp; *p && *str; ) {
2356 switch(*p) {
2357 case '?':
2358 str++;
2359 p++;
2360 break;
2362 case '*':
2365 * Look for a character matching
2366 * the one after the '*'.
2368 p++;
2369 if(!*p)
2370 return True; /* Automatic match */
2371 while(*str) {
2373 while(*str && (*p != *str))
2374 str++;
2377 * Patch from weidel@multichart.de. In the case of the regexp
2378 * '*XX*' we want to ensure there are at least 2 'X' characters
2379 * in the string after the '*' for a match to be made.
2383 int matchcount=0;
2386 * Eat all the characters that match, but count how many there were.
2389 while(*str && (*p == *str)) {
2390 str++;
2391 matchcount++;
2395 * Now check that if the regexp had n identical characters that
2396 * matchcount had at least that many matches.
2399 while ( *(p+1) && (*(p+1) == *p)) {
2400 p++;
2401 matchcount--;
2404 if ( matchcount <= 0 )
2405 return False;
2408 str--; /* We've eaten the match char after the '*' */
2410 if(unix_do_match(p, str))
2411 return True;
2413 if(!*str)
2414 return False;
2415 else
2416 str++;
2418 return False;
2420 default:
2421 if(*str != *p)
2422 return False;
2423 str++;
2424 p++;
2425 break;
2429 if(!*p && !*str)
2430 return True;
2432 if (!*p && str[0] == '.' && str[1] == 0)
2433 return(True);
2435 if (!*str && *p == '?') {
2436 while (*p == '?')
2437 p++;
2438 return(!*p);
2441 if(!*str && (*p == '*' && p[1] == '\0'))
2442 return True;
2444 return False;
2447 /*******************************************************************
2448 Simple case insensitive interface to a UNIX wildcard matcher.
2449 *******************************************************************/
2451 BOOL unix_wild_match(const char *pattern, const char *string)
2453 pstring p2, s2;
2454 char *p;
2456 pstrcpy(p2, pattern);
2457 pstrcpy(s2, string);
2458 strlower_m(p2);
2459 strlower_m(s2);
2461 /* Remove any *? and ** from the pattern as they are meaningless */
2462 for(p = p2; *p; p++)
2463 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2464 pstrcpy( &p[1], &p[2]);
2466 if (strequal(p2,"*"))
2467 return True;
2469 return unix_do_match(p2, s2) == 0;
2473 #ifdef __INSURE__
2475 /*******************************************************************
2476 This routine is a trick to immediately catch errors when debugging
2477 with insure. A xterm with a gdb is popped up when insure catches
2478 a error. It is Linux specific.
2479 ********************************************************************/
2481 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2483 static int (*fn)();
2484 int ret;
2485 char pidstr[10];
2486 /* you can get /usr/bin/backtrace from
2487 http://samba.org/ftp/unpacked/junkcode/backtrace */
2488 pstring cmd = "/usr/bin/backtrace %d";
2490 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2491 pstring_sub(cmd, "%d", pidstr);
2493 if (!fn) {
2494 static void *h;
2495 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2496 fn = dlsym(h, "_Insure_trap_error");
2498 if (!h || h == _Insure_trap_error) {
2499 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2500 fn = dlsym(h, "_Insure_trap_error");
2504 ret = fn(a1, a2, a3, a4, a5, a6);
2506 system(cmd);
2508 return ret;
2510 #endif