r6080: Port some of the non-critical changes from HEAD to 3_0. The main one is the
[Samba.git] / source3 / lib / util.c
blobd945bca5a7353cdc58a63115a2527fcbd01f599b
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 /* Max allowable allococation - 256mb - 0x10000000 */
27 #define MAX_ALLOC_SIZE (1024*1024*256)
29 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
30 #ifdef WITH_NISPLUS_HOME
31 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
33 * The following lines are needed due to buggy include files
34 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
35 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
36 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
37 * an enum in /usr/include/rpcsvc/nis.h.
40 #if defined(GROUP)
41 #undef GROUP
42 #endif
44 #if defined(GROUP_OBJ)
45 #undef GROUP_OBJ
46 #endif
48 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
50 #include <rpcsvc/nis.h>
52 #endif /* WITH_NISPLUS_HOME */
53 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
55 enum protocol_types Protocol = PROTOCOL_COREPLUS;
57 /* a default finfo structure to ensure all fields are sensible */
58 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
60 /* this is used by the chaining code */
61 int chain_size = 0;
63 int trans_num = 0;
65 static enum remote_arch_types ra_type = RA_UNKNOWN;
66 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
68 /***********************************************************************
69 Definitions for all names.
70 ***********************************************************************/
72 static char *smb_myname;
73 static char *smb_myworkgroup;
74 static char *smb_scope;
75 static int smb_num_netbios_names;
76 static char **smb_my_netbios_names;
78 /***********************************************************************
79 Allocate and set myname. Ensure upper case.
80 ***********************************************************************/
82 BOOL set_global_myname(const char *myname)
84 SAFE_FREE(smb_myname);
85 smb_myname = SMB_STRDUP(myname);
86 if (!smb_myname)
87 return False;
88 strupper_m(smb_myname);
89 return True;
92 const char *global_myname(void)
94 return smb_myname;
97 /***********************************************************************
98 Allocate and set myworkgroup. Ensure upper case.
99 ***********************************************************************/
101 BOOL set_global_myworkgroup(const char *myworkgroup)
103 SAFE_FREE(smb_myworkgroup);
104 smb_myworkgroup = SMB_STRDUP(myworkgroup);
105 if (!smb_myworkgroup)
106 return False;
107 strupper_m(smb_myworkgroup);
108 return True;
111 const char *lp_workgroup(void)
113 return smb_myworkgroup;
116 /***********************************************************************
117 Allocate and set scope. Ensure upper case.
118 ***********************************************************************/
120 BOOL set_global_scope(const char *scope)
122 SAFE_FREE(smb_scope);
123 smb_scope = SMB_STRDUP(scope);
124 if (!smb_scope)
125 return False;
126 strupper_m(smb_scope);
127 return True;
130 /*********************************************************************
131 Ensure scope is never null string.
132 *********************************************************************/
134 const char *global_scope(void)
136 if (!smb_scope)
137 set_global_scope("");
138 return smb_scope;
141 static void free_netbios_names_array(void)
143 int i;
145 for (i = 0; i < smb_num_netbios_names; i++)
146 SAFE_FREE(smb_my_netbios_names[i]);
148 SAFE_FREE(smb_my_netbios_names);
149 smb_num_netbios_names = 0;
152 static BOOL allocate_my_netbios_names_array(size_t number)
154 free_netbios_names_array();
156 smb_num_netbios_names = number + 1;
157 smb_my_netbios_names = SMB_MALLOC_ARRAY( char *, smb_num_netbios_names );
159 if (!smb_my_netbios_names)
160 return False;
162 memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
163 return True;
166 static BOOL set_my_netbios_names(const char *name, int i)
168 SAFE_FREE(smb_my_netbios_names[i]);
170 smb_my_netbios_names[i] = SMB_STRDUP(name);
171 if (!smb_my_netbios_names[i])
172 return False;
173 strupper_m(smb_my_netbios_names[i]);
174 return True;
177 const char *my_netbios_names(int i)
179 return smb_my_netbios_names[i];
182 BOOL set_netbios_aliases(const char **str_array)
184 size_t namecount;
186 /* Work out the max number of netbios aliases that we have */
187 for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
190 if ( global_myname() && *global_myname())
191 namecount++;
193 /* Allocate space for the netbios aliases */
194 if (!allocate_my_netbios_names_array(namecount))
195 return False;
197 /* Use the global_myname string first */
198 namecount=0;
199 if ( global_myname() && *global_myname()) {
200 set_my_netbios_names( global_myname(), namecount );
201 namecount++;
204 if (str_array) {
205 size_t i;
206 for ( i = 0; str_array[i] != NULL; i++) {
207 size_t n;
208 BOOL duplicate = False;
210 /* Look for duplicates */
211 for( n=0; n<namecount; n++ ) {
212 if( strequal( str_array[i], my_netbios_names(n) ) ) {
213 duplicate = True;
214 break;
217 if (!duplicate) {
218 if (!set_my_netbios_names(str_array[i], namecount))
219 return False;
220 namecount++;
224 return True;
227 /****************************************************************************
228 Common name initialization code.
229 ****************************************************************************/
231 BOOL init_names(void)
233 extern fstring local_machine;
234 char *p;
235 int n;
237 if (global_myname() == NULL || *global_myname() == '\0') {
238 if (!set_global_myname(myhostname())) {
239 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
240 return False;
244 if (!set_netbios_aliases(lp_netbios_aliases())) {
245 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
246 return False;
249 fstrcpy( local_machine, global_myname() );
250 trim_char( local_machine, ' ', ' ' );
251 p = strchr( local_machine, ' ' );
252 if (p)
253 *p = 0;
254 strlower_m( local_machine );
256 DEBUG( 5, ("Netbios name list:-\n") );
257 for( n=0; my_netbios_names(n); n++ )
258 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
260 return( True );
263 /**************************************************************************n
264 Find a suitable temporary directory. The result should be copied immediately
265 as it may be overwritten by a subsequent call.
266 ****************************************************************************/
268 const char *tmpdir(void)
270 char *p;
271 if ((p = getenv("TMPDIR")))
272 return p;
273 return "/tmp";
276 /****************************************************************************
277 Add a gid to an array of gids if it's not already there.
278 ****************************************************************************/
280 void add_gid_to_array_unique(TALLOC_CTX *mem_ctx, gid_t gid,
281 gid_t **gids, int *num)
283 int i;
285 for (i=0; i<*num; i++) {
286 if ((*gids)[i] == gid)
287 return;
290 if (mem_ctx != NULL)
291 *gids = TALLOC_REALLOC_ARRAY(mem_ctx, *gids, gid_t, *num+1);
292 else
293 *gids = SMB_REALLOC_ARRAY(*gids, gid_t, *num+1);
295 if (*gids == NULL)
296 return;
298 (*gids)[*num] = gid;
299 *num += 1;
302 /****************************************************************************
303 Like atoi but gets the value up to the separator character.
304 ****************************************************************************/
306 static const char *Atoic(const char *p, int *n, const char *c)
308 if (!isdigit((int)*p)) {
309 DEBUG(5, ("Atoic: malformed number\n"));
310 return NULL;
313 (*n) = atoi(p);
315 while ((*p) && isdigit((int)*p))
316 p++;
318 if (strchr_m(c, *p) == NULL) {
319 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
320 return NULL;
323 return p;
326 /*************************************************************************
327 Reads a list of numbers.
328 *************************************************************************/
330 const char *get_numlist(const char *p, uint32 **num, int *count)
332 int val;
334 if (num == NULL || count == NULL)
335 return NULL;
337 (*count) = 0;
338 (*num ) = NULL;
340 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
341 uint32 *tn;
343 tn = SMB_REALLOC_ARRAY((*num), uint32, (*count)+1);
344 if (tn == NULL) {
345 SAFE_FREE(*num);
346 return NULL;
347 } else
348 (*num) = tn;
349 (*num)[(*count)] = val;
350 (*count)++;
351 p++;
354 return p;
357 /*******************************************************************
358 Check if a file exists - call vfs_file_exist for samba files.
359 ********************************************************************/
361 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
363 SMB_STRUCT_STAT st;
364 if (!sbuf)
365 sbuf = &st;
367 if (sys_stat(fname,sbuf) != 0)
368 return(False);
370 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
373 /*******************************************************************
374 Check a files mod time.
375 ********************************************************************/
377 time_t file_modtime(const char *fname)
379 SMB_STRUCT_STAT st;
381 if (sys_stat(fname,&st) != 0)
382 return(0);
384 return(st.st_mtime);
387 /*******************************************************************
388 Check if a directory exists.
389 ********************************************************************/
391 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
393 SMB_STRUCT_STAT st2;
394 BOOL ret;
396 if (!st)
397 st = &st2;
399 if (sys_stat(dname,st) != 0)
400 return(False);
402 ret = S_ISDIR(st->st_mode);
403 if(!ret)
404 errno = ENOTDIR;
405 return ret;
408 /*******************************************************************
409 Returns the size in bytes of the named file.
410 ********************************************************************/
412 SMB_OFF_T get_file_size(char *file_name)
414 SMB_STRUCT_STAT buf;
415 buf.st_size = 0;
416 if(sys_stat(file_name,&buf) != 0)
417 return (SMB_OFF_T)-1;
418 return(buf.st_size);
421 /*******************************************************************
422 Return a string representing an attribute for a file.
423 ********************************************************************/
425 char *attrib_string(uint16 mode)
427 static fstring attrstr;
429 attrstr[0] = 0;
431 if (mode & aVOLID) fstrcat(attrstr,"V");
432 if (mode & aDIR) fstrcat(attrstr,"D");
433 if (mode & aARCH) fstrcat(attrstr,"A");
434 if (mode & aHIDDEN) fstrcat(attrstr,"H");
435 if (mode & aSYSTEM) fstrcat(attrstr,"S");
436 if (mode & aRONLY) fstrcat(attrstr,"R");
438 return(attrstr);
441 /*******************************************************************
442 Show a smb message structure.
443 ********************************************************************/
445 void show_msg(char *buf)
447 int i;
448 int bcc=0;
450 if (!DEBUGLVL(5))
451 return;
453 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
454 smb_len(buf),
455 (int)CVAL(buf,smb_com),
456 (int)CVAL(buf,smb_rcls),
457 (int)CVAL(buf,smb_reh),
458 (int)SVAL(buf,smb_err),
459 (int)CVAL(buf,smb_flg),
460 (int)SVAL(buf,smb_flg2)));
461 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
462 (int)SVAL(buf,smb_tid),
463 (int)SVAL(buf,smb_pid),
464 (int)SVAL(buf,smb_uid),
465 (int)SVAL(buf,smb_mid)));
466 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
468 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
469 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
470 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
472 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
474 DEBUGADD(5,("smb_bcc=%d\n",bcc));
476 if (DEBUGLEVEL < 10)
477 return;
479 if (DEBUGLEVEL < 50)
480 bcc = MIN(bcc, 512);
482 dump_data(10, smb_buf(buf), bcc);
485 /*******************************************************************
486 Set the length and marker of an smb packet.
487 ********************************************************************/
489 void smb_setlen(char *buf,int len)
491 _smb_setlen(buf,len);
493 SCVAL(buf,4,0xFF);
494 SCVAL(buf,5,'S');
495 SCVAL(buf,6,'M');
496 SCVAL(buf,7,'B');
499 /*******************************************************************
500 Setup the word count and byte count for a smb message.
501 ********************************************************************/
503 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
505 if (zero)
506 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
507 SCVAL(buf,smb_wct,num_words);
508 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
509 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
510 return (smb_size + num_words*2 + num_bytes);
513 /*******************************************************************
514 Setup only the byte count for a smb message.
515 ********************************************************************/
517 int set_message_bcc(char *buf,int num_bytes)
519 int num_words = CVAL(buf,smb_wct);
520 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
521 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
522 return (smb_size + num_words*2 + num_bytes);
525 /*******************************************************************
526 Setup only the byte count for a smb message, using the end of the
527 message as a marker.
528 ********************************************************************/
530 int set_message_end(void *outbuf,void *end_ptr)
532 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
535 /*******************************************************************
536 Reduce a file name, removing .. elements.
537 ********************************************************************/
539 void dos_clean_name(char *s)
541 char *p=NULL;
543 DEBUG(3,("dos_clean_name [%s]\n",s));
545 /* remove any double slashes */
546 all_string_sub(s, "\\\\", "\\", 0);
548 while ((p = strstr_m(s,"\\..\\")) != NULL) {
549 pstring s1;
551 *p = 0;
552 pstrcpy(s1,p+3);
554 if ((p=strrchr_m(s,'\\')) != NULL)
555 *p = 0;
556 else
557 *s = 0;
558 pstrcat(s,s1);
561 trim_string(s,NULL,"\\..");
563 all_string_sub(s, "\\.\\", "\\", 0);
566 /*******************************************************************
567 Reduce a file name, removing .. elements.
568 ********************************************************************/
570 void unix_clean_name(char *s)
572 char *p=NULL;
574 DEBUG(3,("unix_clean_name [%s]\n",s));
576 /* remove any double slashes */
577 all_string_sub(s, "//","/", 0);
579 /* Remove leading ./ characters */
580 if(strncmp(s, "./", 2) == 0) {
581 trim_string(s, "./", NULL);
582 if(*s == 0)
583 pstrcpy(s,"./");
586 while ((p = strstr_m(s,"/../")) != NULL) {
587 pstring s1;
589 *p = 0;
590 pstrcpy(s1,p+3);
592 if ((p=strrchr_m(s,'/')) != NULL)
593 *p = 0;
594 else
595 *s = 0;
596 pstrcat(s,s1);
599 trim_string(s,NULL,"/..");
602 /****************************************************************************
603 Make a dir struct.
604 ****************************************************************************/
606 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
608 char *p;
609 pstring mask2;
611 pstrcpy(mask2,mask);
613 if ((mode & aDIR) != 0)
614 size = 0;
616 memset(buf+1,' ',11);
617 if ((p = strchr_m(mask2,'.')) != NULL) {
618 *p = 0;
619 push_ascii(buf+1,mask2,8, 0);
620 push_ascii(buf+9,p+1,3, 0);
621 *p = '.';
622 } else
623 push_ascii(buf+1,mask2,11, 0);
625 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
626 SCVAL(buf,21,mode);
627 put_dos_date(buf,22,date);
628 SSVAL(buf,26,size & 0xFFFF);
629 SSVAL(buf,28,(size >> 16)&0xFFFF);
630 /* We only uppercase if the protocol is downrev.
631 Strange, but verified on W2K3. Needed for OS/2. JRA. */
632 push_ascii(buf+30,fname,12,Protocol < PROTOCOL_NT1 ? STR_UPPER : 0);
633 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
636 /*******************************************************************
637 Close the low 3 fd's and open dev/null in their place.
638 ********************************************************************/
640 void close_low_fds(BOOL stderr_too)
642 #ifndef VALGRIND
643 int fd;
644 int i;
646 close(0);
647 close(1);
649 if (stderr_too)
650 close(2);
652 /* try and use up these file descriptors, so silly
653 library routines writing to stdout etc won't cause havoc */
654 for (i=0;i<3;i++) {
655 if (i == 2 && !stderr_too)
656 continue;
658 fd = sys_open("/dev/null",O_RDWR,0);
659 if (fd < 0)
660 fd = sys_open("/dev/null",O_WRONLY,0);
661 if (fd < 0) {
662 DEBUG(0,("Can't open /dev/null\n"));
663 return;
665 if (fd != i) {
666 DEBUG(0,("Didn't get file descriptor %d\n",i));
667 return;
670 #endif
673 /****************************************************************************
674 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
675 else
676 if SYSV use O_NDELAY
677 if BSD use FNDELAY
678 ****************************************************************************/
680 int set_blocking(int fd, BOOL set)
682 int val;
683 #ifdef O_NONBLOCK
684 #define FLAG_TO_SET O_NONBLOCK
685 #else
686 #ifdef SYSV
687 #define FLAG_TO_SET O_NDELAY
688 #else /* BSD */
689 #define FLAG_TO_SET FNDELAY
690 #endif
691 #endif
693 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
694 return -1;
695 if(set) /* Turn blocking on - ie. clear nonblock flag */
696 val &= ~FLAG_TO_SET;
697 else
698 val |= FLAG_TO_SET;
699 return sys_fcntl_long( fd, F_SETFL, val);
700 #undef FLAG_TO_SET
703 /****************************************************************************
704 Transfer some data between two fd's.
705 ****************************************************************************/
707 #ifndef TRANSFER_BUF_SIZE
708 #define TRANSFER_BUF_SIZE 65536
709 #endif
711 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
712 ssize_t (*write_fn)(int, const void *, size_t))
714 char *buf;
715 size_t total = 0;
716 ssize_t read_ret;
717 ssize_t write_ret;
718 size_t num_to_read_thistime;
719 size_t num_written = 0;
721 if ((buf = SMB_MALLOC(TRANSFER_BUF_SIZE)) == NULL)
722 return -1;
724 while (total < n) {
725 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
727 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
728 if (read_ret == -1) {
729 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
730 SAFE_FREE(buf);
731 return -1;
733 if (read_ret == 0)
734 break;
736 num_written = 0;
738 while (num_written < read_ret) {
739 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
741 if (write_ret == -1) {
742 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
743 SAFE_FREE(buf);
744 return -1;
746 if (write_ret == 0)
747 return (ssize_t)total;
749 num_written += (size_t)write_ret;
752 total += (size_t)read_ret;
755 SAFE_FREE(buf);
756 return (ssize_t)total;
759 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
761 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
764 /*******************************************************************
765 Sleep for a specified number of milliseconds.
766 ********************************************************************/
768 void smb_msleep(unsigned int t)
770 #if defined(HAVE_NANOSLEEP)
771 struct timespec tval;
772 int ret;
774 tval.tv_sec = t/1000;
775 tval.tv_nsec = 1000000*(t%1000);
777 do {
778 errno = 0;
779 ret = nanosleep(&tval, &tval);
780 } while (ret < 0 && errno == EINTR && (tval.tv_sec > 0 || tval.tv_nsec > 0));
781 #else
782 unsigned int tdiff=0;
783 struct timeval tval,t1,t2;
784 fd_set fds;
786 GetTimeOfDay(&t1);
787 t2 = t1;
789 while (tdiff < t) {
790 tval.tv_sec = (t-tdiff)/1000;
791 tval.tv_usec = 1000*((t-tdiff)%1000);
793 /* Never wait for more than 1 sec. */
794 if (tval.tv_sec > 1) {
795 tval.tv_sec = 1;
796 tval.tv_usec = 0;
799 FD_ZERO(&fds);
800 errno = 0;
801 sys_select_intr(0,&fds,NULL,NULL,&tval);
803 GetTimeOfDay(&t2);
804 if (t2.tv_sec < t1.tv_sec) {
805 /* Someone adjusted time... */
806 t1 = t2;
809 tdiff = TvalDiff(&t1,&t2);
811 #endif
814 /****************************************************************************
815 Become a daemon, discarding the controlling terminal.
816 ****************************************************************************/
818 void become_daemon(BOOL Fork)
820 if (Fork) {
821 if (sys_fork()) {
822 _exit(0);
826 /* detach from the terminal */
827 #ifdef HAVE_SETSID
828 setsid();
829 #elif defined(TIOCNOTTY)
831 int i = sys_open("/dev/tty", O_RDWR, 0);
832 if (i != -1) {
833 ioctl(i, (int) TIOCNOTTY, (char *)0);
834 close(i);
837 #endif /* HAVE_SETSID */
839 /* Close fd's 0,1,2. Needed if started by rsh */
840 close_low_fds(False); /* Don't close stderr, let the debug system
841 attach it to the logfile */
844 /****************************************************************************
845 Put up a yes/no prompt.
846 ****************************************************************************/
848 BOOL yesno(char *p)
850 pstring ans;
851 printf("%s",p);
853 if (!fgets(ans,sizeof(ans)-1,stdin))
854 return(False);
856 if (*ans == 'y' || *ans == 'Y')
857 return(True);
859 return(False);
862 #if defined(PARANOID_MALLOC_CHECKER)
864 /****************************************************************************
865 Internal malloc wrapper. Externally visible.
866 ****************************************************************************/
868 void *malloc_(size_t size)
870 #undef malloc
871 return malloc(size);
872 #define malloc(s) __ERROR_DONT_USE_MALLOC_DIRECTLY
875 /****************************************************************************
876 Internal calloc wrapper. Not externally visible.
877 ****************************************************************************/
879 static void *calloc_(size_t count, size_t size)
881 #undef calloc
882 return calloc(count, size);
883 #define calloc(n,s) __ERROR_DONT_USE_CALLOC_DIRECTLY
886 /****************************************************************************
887 Internal realloc wrapper. Not externally visible.
888 ****************************************************************************/
890 static void *realloc_(void *ptr, size_t size)
892 #undef realloc
893 return realloc(ptr, size);
894 #define realloc(p,s) __ERROR_DONT_USE_RELLOC_DIRECTLY
897 #endif /* PARANOID_MALLOC_CHECKER */
899 /****************************************************************************
900 Type-safe malloc.
901 ****************************************************************************/
903 void *malloc_array(size_t el_size, unsigned int count)
905 if (count >= MAX_ALLOC_SIZE/el_size) {
906 return NULL;
909 #if defined(PARANOID_MALLOC_CHECKER)
910 return malloc_(el_size*count);
911 #else
912 return malloc(el_size*count);
913 #endif
916 /****************************************************************************
917 Type-safe calloc.
918 ****************************************************************************/
920 void *calloc_array(size_t size, size_t nmemb)
922 if (nmemb >= MAX_ALLOC_SIZE/size) {
923 return NULL;
925 #if defined(PARANOID_MALLOC_CHECKER)
926 return calloc_(nmemb, size);
927 #else
928 return calloc(nmemb, size);
929 #endif
932 /****************************************************************************
933 Expand a pointer to be a particular size.
934 ****************************************************************************/
936 void *Realloc(void *p,size_t size)
938 void *ret=NULL;
940 if (size == 0) {
941 SAFE_FREE(p);
942 DEBUG(5,("Realloc asked for 0 bytes\n"));
943 return NULL;
946 #if defined(PARANOID_MALLOC_CHECKER)
947 if (!p)
948 ret = (void *)malloc_(size);
949 else
950 ret = (void *)realloc_(p,size);
951 #else
952 if (!p)
953 ret = (void *)malloc(size);
954 else
955 ret = (void *)realloc(p,size);
956 #endif
958 if (!ret)
959 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
961 return(ret);
964 /****************************************************************************
965 Type-safe realloc.
966 ****************************************************************************/
968 void *realloc_array(void *p,size_t el_size, unsigned int count)
970 if (count >= MAX_ALLOC_SIZE/el_size) {
971 return NULL;
973 return Realloc(p,el_size*count);
976 /****************************************************************************
977 Free memory, checks for NULL.
978 Use directly SAFE_FREE()
979 Exists only because we need to pass a function pointer somewhere --SSS
980 ****************************************************************************/
982 void safe_free(void *p)
984 SAFE_FREE(p);
987 /****************************************************************************
988 Get my own name and IP.
989 ****************************************************************************/
991 BOOL get_myname(char *my_name)
993 pstring hostname;
995 *hostname = 0;
997 /* get my host name */
998 if (gethostname(hostname, sizeof(hostname)) == -1) {
999 DEBUG(0,("gethostname failed\n"));
1000 return False;
1003 /* Ensure null termination. */
1004 hostname[sizeof(hostname)-1] = '\0';
1006 if (my_name) {
1007 /* split off any parts after an initial . */
1008 char *p = strchr_m(hostname,'.');
1010 if (p)
1011 *p = 0;
1013 fstrcpy(my_name,hostname);
1016 return(True);
1019 /****************************************************************************
1020 Get my own canonical name, including domain.
1021 ****************************************************************************/
1023 BOOL get_mydnsfullname(fstring my_dnsname)
1025 static fstring dnshostname;
1026 struct hostent *hp;
1028 if (!*dnshostname) {
1029 /* get my host name */
1030 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
1031 *dnshostname = '\0';
1032 DEBUG(0,("gethostname failed\n"));
1033 return False;
1036 /* Ensure null termination. */
1037 dnshostname[sizeof(dnshostname)-1] = '\0';
1039 /* Ensure we get the cannonical name. */
1040 if (!(hp = sys_gethostbyname(dnshostname))) {
1041 *dnshostname = '\0';
1042 return False;
1044 fstrcpy(dnshostname, hp->h_name);
1046 fstrcpy(my_dnsname, dnshostname);
1047 return True;
1050 /****************************************************************************
1051 Get my own domain name.
1052 ****************************************************************************/
1054 BOOL get_mydnsdomname(fstring my_domname)
1056 fstring domname;
1057 char *p;
1059 *my_domname = '\0';
1060 if (!get_mydnsfullname(domname)) {
1061 return False;
1063 p = strchr_m(domname, '.');
1064 if (p) {
1065 p++;
1066 fstrcpy(my_domname, p);
1069 return False;
1072 /****************************************************************************
1073 Interpret a protocol description string, with a default.
1074 ****************************************************************************/
1076 int interpret_protocol(const char *str,int def)
1078 if (strequal(str,"NT1"))
1079 return(PROTOCOL_NT1);
1080 if (strequal(str,"LANMAN2"))
1081 return(PROTOCOL_LANMAN2);
1082 if (strequal(str,"LANMAN1"))
1083 return(PROTOCOL_LANMAN1);
1084 if (strequal(str,"CORE"))
1085 return(PROTOCOL_CORE);
1086 if (strequal(str,"COREPLUS"))
1087 return(PROTOCOL_COREPLUS);
1088 if (strequal(str,"CORE+"))
1089 return(PROTOCOL_COREPLUS);
1091 DEBUG(0,("Unrecognised protocol level %s\n",str));
1093 return(def);
1096 /****************************************************************************
1097 Return true if a string could be a pure IP address.
1098 ****************************************************************************/
1100 BOOL is_ipaddress(const char *str)
1102 BOOL pure_address = True;
1103 int i;
1105 for (i=0; pure_address && str[i]; i++)
1106 if (!(isdigit((int)str[i]) || str[i] == '.'))
1107 pure_address = False;
1109 /* Check that a pure number is not misinterpreted as an IP */
1110 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1112 return pure_address;
1115 /****************************************************************************
1116 Interpret an internet address or name into an IP address in 4 byte form.
1117 ****************************************************************************/
1119 uint32 interpret_addr(const char *str)
1121 struct hostent *hp;
1122 uint32 res;
1124 if (strcmp(str,"0.0.0.0") == 0)
1125 return(0);
1126 if (strcmp(str,"255.255.255.255") == 0)
1127 return(0xFFFFFFFF);
1129 /* if it's in the form of an IP address then get the lib to interpret it */
1130 if (is_ipaddress(str)) {
1131 res = inet_addr(str);
1132 } else {
1133 /* otherwise assume it's a network name of some sort and use
1134 sys_gethostbyname */
1135 if ((hp = sys_gethostbyname(str)) == 0) {
1136 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1137 return 0;
1140 if(hp->h_addr == NULL) {
1141 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1142 return 0;
1144 putip((char *)&res,(char *)hp->h_addr);
1147 if (res == (uint32)-1)
1148 return(0);
1150 return(res);
1153 /*******************************************************************
1154 A convenient addition to interpret_addr().
1155 ******************************************************************/
1157 struct in_addr *interpret_addr2(const char *str)
1159 static struct in_addr ret;
1160 uint32 a = interpret_addr(str);
1161 ret.s_addr = a;
1162 return(&ret);
1165 /*******************************************************************
1166 Check if an IP is the 0.0.0.0.
1167 ******************************************************************/
1169 BOOL is_zero_ip(struct in_addr ip)
1171 uint32 a;
1172 putip((char *)&a,(char *)&ip);
1173 return(a == 0);
1176 /*******************************************************************
1177 Set an IP to 0.0.0.0.
1178 ******************************************************************/
1180 void zero_ip(struct in_addr *ip)
1182 static BOOL init;
1183 static struct in_addr ipzero;
1185 if (!init) {
1186 ipzero = *interpret_addr2("0.0.0.0");
1187 init = True;
1190 *ip = ipzero;
1193 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1194 /******************************************************************
1195 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1196 Based on a fix from <Thomas.Hepper@icem.de>.
1197 *******************************************************************/
1199 static void strip_mount_options( pstring *str)
1201 if (**str == '-') {
1202 char *p = *str;
1203 while(*p && !isspace(*p))
1204 p++;
1205 while(*p && isspace(*p))
1206 p++;
1207 if(*p) {
1208 pstring tmp_str;
1210 pstrcpy(tmp_str, p);
1211 pstrcpy(*str, tmp_str);
1216 /*******************************************************************
1217 Patch from jkf@soton.ac.uk
1218 Split Luke's automount_server into YP lookup and string splitter
1219 so can easily implement automount_path().
1220 As we may end up doing both, cache the last YP result.
1221 *******************************************************************/
1223 #ifdef WITH_NISPLUS_HOME
1224 char *automount_lookup( char *user_name)
1226 static fstring last_key = "";
1227 static pstring last_value = "";
1229 char *nis_map = (char *)lp_nis_home_map_name();
1231 char buffer[NIS_MAXATTRVAL + 1];
1232 nis_result *result;
1233 nis_object *object;
1234 entry_obj *entry;
1236 if (strcmp(user_name, last_key)) {
1237 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1238 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1240 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1241 if (result->status != NIS_SUCCESS) {
1242 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1243 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1244 } else {
1245 object = result->objects.objects_val;
1246 if (object->zo_data.zo_type == ENTRY_OBJ) {
1247 entry = &object->zo_data.objdata_u.en_data;
1248 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1249 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1251 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1252 pstring_sub(last_value, "&", user_name);
1253 fstrcpy(last_key, user_name);
1257 nis_freeresult(result);
1260 strip_mount_options(&last_value);
1262 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1263 return last_value;
1265 #else /* WITH_NISPLUS_HOME */
1267 char *automount_lookup( char *user_name)
1269 static fstring last_key = "";
1270 static pstring last_value = "";
1272 int nis_error; /* returned by yp all functions */
1273 char *nis_result; /* yp_match inits this */
1274 int nis_result_len; /* and set this */
1275 char *nis_domain; /* yp_get_default_domain inits this */
1276 char *nis_map = (char *)lp_nis_home_map_name();
1278 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1279 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1280 return last_value;
1283 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1285 if (!strcmp(user_name, last_key)) {
1286 nis_result = last_value;
1287 nis_result_len = strlen(last_value);
1288 nis_error = 0;
1289 } else {
1290 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1291 &nis_result, &nis_result_len)) == 0) {
1292 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1293 nis_result_len = sizeof(pstring)-1;
1295 fstrcpy(last_key, user_name);
1296 strncpy(last_value, nis_result, nis_result_len);
1297 last_value[nis_result_len] = '\0';
1298 strip_mount_options(&last_value);
1300 } else if(nis_error == YPERR_KEY) {
1302 /* If Key lookup fails user home server is not in nis_map
1303 use default information for server, and home directory */
1304 last_value[0] = 0;
1305 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1306 user_name, nis_map));
1307 DEBUG(3, ("using defaults for server and home directory\n"));
1308 } else {
1309 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1310 yperr_string(nis_error), user_name, nis_map));
1314 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1315 return last_value;
1317 #endif /* WITH_NISPLUS_HOME */
1318 #endif
1320 /*******************************************************************
1321 Are two IPs on the same subnet?
1322 ********************************************************************/
1324 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1326 uint32 net1,net2,nmask;
1328 nmask = ntohl(mask.s_addr);
1329 net1 = ntohl(ip1.s_addr);
1330 net2 = ntohl(ip2.s_addr);
1332 return((net1 & nmask) == (net2 & nmask));
1336 /****************************************************************************
1337 Check if a process exists. Does this work on all unixes?
1338 ****************************************************************************/
1340 BOOL process_exists(pid_t pid)
1342 /* Doing kill with a non-positive pid causes messages to be
1343 * sent to places we don't want. */
1344 SMB_ASSERT(pid > 0);
1345 return(kill(pid,0) == 0 || errno != ESRCH);
1348 /*******************************************************************
1349 Convert a uid into a user name.
1350 ********************************************************************/
1352 const char *uidtoname(uid_t uid)
1354 static fstring name;
1355 struct passwd *pass;
1357 pass = getpwuid_alloc(uid);
1358 if (pass) {
1359 fstrcpy(name, pass->pw_name);
1360 passwd_free(&pass);
1361 } else {
1362 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1364 return name;
1368 /*******************************************************************
1369 Convert a gid into a group name.
1370 ********************************************************************/
1372 char *gidtoname(gid_t gid)
1374 static fstring name;
1375 struct group *grp;
1377 grp = getgrgid(gid);
1378 if (grp)
1379 return(grp->gr_name);
1380 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1381 return(name);
1384 /*******************************************************************
1385 Convert a user name into a uid.
1386 ********************************************************************/
1388 uid_t nametouid(const char *name)
1390 struct passwd *pass;
1391 char *p;
1392 uid_t u;
1394 pass = getpwnam_alloc(name);
1395 if (pass) {
1396 u = pass->pw_uid;
1397 passwd_free(&pass);
1398 return u;
1401 u = (uid_t)strtol(name, &p, 0);
1402 if ((p != name) && (*p == '\0'))
1403 return u;
1405 return (uid_t)-1;
1408 /*******************************************************************
1409 Convert a name to a gid_t if possible. Return -1 if not a group.
1410 ********************************************************************/
1412 gid_t nametogid(const char *name)
1414 struct group *grp;
1415 char *p;
1416 gid_t g;
1418 g = (gid_t)strtol(name, &p, 0);
1419 if ((p != name) && (*p == '\0'))
1420 return g;
1422 grp = sys_getgrnam(name);
1423 if (grp)
1424 return(grp->gr_gid);
1425 return (gid_t)-1;
1428 /*******************************************************************
1429 legacy wrapper for smb_panic2()
1430 ********************************************************************/
1431 void smb_panic( const char *why )
1433 smb_panic2( why, True );
1436 /*******************************************************************
1437 Something really nasty happened - panic !
1438 ********************************************************************/
1440 #ifdef HAVE_LIBEXC_H
1441 #include <libexc.h>
1442 #endif
1444 void smb_panic2(const char *why, BOOL decrement_pid_count )
1446 char *cmd;
1447 int result;
1448 #ifdef HAVE_BACKTRACE_SYMBOLS
1449 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1450 size_t backtrace_size;
1451 char **backtrace_strings;
1452 #endif
1454 #ifdef DEVELOPER
1456 extern char *global_clobber_region_function;
1457 extern unsigned int global_clobber_region_line;
1459 if (global_clobber_region_function) {
1460 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1461 global_clobber_region_function,
1462 global_clobber_region_line));
1465 #endif
1467 /* only smbd needs to decrement the smbd counter in connections.tdb */
1468 if ( decrement_pid_count )
1469 decrement_smbd_process_count();
1471 cmd = lp_panic_action();
1472 if (cmd && *cmd) {
1473 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1474 result = system(cmd);
1476 if (result == -1)
1477 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1478 strerror(errno)));
1479 else
1480 DEBUG(0, ("smb_panic(): action returned status %d\n",
1481 WEXITSTATUS(result)));
1483 DEBUG(0,("PANIC: %s\n", why));
1485 #ifdef HAVE_BACKTRACE_SYMBOLS
1486 /* get the backtrace (stack frames) */
1487 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1488 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1490 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
1491 (unsigned long)backtrace_size));
1493 if (backtrace_strings) {
1494 int i;
1496 for (i = 0; i < backtrace_size; i++)
1497 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1499 /* Leak the backtrace_strings, rather than risk what free() might do */
1502 #elif HAVE_LIBEXC
1504 #define NAMESIZE 32 /* Arbitrary */
1506 /* The IRIX libexc library provides an API for unwinding the stack. See
1507 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
1508 * since we are about to abort anyway, it hardly matters.
1510 * Note that if we paniced due to a SIGSEGV or SIGBUS (or similar) this
1511 * will fail with a nasty message upon failing to open the /proc entry.
1514 __uint64_t addrs[BACKTRACE_STACK_SIZE];
1515 char * names[BACKTRACE_STACK_SIZE];
1516 char namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
1518 int i;
1519 int levels;
1521 ZERO_ARRAY(addrs);
1522 ZERO_ARRAY(names);
1523 ZERO_ARRAY(namebuf);
1525 /* We need to be root so we can open our /proc entry to walk
1526 * our stack. It also helps when we want to dump core.
1528 become_root();
1530 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
1531 names[i] = namebuf + (i * NAMESIZE);
1534 levels = trace_back_stack(0, addrs, names,
1535 BACKTRACE_STACK_SIZE, NAMESIZE);
1537 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
1538 for (i = 0; i < levels; i++) {
1539 DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
1542 #undef NAMESIZE
1543 #endif
1545 dbgflush();
1546 #ifdef SIGABRT
1547 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
1548 #endif
1549 abort();
1552 /*******************************************************************
1553 A readdir wrapper which just returns the file name.
1554 ********************************************************************/
1556 const char *readdirname(DIR *p)
1558 SMB_STRUCT_DIRENT *ptr;
1559 char *dname;
1561 if (!p)
1562 return(NULL);
1564 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1565 if (!ptr)
1566 return(NULL);
1568 dname = ptr->d_name;
1570 #ifdef NEXT2
1571 if (telldir(p) < 0)
1572 return(NULL);
1573 #endif
1575 #ifdef HAVE_BROKEN_READDIR
1576 /* using /usr/ucb/cc is BAD */
1577 dname = dname - 2;
1578 #endif
1581 static pstring buf;
1582 int len = NAMLEN(ptr);
1583 memcpy(buf, dname, len);
1584 buf[len] = 0;
1585 dname = buf;
1588 return(dname);
1591 /*******************************************************************
1592 Utility function used to decide if the last component
1593 of a path matches a (possibly wildcarded) entry in a namelist.
1594 ********************************************************************/
1596 BOOL is_in_path(const char *name, name_compare_entry *namelist, BOOL case_sensitive)
1598 pstring last_component;
1599 char *p;
1601 /* if we have no list it's obviously not in the path */
1602 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1603 return False;
1606 DEBUG(8, ("is_in_path: %s\n", name));
1608 /* Get the last component of the unix name. */
1609 p = strrchr_m(name, '/');
1610 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1611 last_component[sizeof(last_component)-1] = '\0';
1613 for(; namelist->name != NULL; namelist++) {
1614 if(namelist->is_wild) {
1615 if (mask_match(last_component, namelist->name, case_sensitive)) {
1616 DEBUG(8,("is_in_path: mask match succeeded\n"));
1617 return True;
1619 } else {
1620 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1621 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1622 DEBUG(8,("is_in_path: match succeeded\n"));
1623 return True;
1627 DEBUG(8,("is_in_path: match not found\n"));
1629 return False;
1632 /*******************************************************************
1633 Strip a '/' separated list into an array of
1634 name_compare_enties structures suitable for
1635 passing to is_in_path(). We do this for
1636 speed so we can pre-parse all the names in the list
1637 and don't do it for each call to is_in_path().
1638 namelist is modified here and is assumed to be
1639 a copy owned by the caller.
1640 We also check if the entry contains a wildcard to
1641 remove a potentially expensive call to mask_match
1642 if possible.
1643 ********************************************************************/
1645 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1647 char *name_end;
1648 char *nameptr = namelist;
1649 int num_entries = 0;
1650 int i;
1652 (*ppname_array) = NULL;
1654 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1655 return;
1657 /* We need to make two passes over the string. The
1658 first to count the number of elements, the second
1659 to split it.
1662 while(*nameptr) {
1663 if ( *nameptr == '/' ) {
1664 /* cope with multiple (useless) /s) */
1665 nameptr++;
1666 continue;
1668 /* find the next / */
1669 name_end = strchr_m(nameptr, '/');
1671 /* oops - the last check for a / didn't find one. */
1672 if (name_end == NULL)
1673 break;
1675 /* next segment please */
1676 nameptr = name_end + 1;
1677 num_entries++;
1680 if(num_entries == 0)
1681 return;
1683 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
1684 DEBUG(0,("set_namearray: malloc fail\n"));
1685 return;
1688 /* Now copy out the names */
1689 nameptr = namelist;
1690 i = 0;
1691 while(*nameptr) {
1692 if ( *nameptr == '/' ) {
1693 /* cope with multiple (useless) /s) */
1694 nameptr++;
1695 continue;
1697 /* find the next / */
1698 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1699 *name_end = 0;
1701 /* oops - the last check for a / didn't find one. */
1702 if(name_end == NULL)
1703 break;
1705 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1706 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1707 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1708 return;
1711 /* next segment please */
1712 nameptr = name_end + 1;
1713 i++;
1716 (*ppname_array)[i].name = NULL;
1718 return;
1721 /****************************************************************************
1722 Routine to free a namearray.
1723 ****************************************************************************/
1725 void free_namearray(name_compare_entry *name_array)
1727 int i;
1729 if(name_array == NULL)
1730 return;
1732 for(i=0; name_array[i].name!=NULL; i++)
1733 SAFE_FREE(name_array[i].name);
1734 SAFE_FREE(name_array);
1737 /****************************************************************************
1738 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1739 is dealt with in posix.c
1740 ****************************************************************************/
1742 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1744 SMB_STRUCT_FLOCK lock;
1745 int ret;
1747 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1749 lock.l_type = type;
1750 lock.l_whence = SEEK_SET;
1751 lock.l_start = offset;
1752 lock.l_len = count;
1753 lock.l_pid = 0;
1755 ret = sys_fcntl_ptr(fd,op,&lock);
1757 if (ret == -1 && errno != 0)
1758 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1760 /* a lock query */
1761 if (op == SMB_F_GETLK) {
1762 if ((ret != -1) &&
1763 (lock.l_type != F_UNLCK) &&
1764 (lock.l_pid != 0) &&
1765 (lock.l_pid != sys_getpid())) {
1766 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1767 return(True);
1770 /* it must be not locked or locked by me */
1771 return(False);
1774 /* a lock set or unset */
1775 if (ret == -1) {
1776 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1777 (double)offset,(double)count,op,type,strerror(errno)));
1778 return(False);
1781 /* everything went OK */
1782 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1784 return(True);
1787 /*******************************************************************
1788 Is the name specified one of my netbios names.
1789 Returns true if it is equal, false otherwise.
1790 ********************************************************************/
1792 BOOL is_myname(const char *s)
1794 int n;
1795 BOOL ret = False;
1797 for (n=0; my_netbios_names(n); n++) {
1798 if (strequal(my_netbios_names(n), s)) {
1799 ret=True;
1800 break;
1803 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1804 return(ret);
1807 BOOL is_myname_or_ipaddr(const char *s)
1809 fstring name, dnsname;
1810 char *servername;
1812 if ( !s )
1813 return False;
1815 /* santize the string from '\\name' */
1817 fstrcpy( name, s );
1819 servername = strrchr_m( name, '\\' );
1820 if ( !servername )
1821 servername = name;
1822 else
1823 servername++;
1825 /* optimize for the common case */
1827 if (strequal(servername, global_myname()))
1828 return True;
1830 /* check for an alias */
1832 if (is_myname(servername))
1833 return True;
1835 /* check for loopback */
1837 if (strequal(servername, "localhost"))
1838 return True;
1840 /* maybe it's my dns name */
1842 if ( get_mydnsfullname( dnsname ) )
1843 if ( strequal( servername, dnsname ) )
1844 return True;
1846 /* handle possible CNAME records */
1848 if ( !is_ipaddress( servername ) ) {
1849 /* use DNS to resolve the name, but only the first address */
1850 struct hostent *hp;
1852 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1853 struct in_addr return_ip;
1854 putip( (char*)&return_ip, (char*)hp->h_addr );
1855 fstrcpy( name, inet_ntoa( return_ip ) );
1856 servername = name;
1860 /* maybe its an IP address? */
1861 if (is_ipaddress(servername)) {
1862 struct iface_struct nics[MAX_INTERFACES];
1863 int i, n;
1864 uint32 ip;
1866 ip = interpret_addr(servername);
1867 if ((ip==0) || (ip==0xffffffff))
1868 return False;
1870 n = get_interfaces(nics, MAX_INTERFACES);
1871 for (i=0; i<n; i++) {
1872 if (ip == nics[i].ip.s_addr)
1873 return True;
1877 /* no match */
1878 return False;
1881 /*******************************************************************
1882 Is the name specified our workgroup/domain.
1883 Returns true if it is equal, false otherwise.
1884 ********************************************************************/
1886 BOOL is_myworkgroup(const char *s)
1888 BOOL ret = False;
1890 if (strequal(s, lp_workgroup())) {
1891 ret=True;
1894 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1895 return(ret);
1898 /*******************************************************************
1899 we distinguish between 2K and XP by the "Native Lan Manager" string
1900 WinXP => "Windows 2002 5.1"
1901 Win2k => "Windows 2000 5.0"
1902 NT4 => "Windows NT 4.0"
1903 Win9x => "Windows 4.0"
1904 Windows 2003 doesn't set the native lan manager string but
1905 they do set the domain to "Windows 2003 5.2" (probably a bug).
1906 ********************************************************************/
1908 void ra_lanman_string( const char *native_lanman )
1910 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1911 set_remote_arch( RA_WINXP );
1912 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1913 set_remote_arch( RA_WIN2K3 );
1916 /*******************************************************************
1917 Set the horrid remote_arch string based on an enum.
1918 ********************************************************************/
1920 void set_remote_arch(enum remote_arch_types type)
1922 extern fstring remote_arch;
1923 ra_type = type;
1924 switch( type ) {
1925 case RA_WFWG:
1926 fstrcpy(remote_arch, "WfWg");
1927 break;
1928 case RA_OS2:
1929 fstrcpy(remote_arch, "OS2");
1930 break;
1931 case RA_WIN95:
1932 fstrcpy(remote_arch, "Win95");
1933 break;
1934 case RA_WINNT:
1935 fstrcpy(remote_arch, "WinNT");
1936 break;
1937 case RA_WIN2K:
1938 fstrcpy(remote_arch, "Win2K");
1939 break;
1940 case RA_WINXP:
1941 fstrcpy(remote_arch, "WinXP");
1942 break;
1943 case RA_WIN2K3:
1944 fstrcpy(remote_arch, "Win2K3");
1945 break;
1946 case RA_SAMBA:
1947 fstrcpy(remote_arch,"Samba");
1948 break;
1949 case RA_CIFSFS:
1950 fstrcpy(remote_arch,"CIFSFS");
1951 break;
1952 default:
1953 ra_type = RA_UNKNOWN;
1954 fstrcpy(remote_arch, "UNKNOWN");
1955 break;
1958 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
1961 /*******************************************************************
1962 Get the remote_arch type.
1963 ********************************************************************/
1965 enum remote_arch_types get_remote_arch(void)
1967 return ra_type;
1970 void print_asc(int level, const unsigned char *buf,int len)
1972 int i;
1973 for (i=0;i<len;i++)
1974 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1977 void dump_data(int level, const char *buf1,int len)
1979 const unsigned char *buf = (const unsigned char *)buf1;
1980 int i=0;
1981 if (len<=0) return;
1983 if (!DEBUGLVL(level)) return;
1985 DEBUGADD(level,("[%03X] ",i));
1986 for (i=0;i<len;) {
1987 DEBUGADD(level,("%02X ",(int)buf[i]));
1988 i++;
1989 if (i%8 == 0) DEBUGADD(level,(" "));
1990 if (i%16 == 0) {
1991 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1992 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1993 if (i<len) DEBUGADD(level,("[%03X] ",i));
1996 if (i%16) {
1997 int n;
1998 n = 16 - (i%16);
1999 DEBUGADD(level,(" "));
2000 if (n>8) DEBUGADD(level,(" "));
2001 while (n--) DEBUGADD(level,(" "));
2002 n = MIN(8,i%16);
2003 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
2004 n = (i%16) - n;
2005 if (n>0) print_asc(level,&buf[i-n],n);
2006 DEBUGADD(level,("\n"));
2010 void dump_data_pw(const char *msg, const uchar * data, size_t len)
2012 #ifdef DEBUG_PASSWORD
2013 DEBUG(11, ("%s", msg));
2014 if (data != NULL && len > 0)
2016 dump_data(11, data, len);
2018 #endif
2021 char *tab_depth(int depth)
2023 static pstring spaces;
2024 memset(spaces, ' ', depth * 4);
2025 spaces[depth * 4] = 0;
2026 return spaces;
2029 /*****************************************************************************
2030 Provide a checksum on a string
2032 Input: s - the null-terminated character string for which the checksum
2033 will be calculated.
2035 Output: The checksum value calculated for s.
2036 *****************************************************************************/
2038 int str_checksum(const char *s)
2040 int res = 0;
2041 int c;
2042 int i=0;
2044 while(*s) {
2045 c = *s;
2046 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
2047 s++;
2048 i++;
2050 return(res);
2053 /*****************************************************************
2054 Zero a memory area then free it. Used to catch bugs faster.
2055 *****************************************************************/
2057 void zero_free(void *p, size_t size)
2059 memset(p, 0, size);
2060 SAFE_FREE(p);
2063 /*****************************************************************
2064 Set our open file limit to a requested max and return the limit.
2065 *****************************************************************/
2067 int set_maxfiles(int requested_max)
2069 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
2070 struct rlimit rlp;
2071 int saved_current_limit;
2073 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2074 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
2075 strerror(errno) ));
2076 /* just guess... */
2077 return requested_max;
2081 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
2082 * account for the extra fd we need
2083 * as well as the log files and standard
2084 * handles etc. Save the limit we want to set in case
2085 * we are running on an OS that doesn't support this limit (AIX)
2086 * which always returns RLIM_INFINITY for rlp.rlim_max.
2089 /* Try raising the hard (max) limit to the requested amount. */
2091 #if defined(RLIM_INFINITY)
2092 if (rlp.rlim_max != RLIM_INFINITY) {
2093 int orig_max = rlp.rlim_max;
2095 if ( rlp.rlim_max < requested_max )
2096 rlp.rlim_max = requested_max;
2098 /* This failing is not an error - many systems (Linux) don't
2099 support our default request of 10,000 open files. JRA. */
2101 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2102 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
2103 (int)rlp.rlim_max, strerror(errno) ));
2105 /* Set failed - restore original value from get. */
2106 rlp.rlim_max = orig_max;
2109 #endif
2111 /* Now try setting the soft (current) limit. */
2113 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
2115 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2116 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
2117 (int)rlp.rlim_cur, strerror(errno) ));
2118 /* just guess... */
2119 return saved_current_limit;
2122 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2123 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2124 strerror(errno) ));
2125 /* just guess... */
2126 return saved_current_limit;
2129 #if defined(RLIM_INFINITY)
2130 if(rlp.rlim_cur == RLIM_INFINITY)
2131 return saved_current_limit;
2132 #endif
2134 if((int)rlp.rlim_cur > saved_current_limit)
2135 return saved_current_limit;
2137 return rlp.rlim_cur;
2138 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2140 * No way to know - just guess...
2142 return requested_max;
2143 #endif
2146 /*****************************************************************
2147 Splits out the start of the key (HKLM or HKU) and the rest of the key.
2148 *****************************************************************/
2150 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
2152 pstring tmp;
2154 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
2155 return False;
2157 (*reg_type) = 0;
2159 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2161 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2162 (*reg_type) = HKEY_LOCAL_MACHINE;
2163 else if (strequal(tmp, "HKCR") || strequal(tmp, "HKEY_CLASSES_ROOT"))
2164 (*reg_type) = HKEY_CLASSES_ROOT;
2165 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2166 (*reg_type) = HKEY_USERS;
2167 else if (strequal(tmp, "HKPD")||strequal(tmp, "HKEY_PERFORMANCE_DATA"))
2168 (*reg_type) = HKEY_PERFORMANCE_DATA;
2169 else {
2170 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2171 return False;
2174 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2175 fstrcpy(key_name, tmp);
2176 else
2177 key_name[0] = 0;
2179 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2181 return True;
2184 /*****************************************************************
2185 Possibly replace mkstemp if it is broken.
2186 *****************************************************************/
2188 int smb_mkstemp(char *template)
2190 #if HAVE_SECURE_MKSTEMP
2191 return mkstemp(template);
2192 #else
2193 /* have a reasonable go at emulating it. Hope that
2194 the system mktemp() isn't completly hopeless */
2195 char *p = mktemp(template);
2196 if (!p)
2197 return -1;
2198 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2199 #endif
2202 /*****************************************************************
2203 malloc that aborts with smb_panic on fail or zero size.
2204 *****************************************************************/
2206 void *smb_xmalloc_array(size_t size, unsigned int count)
2208 void *p;
2209 if (size == 0)
2210 smb_panic("smb_xmalloc_array: called with zero size.\n");
2211 if (count >= MAX_ALLOC_SIZE/size) {
2212 smb_panic("smb_xmalloc: alloc size too large.\n");
2214 if ((p = SMB_MALLOC(size*count)) == NULL) {
2215 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
2216 (unsigned long)size, (unsigned long)count));
2217 smb_panic("smb_xmalloc_array: malloc fail.\n");
2219 return p;
2223 Memdup with smb_panic on fail.
2226 void *smb_xmemdup(const void *p, size_t size)
2228 void *p2;
2229 p2 = SMB_XMALLOC_ARRAY(unsigned char,size);
2230 memcpy(p2, p, size);
2231 return p2;
2235 strdup that aborts on malloc fail.
2238 char *smb_xstrdup(const char *s)
2240 #if defined(PARANOID_MALLOC_CHECKER)
2241 #ifdef strdup
2242 #undef strdup
2243 #endif
2244 #endif
2245 char *s1 = strdup(s);
2246 #if defined(PARANOID_MALLOC_CHECKER)
2247 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
2248 #endif
2249 if (!s1)
2250 smb_panic("smb_xstrdup: malloc fail\n");
2251 return s1;
2256 strndup that aborts on malloc fail.
2259 char *smb_xstrndup(const char *s, size_t n)
2261 #if defined(PARANOID_MALLOC_CHECKER)
2262 #ifdef strndup
2263 #undef strndup
2264 #endif
2265 #endif
2266 char *s1 = strndup(s, n);
2267 #if defined(PARANOID_MALLOC_CHECKER)
2268 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
2269 #endif
2270 if (!s1)
2271 smb_panic("smb_xstrndup: malloc fail\n");
2272 return s1;
2276 vasprintf that aborts on malloc fail
2279 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2281 int n;
2282 va_list ap2;
2284 VA_COPY(ap2, ap);
2286 n = vasprintf(ptr, format, ap2);
2287 if (n == -1 || ! *ptr)
2288 smb_panic("smb_xvasprintf: out of memory");
2289 return n;
2292 /*****************************************************************
2293 Like strdup but for memory.
2294 *****************************************************************/
2296 void *memdup(const void *p, size_t size)
2298 void *p2;
2299 if (size == 0)
2300 return NULL;
2301 p2 = SMB_MALLOC(size);
2302 if (!p2)
2303 return NULL;
2304 memcpy(p2, p, size);
2305 return p2;
2308 /*****************************************************************
2309 Get local hostname and cache result.
2310 *****************************************************************/
2312 char *myhostname(void)
2314 static pstring ret;
2315 if (ret[0] == 0)
2316 get_myname(ret);
2317 return ret;
2320 /*****************************************************************
2321 A useful function for returning a path in the Samba lock directory.
2322 *****************************************************************/
2324 char *lock_path(const char *name)
2326 static pstring fname;
2328 pstrcpy(fname,lp_lockdir());
2329 trim_char(fname,'\0','/');
2331 if (!directory_exist(fname,NULL))
2332 mkdir(fname,0755);
2334 pstrcat(fname,"/");
2335 pstrcat(fname,name);
2337 return fname;
2340 /*****************************************************************
2341 A useful function for returning a path in the Samba pid directory.
2342 *****************************************************************/
2344 char *pid_path(const char *name)
2346 static pstring fname;
2348 pstrcpy(fname,lp_piddir());
2349 trim_char(fname,'\0','/');
2351 if (!directory_exist(fname,NULL))
2352 mkdir(fname,0755);
2354 pstrcat(fname,"/");
2355 pstrcat(fname,name);
2357 return fname;
2361 * @brief Returns an absolute path to a file in the Samba lib directory.
2363 * @param name File to find, relative to LIBDIR.
2365 * @retval Pointer to a static #pstring containing the full path.
2368 char *lib_path(const char *name)
2370 static pstring fname;
2371 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2372 return fname;
2376 * @brief Returns the platform specific shared library extension.
2378 * @retval Pointer to a static #fstring containing the extension.
2381 const char *shlib_ext(void)
2383 return dyn_SHLIBEXT;
2386 /*******************************************************************
2387 Given a filename - get its directory name
2388 NB: Returned in static storage. Caveats:
2389 o Not safe in thread environment.
2390 o Caller must not free.
2391 o If caller wishes to preserve, they should copy.
2392 ********************************************************************/
2394 char *parent_dirname(const char *path)
2396 static pstring dirpath;
2397 char *p;
2399 if (!path)
2400 return(NULL);
2402 pstrcpy(dirpath, path);
2403 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2404 if (!p) {
2405 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2406 } else {
2407 if (p == dirpath)
2408 ++p; /* For root "/", leave "/" in place */
2409 *p = '\0';
2411 return dirpath;
2415 /*******************************************************************
2416 Determine if a pattern contains any Microsoft wildcard characters.
2417 *******************************************************************/
2419 BOOL ms_has_wild(const char *s)
2421 char c;
2422 while ((c = *s++)) {
2423 switch (c) {
2424 case '*':
2425 case '?':
2426 case '<':
2427 case '>':
2428 case '"':
2429 return True;
2432 return False;
2435 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2437 smb_ucs2_t c;
2438 if (!s) return False;
2439 while ((c = *s++)) {
2440 switch (c) {
2441 case UCS2_CHAR('*'):
2442 case UCS2_CHAR('?'):
2443 case UCS2_CHAR('<'):
2444 case UCS2_CHAR('>'):
2445 case UCS2_CHAR('"'):
2446 return True;
2449 return False;
2452 /*******************************************************************
2453 A wrapper that handles case sensitivity and the special handling
2454 of the ".." name.
2455 *******************************************************************/
2457 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2459 if (strcmp(string,"..") == 0)
2460 string = ".";
2461 if (strcmp(pattern,".") == 0)
2462 return False;
2464 return ms_fnmatch(pattern, string, Protocol <= PROTOCOL_LANMAN2, is_case_sensitive) == 0;
2467 /*******************************************************************
2468 A wrapper that handles case sensitivity and the special handling
2469 of the ".." name. Varient that is only called by old search code which requires
2470 pattern translation.
2471 *******************************************************************/
2473 BOOL mask_match_search(const char *string, char *pattern, BOOL is_case_sensitive)
2475 if (strcmp(string,"..") == 0)
2476 string = ".";
2477 if (strcmp(pattern,".") == 0)
2478 return False;
2480 return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
2483 /*******************************************************************
2484 A wrapper that handles a list of patters and calls mask_match()
2485 on each. Returns True if any of the patterns match.
2486 *******************************************************************/
2488 BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
2490 while (listLen-- > 0) {
2491 if (mask_match(string, *list++, is_case_sensitive))
2492 return True;
2494 return False;
2497 /*********************************************************
2498 Recursive routine that is called by unix_wild_match.
2499 *********************************************************/
2501 static BOOL unix_do_match(const char *regexp, const char *str)
2503 const char *p;
2505 for( p = regexp; *p && *str; ) {
2507 switch(*p) {
2508 case '?':
2509 str++;
2510 p++;
2511 break;
2513 case '*':
2516 * Look for a character matching
2517 * the one after the '*'.
2519 p++;
2520 if(!*p)
2521 return True; /* Automatic match */
2522 while(*str) {
2524 while(*str && (*p != *str))
2525 str++;
2528 * Patch from weidel@multichart.de. In the case of the regexp
2529 * '*XX*' we want to ensure there are at least 2 'X' characters
2530 * in the string after the '*' for a match to be made.
2534 int matchcount=0;
2537 * Eat all the characters that match, but count how many there were.
2540 while(*str && (*p == *str)) {
2541 str++;
2542 matchcount++;
2546 * Now check that if the regexp had n identical characters that
2547 * matchcount had at least that many matches.
2550 while ( *(p+1) && (*(p+1) == *p)) {
2551 p++;
2552 matchcount--;
2555 if ( matchcount <= 0 )
2556 return False;
2559 str--; /* We've eaten the match char after the '*' */
2561 if(unix_do_match(p, str))
2562 return True;
2564 if(!*str)
2565 return False;
2566 else
2567 str++;
2569 return False;
2571 default:
2572 if(*str != *p)
2573 return False;
2574 str++;
2575 p++;
2576 break;
2580 if(!*p && !*str)
2581 return True;
2583 if (!*p && str[0] == '.' && str[1] == 0)
2584 return(True);
2586 if (!*str && *p == '?') {
2587 while (*p == '?')
2588 p++;
2589 return(!*p);
2592 if(!*str && (*p == '*' && p[1] == '\0'))
2593 return True;
2595 return False;
2598 /*******************************************************************
2599 Simple case insensitive interface to a UNIX wildcard matcher.
2600 *******************************************************************/
2602 BOOL unix_wild_match(const char *pattern, const char *string)
2604 pstring p2, s2;
2605 char *p;
2607 pstrcpy(p2, pattern);
2608 pstrcpy(s2, string);
2609 strlower_m(p2);
2610 strlower_m(s2);
2612 /* Remove any *? and ** from the pattern as they are meaningless */
2613 for(p = p2; *p; p++)
2614 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2615 pstrcpy( &p[1], &p[2]);
2617 if (strequal(p2,"*"))
2618 return True;
2620 return unix_do_match(p2, s2) == 0;
2623 /**********************************************************************
2624 Converts a name to a fully qalified domain name.
2625 ***********************************************************************/
2627 void name_to_fqdn(fstring fqdn, const char *name)
2629 struct hostent *hp = sys_gethostbyname(name);
2630 if ( hp && hp->h_name && *hp->h_name ) {
2631 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
2632 fstrcpy(fqdn,hp->h_name);
2633 } else {
2634 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
2635 fstrcpy(fqdn, name);
2639 #ifdef __INSURE__
2641 /*******************************************************************
2642 This routine is a trick to immediately catch errors when debugging
2643 with insure. A xterm with a gdb is popped up when insure catches
2644 a error. It is Linux specific.
2645 ********************************************************************/
2647 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2649 static int (*fn)();
2650 int ret;
2651 char pidstr[10];
2652 /* you can get /usr/bin/backtrace from
2653 http://samba.org/ftp/unpacked/junkcode/backtrace */
2654 pstring cmd = "/usr/bin/backtrace %d";
2656 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2657 pstring_sub(cmd, "%d", pidstr);
2659 if (!fn) {
2660 static void *h;
2661 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2662 fn = dlsym(h, "_Insure_trap_error");
2664 if (!h || h == _Insure_trap_error) {
2665 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2666 fn = dlsym(h, "_Insure_trap_error");
2670 ret = fn(a1, a2, a3, a4, a5, a6);
2672 system(cmd);
2674 return ret;
2676 #endif