r4231: commiting changes to 3.0.10
[Samba.git] / source / lib / util.c
blob00afdded83c893e08a867cef2e5b5cdc0830086a
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 int 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 Determine whether we are in the specified group.
278 ****************************************************************************/
280 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
282 int i;
284 if (group == current_gid)
285 return(True);
287 for (i=0;i<ngroups;i++)
288 if (group == groups[i])
289 return(True);
291 return(False);
294 /****************************************************************************
295 Add a gid to an array of gids if it's not already there.
296 ****************************************************************************/
298 void add_gid_to_array_unique(gid_t gid, gid_t **gids, int *num)
300 int i;
302 for (i=0; i<*num; i++) {
303 if ((*gids)[i] == gid)
304 return;
307 *gids = SMB_REALLOC_ARRAY(*gids, gid_t, *num+1);
309 if (*gids == NULL)
310 return;
312 (*gids)[*num] = gid;
313 *num += 1;
316 /****************************************************************************
317 Like atoi but gets the value up to the separator character.
318 ****************************************************************************/
320 static const char *Atoic(const char *p, int *n, const char *c)
322 if (!isdigit((int)*p)) {
323 DEBUG(5, ("Atoic: malformed number\n"));
324 return NULL;
327 (*n) = atoi(p);
329 while ((*p) && isdigit((int)*p))
330 p++;
332 if (strchr_m(c, *p) == NULL) {
333 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
334 return NULL;
337 return p;
340 /*************************************************************************
341 Reads a list of numbers.
342 *************************************************************************/
344 const char *get_numlist(const char *p, uint32 **num, int *count)
346 int val;
348 if (num == NULL || count == NULL)
349 return NULL;
351 (*count) = 0;
352 (*num ) = NULL;
354 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
355 uint32 *tn;
357 tn = SMB_REALLOC_ARRAY((*num), uint32, (*count)+1);
358 if (tn == NULL) {
359 SAFE_FREE(*num);
360 return NULL;
361 } else
362 (*num) = tn;
363 (*num)[(*count)] = val;
364 (*count)++;
365 p++;
368 return p;
371 /*******************************************************************
372 Check if a file exists - call vfs_file_exist for samba files.
373 ********************************************************************/
375 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
377 SMB_STRUCT_STAT st;
378 if (!sbuf)
379 sbuf = &st;
381 if (sys_stat(fname,sbuf) != 0)
382 return(False);
384 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
387 /*******************************************************************
388 Check a files mod time.
389 ********************************************************************/
391 time_t file_modtime(const char *fname)
393 SMB_STRUCT_STAT st;
395 if (sys_stat(fname,&st) != 0)
396 return(0);
398 return(st.st_mtime);
401 /*******************************************************************
402 Check if a directory exists.
403 ********************************************************************/
405 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
407 SMB_STRUCT_STAT st2;
408 BOOL ret;
410 if (!st)
411 st = &st2;
413 if (sys_stat(dname,st) != 0)
414 return(False);
416 ret = S_ISDIR(st->st_mode);
417 if(!ret)
418 errno = ENOTDIR;
419 return ret;
422 /*******************************************************************
423 Returns the size in bytes of the named file.
424 ********************************************************************/
426 SMB_OFF_T get_file_size(char *file_name)
428 SMB_STRUCT_STAT buf;
429 buf.st_size = 0;
430 if(sys_stat(file_name,&buf) != 0)
431 return (SMB_OFF_T)-1;
432 return(buf.st_size);
435 /*******************************************************************
436 Return a string representing an attribute for a file.
437 ********************************************************************/
439 char *attrib_string(uint16 mode)
441 static fstring attrstr;
443 attrstr[0] = 0;
445 if (mode & aVOLID) fstrcat(attrstr,"V");
446 if (mode & aDIR) fstrcat(attrstr,"D");
447 if (mode & aARCH) fstrcat(attrstr,"A");
448 if (mode & aHIDDEN) fstrcat(attrstr,"H");
449 if (mode & aSYSTEM) fstrcat(attrstr,"S");
450 if (mode & aRONLY) fstrcat(attrstr,"R");
452 return(attrstr);
455 /*******************************************************************
456 Show a smb message structure.
457 ********************************************************************/
459 void show_msg(char *buf)
461 int i;
462 int bcc=0;
464 if (!DEBUGLVL(5))
465 return;
467 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
468 smb_len(buf),
469 (int)CVAL(buf,smb_com),
470 (int)CVAL(buf,smb_rcls),
471 (int)CVAL(buf,smb_reh),
472 (int)SVAL(buf,smb_err),
473 (int)CVAL(buf,smb_flg),
474 (int)SVAL(buf,smb_flg2)));
475 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
476 (int)SVAL(buf,smb_tid),
477 (int)SVAL(buf,smb_pid),
478 (int)SVAL(buf,smb_uid),
479 (int)SVAL(buf,smb_mid)));
480 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
482 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
483 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
484 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
486 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
488 DEBUGADD(5,("smb_bcc=%d\n",bcc));
490 if (DEBUGLEVEL < 10)
491 return;
493 if (DEBUGLEVEL < 50)
494 bcc = MIN(bcc, 512);
496 dump_data(10, smb_buf(buf), bcc);
499 /*******************************************************************
500 Set the length and marker of an smb packet.
501 ********************************************************************/
503 void smb_setlen(char *buf,int len)
505 _smb_setlen(buf,len);
507 SCVAL(buf,4,0xFF);
508 SCVAL(buf,5,'S');
509 SCVAL(buf,6,'M');
510 SCVAL(buf,7,'B');
513 /*******************************************************************
514 Setup the word count and byte count for a smb message.
515 ********************************************************************/
517 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
519 if (zero)
520 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
521 SCVAL(buf,smb_wct,num_words);
522 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
523 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
524 return (smb_size + num_words*2 + num_bytes);
527 /*******************************************************************
528 Setup only the byte count for a smb message.
529 ********************************************************************/
531 int set_message_bcc(char *buf,int num_bytes)
533 int num_words = CVAL(buf,smb_wct);
534 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
535 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
536 return (smb_size + num_words*2 + num_bytes);
539 /*******************************************************************
540 Setup only the byte count for a smb message, using the end of the
541 message as a marker.
542 ********************************************************************/
544 int set_message_end(void *outbuf,void *end_ptr)
546 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
549 /*******************************************************************
550 Reduce a file name, removing .. elements.
551 ********************************************************************/
553 void dos_clean_name(char *s)
555 char *p=NULL;
557 DEBUG(3,("dos_clean_name [%s]\n",s));
559 /* remove any double slashes */
560 all_string_sub(s, "\\\\", "\\", 0);
562 while ((p = strstr_m(s,"\\..\\")) != NULL) {
563 pstring s1;
565 *p = 0;
566 pstrcpy(s1,p+3);
568 if ((p=strrchr_m(s,'\\')) != NULL)
569 *p = 0;
570 else
571 *s = 0;
572 pstrcat(s,s1);
575 trim_string(s,NULL,"\\..");
577 all_string_sub(s, "\\.\\", "\\", 0);
580 /*******************************************************************
581 Reduce a file name, removing .. elements.
582 ********************************************************************/
584 void unix_clean_name(char *s)
586 char *p=NULL;
588 DEBUG(3,("unix_clean_name [%s]\n",s));
590 /* remove any double slashes */
591 all_string_sub(s, "//","/", 0);
593 /* Remove leading ./ characters */
594 if(strncmp(s, "./", 2) == 0) {
595 trim_string(s, "./", NULL);
596 if(*s == 0)
597 pstrcpy(s,"./");
600 while ((p = strstr_m(s,"/../")) != NULL) {
601 pstring s1;
603 *p = 0;
604 pstrcpy(s1,p+3);
606 if ((p=strrchr_m(s,'/')) != NULL)
607 *p = 0;
608 else
609 *s = 0;
610 pstrcat(s,s1);
613 trim_string(s,NULL,"/..");
616 /****************************************************************************
617 Make a dir struct.
618 ****************************************************************************/
620 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date, BOOL case_sensitive)
622 char *p;
623 pstring mask2;
625 pstrcpy(mask2,mask);
627 if ((mode & aDIR) != 0)
628 size = 0;
630 memset(buf+1,' ',11);
631 if ((p = strchr_m(mask2,'.')) != NULL) {
632 *p = 0;
633 push_ascii(buf+1,mask2,8, 0);
634 push_ascii(buf+9,p+1,3, 0);
635 *p = '.';
636 } else
637 push_ascii(buf+1,mask2,11, 0);
639 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
640 SCVAL(buf,21,mode);
641 put_dos_date(buf,22,date);
642 SSVAL(buf,26,size & 0xFFFF);
643 SSVAL(buf,28,(size >> 16)&0xFFFF);
644 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
645 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
648 /*******************************************************************
649 Close the low 3 fd's and open dev/null in their place.
650 ********************************************************************/
652 void close_low_fds(BOOL stderr_too)
654 #ifndef VALGRIND
655 int fd;
656 int i;
658 close(0);
659 close(1);
661 if (stderr_too)
662 close(2);
664 /* try and use up these file descriptors, so silly
665 library routines writing to stdout etc won't cause havoc */
666 for (i=0;i<3;i++) {
667 if (i == 2 && !stderr_too)
668 continue;
670 fd = sys_open("/dev/null",O_RDWR,0);
671 if (fd < 0)
672 fd = sys_open("/dev/null",O_WRONLY,0);
673 if (fd < 0) {
674 DEBUG(0,("Can't open /dev/null\n"));
675 return;
677 if (fd != i) {
678 DEBUG(0,("Didn't get file descriptor %d\n",i));
679 return;
682 #endif
685 /****************************************************************************
686 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
687 else
688 if SYSV use O_NDELAY
689 if BSD use FNDELAY
690 ****************************************************************************/
692 int set_blocking(int fd, BOOL set)
694 int val;
695 #ifdef O_NONBLOCK
696 #define FLAG_TO_SET O_NONBLOCK
697 #else
698 #ifdef SYSV
699 #define FLAG_TO_SET O_NDELAY
700 #else /* BSD */
701 #define FLAG_TO_SET FNDELAY
702 #endif
703 #endif
705 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
706 return -1;
707 if(set) /* Turn blocking on - ie. clear nonblock flag */
708 val &= ~FLAG_TO_SET;
709 else
710 val |= FLAG_TO_SET;
711 return sys_fcntl_long( fd, F_SETFL, val);
712 #undef FLAG_TO_SET
715 /****************************************************************************
716 Transfer some data between two fd's.
717 ****************************************************************************/
719 #ifndef TRANSFER_BUF_SIZE
720 #define TRANSFER_BUF_SIZE 65536
721 #endif
723 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
724 ssize_t (*write_fn)(int, const void *, size_t))
726 char *buf;
727 size_t total = 0;
728 ssize_t read_ret;
729 ssize_t write_ret;
730 size_t num_to_read_thistime;
731 size_t num_written = 0;
733 if ((buf = SMB_MALLOC(TRANSFER_BUF_SIZE)) == NULL)
734 return -1;
736 while (total < n) {
737 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
739 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
740 if (read_ret == -1) {
741 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
742 SAFE_FREE(buf);
743 return -1;
745 if (read_ret == 0)
746 break;
748 num_written = 0;
750 while (num_written < read_ret) {
751 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
753 if (write_ret == -1) {
754 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
755 SAFE_FREE(buf);
756 return -1;
758 if (write_ret == 0)
759 return (ssize_t)total;
761 num_written += (size_t)write_ret;
764 total += (size_t)read_ret;
767 SAFE_FREE(buf);
768 return (ssize_t)total;
771 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
773 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
776 /*******************************************************************
777 Sleep for a specified number of milliseconds.
778 ********************************************************************/
780 void smb_msleep(unsigned int t)
782 unsigned int tdiff=0;
783 struct timeval tval,t1,t2;
784 fd_set fds;
786 GetTimeOfDay(&t1);
787 GetTimeOfDay(&t2);
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);
813 /****************************************************************************
814 Become a daemon, discarding the controlling terminal.
815 ****************************************************************************/
817 void become_daemon(BOOL Fork)
819 if (Fork) {
820 if (sys_fork()) {
821 _exit(0);
825 /* detach from the terminal */
826 #ifdef HAVE_SETSID
827 setsid();
828 #elif defined(TIOCNOTTY)
830 int i = sys_open("/dev/tty", O_RDWR, 0);
831 if (i != -1) {
832 ioctl(i, (int) TIOCNOTTY, (char *)0);
833 close(i);
836 #endif /* HAVE_SETSID */
838 /* Close fd's 0,1,2. Needed if started by rsh */
839 close_low_fds(False); /* Don't close stderr, let the debug system
840 attach it to the logfile */
843 /****************************************************************************
844 Put up a yes/no prompt.
845 ****************************************************************************/
847 BOOL yesno(char *p)
849 pstring ans;
850 printf("%s",p);
852 if (!fgets(ans,sizeof(ans)-1,stdin))
853 return(False);
855 if (*ans == 'y' || *ans == 'Y')
856 return(True);
858 return(False);
861 #if defined(PARANOID_MALLOC_CHECKER)
863 /****************************************************************************
864 Internal malloc wrapper. Externally visible.
865 ****************************************************************************/
867 void *malloc_(size_t size)
869 #undef malloc
870 return malloc(size);
871 #define malloc(s) __ERROR_DONT_USE_MALLOC_DIRECTLY
874 /****************************************************************************
875 Internal calloc wrapper. Not externally visible.
876 ****************************************************************************/
878 static void *calloc_(size_t count, size_t size)
880 #undef calloc
881 return calloc(count, size);
882 #define calloc(n,s) __ERROR_DONT_USE_CALLOC_DIRECTLY
885 /****************************************************************************
886 Internal realloc wrapper. Not externally visible.
887 ****************************************************************************/
889 static void *realloc_(void *ptr, size_t size)
891 #undef realloc
892 return realloc(ptr, size);
893 #define realloc(p,s) __ERROR_DONT_USE_RELLOC_DIRECTLY
896 #endif /* PARANOID_MALLOC_CHECKER */
898 /****************************************************************************
899 Type-safe malloc.
900 ****************************************************************************/
902 void *malloc_array(size_t el_size, unsigned int count)
904 if (count >= MAX_ALLOC_SIZE/el_size) {
905 return NULL;
908 #if defined(PARANOID_MALLOC_CHECKER)
909 return malloc_(el_size*count);
910 #else
911 return malloc(el_size*count);
912 #endif
915 /****************************************************************************
916 Type-safe calloc.
917 ****************************************************************************/
919 void *calloc_array(size_t size, size_t nmemb)
921 if (nmemb >= MAX_ALLOC_SIZE/size) {
922 return NULL;
924 #if defined(PARANOID_MALLOC_CHECKER)
925 return calloc_(nmemb, size);
926 #else
927 return calloc(nmemb, size);
928 #endif
931 /****************************************************************************
932 Expand a pointer to be a particular size.
933 ****************************************************************************/
935 void *Realloc(void *p,size_t size)
937 void *ret=NULL;
939 if (size == 0) {
940 SAFE_FREE(p);
941 DEBUG(5,("Realloc asked for 0 bytes\n"));
942 return NULL;
945 #if defined(PARANOID_MALLOC_CHECKER)
946 if (!p)
947 ret = (void *)malloc_(size);
948 else
949 ret = (void *)realloc_(p,size);
950 #else
951 if (!p)
952 ret = (void *)malloc(size);
953 else
954 ret = (void *)realloc(p,size);
955 #endif
957 if (!ret)
958 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
960 return(ret);
963 /****************************************************************************
964 Type-safe realloc.
965 ****************************************************************************/
967 void *realloc_array(void *p,size_t el_size, unsigned int count)
969 if (count >= MAX_ALLOC_SIZE/el_size) {
970 return NULL;
972 return Realloc(p,el_size*count);
975 /****************************************************************************
976 Free memory, checks for NULL.
977 Use directly SAFE_FREE()
978 Exists only because we need to pass a function pointer somewhere --SSS
979 ****************************************************************************/
981 void safe_free(void *p)
983 SAFE_FREE(p);
986 /****************************************************************************
987 Get my own name and IP.
988 ****************************************************************************/
990 BOOL get_myname(char *my_name)
992 pstring hostname;
994 *hostname = 0;
996 /* get my host name */
997 if (gethostname(hostname, sizeof(hostname)) == -1) {
998 DEBUG(0,("gethostname failed\n"));
999 return False;
1002 /* Ensure null termination. */
1003 hostname[sizeof(hostname)-1] = '\0';
1005 if (my_name) {
1006 /* split off any parts after an initial . */
1007 char *p = strchr_m(hostname,'.');
1009 if (p)
1010 *p = 0;
1012 fstrcpy(my_name,hostname);
1015 return(True);
1018 /****************************************************************************
1019 Get my own canonical name, including domain.
1020 ****************************************************************************/
1022 BOOL get_mydnsfullname(fstring my_dnsname)
1024 static fstring dnshostname;
1025 struct hostent *hp;
1027 if (!*dnshostname) {
1028 /* get my host name */
1029 if (gethostname(dnshostname, sizeof(dnshostname)) == -1) {
1030 *dnshostname = '\0';
1031 DEBUG(0,("gethostname failed\n"));
1032 return False;
1035 /* Ensure null termination. */
1036 dnshostname[sizeof(dnshostname)-1] = '\0';
1038 /* Ensure we get the cannonical name. */
1039 if (!(hp = sys_gethostbyname(dnshostname))) {
1040 *dnshostname = '\0';
1041 return False;
1043 fstrcpy(dnshostname, hp->h_name);
1045 fstrcpy(my_dnsname, dnshostname);
1046 return True;
1049 /****************************************************************************
1050 Get my own domain name.
1051 ****************************************************************************/
1053 BOOL get_mydnsdomname(fstring my_domname)
1055 fstring domname;
1056 char *p;
1058 *my_domname = '\0';
1059 if (!get_mydnsfullname(domname)) {
1060 return False;
1062 p = strchr_m(domname, '.');
1063 if (p) {
1064 p++;
1065 fstrcpy(my_domname, p);
1068 return False;
1071 /****************************************************************************
1072 Interpret a protocol description string, with a default.
1073 ****************************************************************************/
1075 int interpret_protocol(const char *str,int def)
1077 if (strequal(str,"NT1"))
1078 return(PROTOCOL_NT1);
1079 if (strequal(str,"LANMAN2"))
1080 return(PROTOCOL_LANMAN2);
1081 if (strequal(str,"LANMAN1"))
1082 return(PROTOCOL_LANMAN1);
1083 if (strequal(str,"CORE"))
1084 return(PROTOCOL_CORE);
1085 if (strequal(str,"COREPLUS"))
1086 return(PROTOCOL_COREPLUS);
1087 if (strequal(str,"CORE+"))
1088 return(PROTOCOL_COREPLUS);
1090 DEBUG(0,("Unrecognised protocol level %s\n",str));
1092 return(def);
1095 /****************************************************************************
1096 Return true if a string could be a pure IP address.
1097 ****************************************************************************/
1099 BOOL is_ipaddress(const char *str)
1101 BOOL pure_address = True;
1102 int i;
1104 for (i=0; pure_address && str[i]; i++)
1105 if (!(isdigit((int)str[i]) || str[i] == '.'))
1106 pure_address = False;
1108 /* Check that a pure number is not misinterpreted as an IP */
1109 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1111 return pure_address;
1114 /****************************************************************************
1115 Interpret an internet address or name into an IP address in 4 byte form.
1116 ****************************************************************************/
1118 uint32 interpret_addr(const char *str)
1120 struct hostent *hp;
1121 uint32 res;
1123 if (strcmp(str,"0.0.0.0") == 0)
1124 return(0);
1125 if (strcmp(str,"255.255.255.255") == 0)
1126 return(0xFFFFFFFF);
1128 /* if it's in the form of an IP address then get the lib to interpret it */
1129 if (is_ipaddress(str)) {
1130 res = inet_addr(str);
1131 } else {
1132 /* otherwise assume it's a network name of some sort and use
1133 sys_gethostbyname */
1134 if ((hp = sys_gethostbyname(str)) == 0) {
1135 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1136 return 0;
1139 if(hp->h_addr == NULL) {
1140 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1141 return 0;
1143 putip((char *)&res,(char *)hp->h_addr);
1146 if (res == (uint32)-1)
1147 return(0);
1149 return(res);
1152 /*******************************************************************
1153 A convenient addition to interpret_addr().
1154 ******************************************************************/
1156 struct in_addr *interpret_addr2(const char *str)
1158 static struct in_addr ret;
1159 uint32 a = interpret_addr(str);
1160 ret.s_addr = a;
1161 return(&ret);
1164 /*******************************************************************
1165 Check if an IP is the 0.0.0.0.
1166 ******************************************************************/
1168 BOOL is_zero_ip(struct in_addr ip)
1170 uint32 a;
1171 putip((char *)&a,(char *)&ip);
1172 return(a == 0);
1175 /*******************************************************************
1176 Set an IP to 0.0.0.0.
1177 ******************************************************************/
1179 void zero_ip(struct in_addr *ip)
1181 static BOOL init;
1182 static struct in_addr ipzero;
1184 if (!init) {
1185 ipzero = *interpret_addr2("0.0.0.0");
1186 init = True;
1189 *ip = ipzero;
1192 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1193 /******************************************************************
1194 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1195 Based on a fix from <Thomas.Hepper@icem.de>.
1196 *******************************************************************/
1198 static void strip_mount_options( pstring *str)
1200 if (**str == '-') {
1201 char *p = *str;
1202 while(*p && !isspace(*p))
1203 p++;
1204 while(*p && isspace(*p))
1205 p++;
1206 if(*p) {
1207 pstring tmp_str;
1209 pstrcpy(tmp_str, p);
1210 pstrcpy(*str, tmp_str);
1215 /*******************************************************************
1216 Patch from jkf@soton.ac.uk
1217 Split Luke's automount_server into YP lookup and string splitter
1218 so can easily implement automount_path().
1219 As we may end up doing both, cache the last YP result.
1220 *******************************************************************/
1222 #ifdef WITH_NISPLUS_HOME
1223 char *automount_lookup( char *user_name)
1225 static fstring last_key = "";
1226 static pstring last_value = "";
1228 char *nis_map = (char *)lp_nis_home_map_name();
1230 char buffer[NIS_MAXATTRVAL + 1];
1231 nis_result *result;
1232 nis_object *object;
1233 entry_obj *entry;
1235 if (strcmp(user_name, last_key)) {
1236 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1237 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1239 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1240 if (result->status != NIS_SUCCESS) {
1241 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1242 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1243 } else {
1244 object = result->objects.objects_val;
1245 if (object->zo_data.zo_type == ENTRY_OBJ) {
1246 entry = &object->zo_data.objdata_u.en_data;
1247 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1248 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1250 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1251 pstring_sub(last_value, "&", user_name);
1252 fstrcpy(last_key, user_name);
1256 nis_freeresult(result);
1259 strip_mount_options(&last_value);
1261 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1262 return last_value;
1264 #else /* WITH_NISPLUS_HOME */
1266 char *automount_lookup( char *user_name)
1268 static fstring last_key = "";
1269 static pstring last_value = "";
1271 int nis_error; /* returned by yp all functions */
1272 char *nis_result; /* yp_match inits this */
1273 int nis_result_len; /* and set this */
1274 char *nis_domain; /* yp_get_default_domain inits this */
1275 char *nis_map = (char *)lp_nis_home_map_name();
1277 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1278 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1279 return last_value;
1282 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1284 if (!strcmp(user_name, last_key)) {
1285 nis_result = last_value;
1286 nis_result_len = strlen(last_value);
1287 nis_error = 0;
1288 } else {
1289 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1290 &nis_result, &nis_result_len)) == 0) {
1291 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1292 nis_result_len = sizeof(pstring)-1;
1294 fstrcpy(last_key, user_name);
1295 strncpy(last_value, nis_result, nis_result_len);
1296 last_value[nis_result_len] = '\0';
1297 strip_mount_options(&last_value);
1299 } else if(nis_error == YPERR_KEY) {
1301 /* If Key lookup fails user home server is not in nis_map
1302 use default information for server, and home directory */
1303 last_value[0] = 0;
1304 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1305 user_name, nis_map));
1306 DEBUG(3, ("using defaults for server and home directory\n"));
1307 } else {
1308 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1309 yperr_string(nis_error), user_name, nis_map));
1313 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1314 return last_value;
1316 #endif /* WITH_NISPLUS_HOME */
1317 #endif
1319 /*******************************************************************
1320 Are two IPs on the same subnet?
1321 ********************************************************************/
1323 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1325 uint32 net1,net2,nmask;
1327 nmask = ntohl(mask.s_addr);
1328 net1 = ntohl(ip1.s_addr);
1329 net2 = ntohl(ip2.s_addr);
1331 return((net1 & nmask) == (net2 & nmask));
1335 /****************************************************************************
1336 Check if a process exists. Does this work on all unixes?
1337 ****************************************************************************/
1339 BOOL process_exists(pid_t pid)
1341 /* Doing kill with a non-positive pid causes messages to be
1342 * sent to places we don't want. */
1343 SMB_ASSERT(pid > 0);
1344 return(kill(pid,0) == 0 || errno != ESRCH);
1347 /*******************************************************************
1348 Convert a uid into a user name.
1349 ********************************************************************/
1351 const char *uidtoname(uid_t uid)
1353 static fstring name;
1354 struct passwd *pass;
1356 pass = getpwuid_alloc(uid);
1357 if (pass) {
1358 fstrcpy(name, pass->pw_name);
1359 passwd_free(&pass);
1360 } else {
1361 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1363 return name;
1367 /*******************************************************************
1368 Convert a gid into a group name.
1369 ********************************************************************/
1371 char *gidtoname(gid_t gid)
1373 static fstring name;
1374 struct group *grp;
1376 grp = getgrgid(gid);
1377 if (grp)
1378 return(grp->gr_name);
1379 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1380 return(name);
1383 /*******************************************************************
1384 Convert a user name into a uid.
1385 ********************************************************************/
1387 uid_t nametouid(const char *name)
1389 struct passwd *pass;
1390 char *p;
1391 uid_t u;
1393 pass = getpwnam_alloc(name);
1394 if (pass) {
1395 u = pass->pw_uid;
1396 passwd_free(&pass);
1397 return u;
1400 u = (uid_t)strtol(name, &p, 0);
1401 if ((p != name) && (*p == '\0'))
1402 return u;
1404 return (uid_t)-1;
1407 /*******************************************************************
1408 Convert a name to a gid_t if possible. Return -1 if not a group.
1409 ********************************************************************/
1411 gid_t nametogid(const char *name)
1413 struct group *grp;
1414 char *p;
1415 gid_t g;
1417 g = (gid_t)strtol(name, &p, 0);
1418 if ((p != name) && (*p == '\0'))
1419 return g;
1421 grp = sys_getgrnam(name);
1422 if (grp)
1423 return(grp->gr_gid);
1424 return (gid_t)-1;
1427 /*******************************************************************
1428 legacy wrapper for smb_panic2()
1429 ********************************************************************/
1430 void smb_panic( const char *why )
1432 smb_panic2( why, True );
1435 /*******************************************************************
1436 Something really nasty happened - panic !
1437 ********************************************************************/
1439 #ifdef HAVE_LIBEXC_H
1440 #include <libexc.h>
1441 #endif
1443 void smb_panic2(const char *why, BOOL decrement_pid_count )
1445 char *cmd;
1446 int result;
1447 #ifdef HAVE_BACKTRACE_SYMBOLS
1448 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1449 size_t backtrace_size;
1450 char **backtrace_strings;
1451 #endif
1453 #ifdef DEVELOPER
1455 extern char *global_clobber_region_function;
1456 extern unsigned int global_clobber_region_line;
1458 if (global_clobber_region_function) {
1459 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1460 global_clobber_region_function,
1461 global_clobber_region_line));
1464 #endif
1466 /* only smbd needs to decrement the smbd counter in connections.tdb */
1467 if ( decrement_pid_count )
1468 decrement_smbd_process_count();
1470 cmd = lp_panic_action();
1471 if (cmd && *cmd) {
1472 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1473 result = system(cmd);
1475 if (result == -1)
1476 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1477 strerror(errno)));
1478 else
1479 DEBUG(0, ("smb_panic(): action returned status %d\n",
1480 WEXITSTATUS(result)));
1482 DEBUG(0,("PANIC: %s\n", why));
1484 #ifdef HAVE_BACKTRACE_SYMBOLS
1485 /* get the backtrace (stack frames) */
1486 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1487 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1489 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
1490 (unsigned long)backtrace_size));
1492 if (backtrace_strings) {
1493 int i;
1495 for (i = 0; i < backtrace_size; i++)
1496 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1498 /* Leak the backtrace_strings, rather than risk what free() might do */
1501 #elif HAVE_LIBEXC
1503 #define NAMESIZE 32 /* Arbitrary */
1505 /* The IRIX libexc library provides an API for unwinding the stack. See
1506 * libexc(3) for details. Apparantly trace_back_stack leaks memory, but
1507 * since we are about to abort anyway, it hardly matters.
1509 * Note that if we paniced due to a SIGSEGV or SIGBUS (or similar) this
1510 * will fail with a nasty message upon failing to open the /proc entry.
1513 __uint64_t addrs[BACKTRACE_STACK_SIZE];
1514 char * names[BACKTRACE_STACK_SIZE];
1515 char namebuf[BACKTRACE_STACK_SIZE * NAMESIZE];
1517 int i;
1518 int levels;
1520 ZERO_ARRAY(addrs);
1521 ZERO_ARRAY(names);
1522 ZERO_ARRAY(namebuf);
1524 for (i = 0; i < BACKTRACE_STACK_SIZE; i++) {
1525 names[i] = namebuf + (i * NAMESIZE);
1528 levels = trace_back_stack(0, addrs, names,
1529 BACKTRACE_STACK_SIZE, NAMESIZE);
1531 DEBUG(0, ("BACKTRACE: %d stack frames:\n", levels));
1532 for (i = 0; i < levels; i++) {
1533 DEBUGADD(0, (" #%d 0x%llx %s\n", i, addrs[i], names[i]));
1536 #undef NAMESIZE
1537 #endif
1539 dbgflush();
1540 #ifdef SIGABRT
1541 CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
1542 #endif
1543 abort();
1546 /*******************************************************************
1547 A readdir wrapper which just returns the file name.
1548 ********************************************************************/
1550 const char *readdirname(DIR *p)
1552 SMB_STRUCT_DIRENT *ptr;
1553 char *dname;
1555 if (!p)
1556 return(NULL);
1558 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1559 if (!ptr)
1560 return(NULL);
1562 dname = ptr->d_name;
1564 #ifdef NEXT2
1565 if (telldir(p) < 0)
1566 return(NULL);
1567 #endif
1569 #ifdef HAVE_BROKEN_READDIR
1570 /* using /usr/ucb/cc is BAD */
1571 dname = dname - 2;
1572 #endif
1575 static pstring buf;
1576 int len = NAMLEN(ptr);
1577 memcpy(buf, dname, len);
1578 buf[len] = 0;
1579 dname = buf;
1582 return(dname);
1585 /*******************************************************************
1586 Utility function used to decide if the last component
1587 of a path matches a (possibly wildcarded) entry in a namelist.
1588 ********************************************************************/
1590 BOOL is_in_path(const char *name, name_compare_entry *namelist, BOOL case_sensitive)
1592 pstring last_component;
1593 char *p;
1595 /* if we have no list it's obviously not in the path */
1596 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1597 return False;
1600 DEBUG(8, ("is_in_path: %s\n", name));
1602 /* Get the last component of the unix name. */
1603 p = strrchr_m(name, '/');
1604 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1605 last_component[sizeof(last_component)-1] = '\0';
1607 for(; namelist->name != NULL; namelist++) {
1608 if(namelist->is_wild) {
1609 if (mask_match(last_component, namelist->name, case_sensitive)) {
1610 DEBUG(8,("is_in_path: mask match succeeded\n"));
1611 return True;
1613 } else {
1614 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1615 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1616 DEBUG(8,("is_in_path: match succeeded\n"));
1617 return True;
1621 DEBUG(8,("is_in_path: match not found\n"));
1623 return False;
1626 /*******************************************************************
1627 Strip a '/' separated list into an array of
1628 name_compare_enties structures suitable for
1629 passing to is_in_path(). We do this for
1630 speed so we can pre-parse all the names in the list
1631 and don't do it for each call to is_in_path().
1632 namelist is modified here and is assumed to be
1633 a copy owned by the caller.
1634 We also check if the entry contains a wildcard to
1635 remove a potentially expensive call to mask_match
1636 if possible.
1637 ********************************************************************/
1639 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1641 char *name_end;
1642 char *nameptr = namelist;
1643 int num_entries = 0;
1644 int i;
1646 (*ppname_array) = NULL;
1648 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1649 return;
1651 /* We need to make two passes over the string. The
1652 first to count the number of elements, the second
1653 to split it.
1656 while(*nameptr) {
1657 if ( *nameptr == '/' ) {
1658 /* cope with multiple (useless) /s) */
1659 nameptr++;
1660 continue;
1662 /* find the next / */
1663 name_end = strchr_m(nameptr, '/');
1665 /* oops - the last check for a / didn't find one. */
1666 if (name_end == NULL)
1667 break;
1669 /* next segment please */
1670 nameptr = name_end + 1;
1671 num_entries++;
1674 if(num_entries == 0)
1675 return;
1677 if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
1678 DEBUG(0,("set_namearray: malloc fail\n"));
1679 return;
1682 /* Now copy out the names */
1683 nameptr = namelist;
1684 i = 0;
1685 while(*nameptr) {
1686 if ( *nameptr == '/' ) {
1687 /* cope with multiple (useless) /s) */
1688 nameptr++;
1689 continue;
1691 /* find the next / */
1692 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1693 *name_end = 0;
1695 /* oops - the last check for a / didn't find one. */
1696 if(name_end == NULL)
1697 break;
1699 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1700 if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
1701 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1702 return;
1705 /* next segment please */
1706 nameptr = name_end + 1;
1707 i++;
1710 (*ppname_array)[i].name = NULL;
1712 return;
1715 /****************************************************************************
1716 Routine to free a namearray.
1717 ****************************************************************************/
1719 void free_namearray(name_compare_entry *name_array)
1721 int i;
1723 if(name_array == NULL)
1724 return;
1726 for(i=0; name_array[i].name!=NULL; i++)
1727 SAFE_FREE(name_array[i].name);
1728 SAFE_FREE(name_array);
1731 /****************************************************************************
1732 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1733 is dealt with in posix.c
1734 ****************************************************************************/
1736 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1738 SMB_STRUCT_FLOCK lock;
1739 int ret;
1741 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1743 lock.l_type = type;
1744 lock.l_whence = SEEK_SET;
1745 lock.l_start = offset;
1746 lock.l_len = count;
1747 lock.l_pid = 0;
1749 ret = sys_fcntl_ptr(fd,op,&lock);
1751 if (ret == -1 && errno != 0)
1752 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1754 /* a lock query */
1755 if (op == SMB_F_GETLK) {
1756 if ((ret != -1) &&
1757 (lock.l_type != F_UNLCK) &&
1758 (lock.l_pid != 0) &&
1759 (lock.l_pid != sys_getpid())) {
1760 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1761 return(True);
1764 /* it must be not locked or locked by me */
1765 return(False);
1768 /* a lock set or unset */
1769 if (ret == -1) {
1770 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1771 (double)offset,(double)count,op,type,strerror(errno)));
1772 return(False);
1775 /* everything went OK */
1776 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1778 return(True);
1781 /*******************************************************************
1782 Is the name specified one of my netbios names.
1783 Returns true if it is equal, false otherwise.
1784 ********************************************************************/
1786 BOOL is_myname(const char *s)
1788 int n;
1789 BOOL ret = False;
1791 for (n=0; my_netbios_names(n); n++) {
1792 if (strequal(my_netbios_names(n), s)) {
1793 ret=True;
1794 break;
1797 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1798 return(ret);
1801 BOOL is_myname_or_ipaddr(const char *s)
1803 fstring name, dnsname;
1804 char *servername;
1806 if ( !s )
1807 return False;
1809 /* santize the string from '\\name' */
1811 fstrcpy( name, s );
1813 servername = strrchr_m( name, '\\' );
1814 if ( !servername )
1815 servername = name;
1816 else
1817 servername++;
1819 /* optimize for the common case */
1821 if (strequal(servername, global_myname()))
1822 return True;
1824 /* check for an alias */
1826 if (is_myname(servername))
1827 return True;
1829 /* check for loopback */
1831 if (strequal(servername, "localhost"))
1832 return True;
1834 /* maybe it's my dns name */
1836 if ( get_mydnsfullname( dnsname ) )
1837 if ( strequal( servername, dnsname ) )
1838 return True;
1840 /* handle possible CNAME records */
1842 if ( !is_ipaddress( servername ) ) {
1843 /* use DNS to resolve the name, but only the first address */
1844 struct hostent *hp;
1846 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1847 struct in_addr return_ip;
1848 putip( (char*)&return_ip, (char*)hp->h_addr );
1849 fstrcpy( name, inet_ntoa( return_ip ) );
1850 servername = name;
1854 /* maybe its an IP address? */
1855 if (is_ipaddress(servername)) {
1856 struct iface_struct nics[MAX_INTERFACES];
1857 int i, n;
1858 uint32 ip;
1860 ip = interpret_addr(servername);
1861 if ((ip==0) || (ip==0xffffffff))
1862 return False;
1864 n = get_interfaces(nics, MAX_INTERFACES);
1865 for (i=0; i<n; i++) {
1866 if (ip == nics[i].ip.s_addr)
1867 return True;
1871 /* no match */
1872 return False;
1875 /*******************************************************************
1876 Is the name specified our workgroup/domain.
1877 Returns true if it is equal, false otherwise.
1878 ********************************************************************/
1880 BOOL is_myworkgroup(const char *s)
1882 BOOL ret = False;
1884 if (strequal(s, lp_workgroup())) {
1885 ret=True;
1888 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1889 return(ret);
1892 /*******************************************************************
1893 we distinguish between 2K and XP by the "Native Lan Manager" string
1894 WinXP => "Windows 2002 5.1"
1895 Win2k => "Windows 2000 5.0"
1896 NT4 => "Windows NT 4.0"
1897 Win9x => "Windows 4.0"
1898 Windows 2003 doesn't set the native lan manager string but
1899 they do set the domain to "Windows 2003 5.2" (probably a bug).
1900 ********************************************************************/
1902 void ra_lanman_string( const char *native_lanman )
1904 if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
1905 set_remote_arch( RA_WINXP );
1906 else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
1907 set_remote_arch( RA_WIN2K3 );
1910 /*******************************************************************
1911 Set the horrid remote_arch string based on an enum.
1912 ********************************************************************/
1914 void set_remote_arch(enum remote_arch_types type)
1916 extern fstring remote_arch;
1917 ra_type = type;
1918 switch( type ) {
1919 case RA_WFWG:
1920 fstrcpy(remote_arch, "WfWg");
1921 break;
1922 case RA_OS2:
1923 fstrcpy(remote_arch, "OS2");
1924 break;
1925 case RA_WIN95:
1926 fstrcpy(remote_arch, "Win95");
1927 break;
1928 case RA_WINNT:
1929 fstrcpy(remote_arch, "WinNT");
1930 break;
1931 case RA_WIN2K:
1932 fstrcpy(remote_arch, "Win2K");
1933 break;
1934 case RA_WINXP:
1935 fstrcpy(remote_arch, "WinXP");
1936 break;
1937 case RA_WIN2K3:
1938 fstrcpy(remote_arch, "Win2K3");
1939 break;
1940 case RA_SAMBA:
1941 fstrcpy(remote_arch,"Samba");
1942 break;
1943 case RA_CIFSFS:
1944 fstrcpy(remote_arch,"CIFSFS");
1945 break;
1946 default:
1947 ra_type = RA_UNKNOWN;
1948 fstrcpy(remote_arch, "UNKNOWN");
1949 break;
1952 DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
1955 /*******************************************************************
1956 Get the remote_arch type.
1957 ********************************************************************/
1959 enum remote_arch_types get_remote_arch(void)
1961 return ra_type;
1964 void print_asc(int level, const unsigned char *buf,int len)
1966 int i;
1967 for (i=0;i<len;i++)
1968 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1971 void dump_data(int level, const char *buf1,int len)
1973 const unsigned char *buf = (const unsigned char *)buf1;
1974 int i=0;
1975 if (len<=0) return;
1977 if (!DEBUGLVL(level)) return;
1979 DEBUGADD(level,("[%03X] ",i));
1980 for (i=0;i<len;) {
1981 DEBUGADD(level,("%02X ",(int)buf[i]));
1982 i++;
1983 if (i%8 == 0) DEBUGADD(level,(" "));
1984 if (i%16 == 0) {
1985 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1986 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1987 if (i<len) DEBUGADD(level,("[%03X] ",i));
1990 if (i%16) {
1991 int n;
1992 n = 16 - (i%16);
1993 DEBUGADD(level,(" "));
1994 if (n>8) DEBUGADD(level,(" "));
1995 while (n--) DEBUGADD(level,(" "));
1996 n = MIN(8,i%16);
1997 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1998 n = (i%16) - n;
1999 if (n>0) print_asc(level,&buf[i-n],n);
2000 DEBUGADD(level,("\n"));
2004 void dump_data_pw(const char *msg, const uchar * data, size_t len)
2006 #ifdef DEBUG_PASSWORD
2007 DEBUG(11, ("%s", msg));
2008 if (data != NULL && len > 0)
2010 dump_data(11, data, len);
2012 #endif
2015 char *tab_depth(int depth)
2017 static pstring spaces;
2018 memset(spaces, ' ', depth * 4);
2019 spaces[depth * 4] = 0;
2020 return spaces;
2023 /*****************************************************************************
2024 Provide a checksum on a string
2026 Input: s - the null-terminated character string for which the checksum
2027 will be calculated.
2029 Output: The checksum value calculated for s.
2030 *****************************************************************************/
2032 int str_checksum(const char *s)
2034 int res = 0;
2035 int c;
2036 int i=0;
2038 while(*s) {
2039 c = *s;
2040 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
2041 s++;
2042 i++;
2044 return(res);
2047 /*****************************************************************
2048 Zero a memory area then free it. Used to catch bugs faster.
2049 *****************************************************************/
2051 void zero_free(void *p, size_t size)
2053 memset(p, 0, size);
2054 SAFE_FREE(p);
2057 /*****************************************************************
2058 Set our open file limit to a requested max and return the limit.
2059 *****************************************************************/
2061 int set_maxfiles(int requested_max)
2063 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
2064 struct rlimit rlp;
2065 int saved_current_limit;
2067 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2068 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
2069 strerror(errno) ));
2070 /* just guess... */
2071 return requested_max;
2075 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
2076 * account for the extra fd we need
2077 * as well as the log files and standard
2078 * handles etc. Save the limit we want to set in case
2079 * we are running on an OS that doesn't support this limit (AIX)
2080 * which always returns RLIM_INFINITY for rlp.rlim_max.
2083 /* Try raising the hard (max) limit to the requested amount. */
2085 #if defined(RLIM_INFINITY)
2086 if (rlp.rlim_max != RLIM_INFINITY) {
2087 int orig_max = rlp.rlim_max;
2089 if ( rlp.rlim_max < requested_max )
2090 rlp.rlim_max = requested_max;
2092 /* This failing is not an error - many systems (Linux) don't
2093 support our default request of 10,000 open files. JRA. */
2095 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2096 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
2097 (int)rlp.rlim_max, strerror(errno) ));
2099 /* Set failed - restore original value from get. */
2100 rlp.rlim_max = orig_max;
2103 #endif
2105 /* Now try setting the soft (current) limit. */
2107 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
2109 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
2110 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
2111 (int)rlp.rlim_cur, strerror(errno) ));
2112 /* just guess... */
2113 return saved_current_limit;
2116 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
2117 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
2118 strerror(errno) ));
2119 /* just guess... */
2120 return saved_current_limit;
2123 #if defined(RLIM_INFINITY)
2124 if(rlp.rlim_cur == RLIM_INFINITY)
2125 return saved_current_limit;
2126 #endif
2128 if((int)rlp.rlim_cur > saved_current_limit)
2129 return saved_current_limit;
2131 return rlp.rlim_cur;
2132 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
2134 * No way to know - just guess...
2136 return requested_max;
2137 #endif
2140 /*****************************************************************
2141 Splits out the start of the key (HKLM or HKU) and the rest of the key.
2142 *****************************************************************/
2144 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
2146 pstring tmp;
2148 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
2149 return False;
2151 (*reg_type) = 0;
2153 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2155 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2156 (*reg_type) = HKEY_LOCAL_MACHINE;
2157 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2158 (*reg_type) = HKEY_USERS;
2159 else {
2160 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2161 return False;
2164 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2165 fstrcpy(key_name, tmp);
2166 else
2167 key_name[0] = 0;
2169 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2171 return True;
2174 /*****************************************************************
2175 Possibly replace mkstemp if it is broken.
2176 *****************************************************************/
2178 int smb_mkstemp(char *template)
2180 #if HAVE_SECURE_MKSTEMP
2181 return mkstemp(template);
2182 #else
2183 /* have a reasonable go at emulating it. Hope that
2184 the system mktemp() isn't completly hopeless */
2185 char *p = mktemp(template);
2186 if (!p)
2187 return -1;
2188 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2189 #endif
2192 /*****************************************************************
2193 malloc that aborts with smb_panic on fail or zero size.
2194 *****************************************************************/
2196 void *smb_xmalloc_array(size_t size, unsigned int count)
2198 void *p;
2199 if (size == 0)
2200 smb_panic("smb_xmalloc_array: called with zero size.\n");
2201 if (count >= MAX_ALLOC_SIZE/size) {
2202 smb_panic("smb_xmalloc: alloc size too large.\n");
2204 if ((p = SMB_MALLOC(size*count)) == NULL) {
2205 DEBUG(0, ("smb_xmalloc_array failed to allocate %lu * %lu bytes\n",
2206 (unsigned long)size, (unsigned long)count));
2207 smb_panic("smb_xmalloc_array: malloc fail.\n");
2209 return p;
2213 Memdup with smb_panic on fail.
2216 void *smb_xmemdup(const void *p, size_t size)
2218 void *p2;
2219 p2 = SMB_XMALLOC_ARRAY(unsigned char,size);
2220 memcpy(p2, p, size);
2221 return p2;
2225 strdup that aborts on malloc fail.
2228 char *smb_xstrdup(const char *s)
2230 #if defined(PARANOID_MALLOC_CHECKER)
2231 #ifdef strdup
2232 #undef strdup
2233 #endif
2234 #endif
2235 char *s1 = strdup(s);
2236 #if defined(PARANOID_MALLOC_CHECKER)
2237 #define strdup(s) __ERROR_DONT_USE_STRDUP_DIRECTLY
2238 #endif
2239 if (!s1)
2240 smb_panic("smb_xstrdup: malloc fail\n");
2241 return s1;
2245 strndup that aborts on malloc fail.
2248 char *smb_xstrndup(const char *s, size_t n)
2250 #if defined(PARANOID_MALLOC_CHECKER)
2251 #ifdef strndup
2252 #undef strndup
2253 #endif
2254 #endif
2255 char *s1 = strndup(s, n);
2256 #if defined(PARANOID_MALLOC_CHECKER)
2257 #define strndup(s,n) __ERROR_DONT_USE_STRNDUP_DIRECTLY
2258 #endif
2259 if (!s1)
2260 smb_panic("smb_xstrndup: malloc fail\n");
2261 return s1;
2265 vasprintf that aborts on malloc fail
2268 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2270 int n;
2271 va_list ap2;
2273 VA_COPY(ap2, ap);
2275 n = vasprintf(ptr, format, ap2);
2276 if (n == -1 || ! *ptr)
2277 smb_panic("smb_xvasprintf: out of memory");
2278 return n;
2281 /*****************************************************************
2282 Like strdup but for memory.
2283 *****************************************************************/
2285 void *memdup(const void *p, size_t size)
2287 void *p2;
2288 if (size == 0)
2289 return NULL;
2290 p2 = SMB_MALLOC(size);
2291 if (!p2)
2292 return NULL;
2293 memcpy(p2, p, size);
2294 return p2;
2297 /*****************************************************************
2298 Get local hostname and cache result.
2299 *****************************************************************/
2301 char *myhostname(void)
2303 static pstring ret;
2304 if (ret[0] == 0)
2305 get_myname(ret);
2306 return ret;
2309 /*****************************************************************
2310 A useful function for returning a path in the Samba lock directory.
2311 *****************************************************************/
2313 char *lock_path(const char *name)
2315 static pstring fname;
2317 pstrcpy(fname,lp_lockdir());
2318 trim_char(fname,'\0','/');
2320 if (!directory_exist(fname,NULL))
2321 mkdir(fname,0755);
2323 pstrcat(fname,"/");
2324 pstrcat(fname,name);
2326 return fname;
2329 /*****************************************************************
2330 A useful function for returning a path in the Samba pid directory.
2331 *****************************************************************/
2333 char *pid_path(const char *name)
2335 static pstring fname;
2337 pstrcpy(fname,lp_piddir());
2338 trim_char(fname,'\0','/');
2340 if (!directory_exist(fname,NULL))
2341 mkdir(fname,0755);
2343 pstrcat(fname,"/");
2344 pstrcat(fname,name);
2346 return fname;
2350 * @brief Returns an absolute path to a file in the Samba lib directory.
2352 * @param name File to find, relative to LIBDIR.
2354 * @retval Pointer to a static #pstring containing the full path.
2357 char *lib_path(const char *name)
2359 static pstring fname;
2360 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2361 return fname;
2365 * @brief Returns the platform specific shared library extension.
2367 * @retval Pointer to a static #fstring containing the extension.
2370 const char *shlib_ext(void)
2372 return dyn_SHLIBEXT;
2375 /*******************************************************************
2376 Given a filename - get its directory name
2377 NB: Returned in static storage. Caveats:
2378 o Not safe in thread environment.
2379 o Caller must not free.
2380 o If caller wishes to preserve, they should copy.
2381 ********************************************************************/
2383 char *parent_dirname(const char *path)
2385 static pstring dirpath;
2386 char *p;
2388 if (!path)
2389 return(NULL);
2391 pstrcpy(dirpath, path);
2392 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2393 if (!p) {
2394 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2395 } else {
2396 if (p == dirpath)
2397 ++p; /* For root "/", leave "/" in place */
2398 *p = '\0';
2400 return dirpath;
2404 /*******************************************************************
2405 Determine if a pattern contains any Microsoft wildcard characters.
2406 *******************************************************************/
2408 BOOL ms_has_wild(const char *s)
2410 char c;
2411 while ((c = *s++)) {
2412 switch (c) {
2413 case '*':
2414 case '?':
2415 case '<':
2416 case '>':
2417 case '"':
2418 return True;
2421 return False;
2424 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2426 smb_ucs2_t c;
2427 if (!s) return False;
2428 while ((c = *s++)) {
2429 switch (c) {
2430 case UCS2_CHAR('*'):
2431 case UCS2_CHAR('?'):
2432 case UCS2_CHAR('<'):
2433 case UCS2_CHAR('>'):
2434 case UCS2_CHAR('"'):
2435 return True;
2438 return False;
2441 /*******************************************************************
2442 A wrapper that handles case sensitivity and the special handling
2443 of the ".." name.
2444 *******************************************************************/
2446 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2448 if (strcmp(string,"..") == 0)
2449 string = ".";
2450 if (strcmp(pattern,".") == 0)
2451 return False;
2453 return ms_fnmatch(pattern, string, Protocol, is_case_sensitive) == 0;
2456 /*******************************************************************
2457 A wrapper that handles a list of patters and calls mask_match()
2458 on each. Returns True if any of the patterns match.
2459 *******************************************************************/
2461 BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
2463 while (listLen-- > 0) {
2464 if (mask_match(string, *list++, is_case_sensitive))
2465 return True;
2467 return False;
2470 /*********************************************************
2471 Recursive routine that is called by unix_wild_match.
2472 *********************************************************/
2474 static BOOL unix_do_match(const char *regexp, const char *str)
2476 const char *p;
2478 for( p = regexp; *p && *str; ) {
2480 switch(*p) {
2481 case '?':
2482 str++;
2483 p++;
2484 break;
2486 case '*':
2489 * Look for a character matching
2490 * the one after the '*'.
2492 p++;
2493 if(!*p)
2494 return True; /* Automatic match */
2495 while(*str) {
2497 while(*str && (*p != *str))
2498 str++;
2501 * Patch from weidel@multichart.de. In the case of the regexp
2502 * '*XX*' we want to ensure there are at least 2 'X' characters
2503 * in the string after the '*' for a match to be made.
2507 int matchcount=0;
2510 * Eat all the characters that match, but count how many there were.
2513 while(*str && (*p == *str)) {
2514 str++;
2515 matchcount++;
2519 * Now check that if the regexp had n identical characters that
2520 * matchcount had at least that many matches.
2523 while ( *(p+1) && (*(p+1) == *p)) {
2524 p++;
2525 matchcount--;
2528 if ( matchcount <= 0 )
2529 return False;
2532 str--; /* We've eaten the match char after the '*' */
2534 if(unix_do_match(p, str))
2535 return True;
2537 if(!*str)
2538 return False;
2539 else
2540 str++;
2542 return False;
2544 default:
2545 if(*str != *p)
2546 return False;
2547 str++;
2548 p++;
2549 break;
2553 if(!*p && !*str)
2554 return True;
2556 if (!*p && str[0] == '.' && str[1] == 0)
2557 return(True);
2559 if (!*str && *p == '?') {
2560 while (*p == '?')
2561 p++;
2562 return(!*p);
2565 if(!*str && (*p == '*' && p[1] == '\0'))
2566 return True;
2568 return False;
2571 /*******************************************************************
2572 Simple case insensitive interface to a UNIX wildcard matcher.
2573 *******************************************************************/
2575 BOOL unix_wild_match(const char *pattern, const char *string)
2577 pstring p2, s2;
2578 char *p;
2580 pstrcpy(p2, pattern);
2581 pstrcpy(s2, string);
2582 strlower_m(p2);
2583 strlower_m(s2);
2585 /* Remove any *? and ** from the pattern as they are meaningless */
2586 for(p = p2; *p; p++)
2587 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2588 pstrcpy( &p[1], &p[2]);
2590 if (strequal(p2,"*"))
2591 return True;
2593 return unix_do_match(p2, s2) == 0;
2596 /**********************************************************************
2597 Converts a name to a fully qalified domain name.
2598 ***********************************************************************/
2600 void name_to_fqdn(fstring fqdn, const char *name)
2602 struct hostent *hp = sys_gethostbyname(name);
2603 if ( hp && hp->h_name && *hp->h_name ) {
2604 DEBUG(10,("name_to_fqdn: lookup for %s -> %s.\n", name, hp->h_name));
2605 fstrcpy(fqdn,hp->h_name);
2606 } else {
2607 DEBUG(10,("name_to_fqdn: lookup for %s failed.\n", name));
2608 fstrcpy(fqdn, name);
2612 #ifdef __INSURE__
2614 /*******************************************************************
2615 This routine is a trick to immediately catch errors when debugging
2616 with insure. A xterm with a gdb is popped up when insure catches
2617 a error. It is Linux specific.
2618 ********************************************************************/
2620 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2622 static int (*fn)();
2623 int ret;
2624 char pidstr[10];
2625 /* you can get /usr/bin/backtrace from
2626 http://samba.org/ftp/unpacked/junkcode/backtrace */
2627 pstring cmd = "/usr/bin/backtrace %d";
2629 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2630 pstring_sub(cmd, "%d", pidstr);
2632 if (!fn) {
2633 static void *h;
2634 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2635 fn = dlsym(h, "_Insure_trap_error");
2637 if (!h || h == _Insure_trap_error) {
2638 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2639 fn = dlsym(h, "_Insure_trap_error");
2643 ret = fn(a1, a2, a3, a4, a5, a6);
2645 system(cmd);
2647 return ret;
2649 #endif