Merge of 64-bit printf warning fixes.
[Samba/gebeck_regimport.git] / source3 / lib / util.c
blobce1389c8e9c632a736bda7f4b5f052789d829764
1 /*
2 Unix SMB/CIFS implementation.
3 Samba utility functions
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2002
6 Copyright (C) Simo Sorce 2001
7 Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include "includes.h"
26 #if (defined(HAVE_NETGROUP) && defined (WITH_AUTOMOUNT))
27 #ifdef WITH_NISPLUS_HOME
28 #ifdef BROKEN_NISPLUS_INCLUDE_FILES
30 * The following lines are needed due to buggy include files
31 * in Solaris 2.6 which define GROUP in both /usr/include/sys/acl.h and
32 * also in /usr/include/rpcsvc/nis.h. The definitions conflict. JRA.
33 * Also GROUP_OBJ is defined as 0x4 in /usr/include/sys/acl.h and as
34 * an enum in /usr/include/rpcsvc/nis.h.
37 #if defined(GROUP)
38 #undef GROUP
39 #endif
41 #if defined(GROUP_OBJ)
42 #undef GROUP_OBJ
43 #endif
45 #endif /* BROKEN_NISPLUS_INCLUDE_FILES */
47 #include <rpcsvc/nis.h>
49 #else /* !WITH_NISPLUS_HOME */
51 #include "rpcsvc/ypclnt.h"
53 #endif /* WITH_NISPLUS_HOME */
54 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
56 int Protocol = PROTOCOL_COREPLUS;
58 /* a default finfo structure to ensure all fields are sensible */
59 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
61 /* this is used by the chaining code */
62 int chain_size = 0;
64 int trans_num = 0;
67 case handling on filenames
69 int case_default = CASE_LOWER;
71 /* the following control case operations - they are put here so the
72 client can link easily */
73 BOOL case_sensitive;
74 BOOL case_preserve;
75 BOOL use_mangled_map = False;
76 BOOL short_case_preserve;
77 BOOL case_mangle;
79 static enum remote_arch_types ra_type = RA_UNKNOWN;
80 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
82 /***********************************************************************
83 Definitions for all names.
84 ***********************************************************************/
86 static char *smb_myname;
87 static char *smb_myworkgroup;
88 static char *smb_scope;
89 static int smb_num_netbios_names;
90 static char **smb_my_netbios_names;
92 /***********************************************************************
93 Allocate and set myname. Ensure upper case.
94 ***********************************************************************/
96 BOOL set_global_myname(const char *myname)
98 SAFE_FREE(smb_myname);
99 smb_myname = strdup(myname);
100 if (!smb_myname)
101 return False;
102 strupper_m(smb_myname);
103 return True;
106 const char *global_myname(void)
108 return smb_myname;
111 /***********************************************************************
112 Allocate and set myworkgroup. Ensure upper case.
113 ***********************************************************************/
115 BOOL set_global_myworkgroup(const char *myworkgroup)
117 SAFE_FREE(smb_myworkgroup);
118 smb_myworkgroup = strdup(myworkgroup);
119 if (!smb_myworkgroup)
120 return False;
121 strupper_m(smb_myworkgroup);
122 return True;
125 const char *lp_workgroup(void)
127 return smb_myworkgroup;
130 /***********************************************************************
131 Allocate and set scope. Ensure upper case.
132 ***********************************************************************/
134 BOOL set_global_scope(const char *scope)
136 SAFE_FREE(smb_scope);
137 smb_scope = strdup(scope);
138 if (!smb_scope)
139 return False;
140 strupper_m(smb_scope);
141 return True;
144 /*********************************************************************
145 Ensure scope is never null string.
146 *********************************************************************/
148 const char *global_scope(void)
150 if (!smb_scope)
151 set_global_scope("");
152 return smb_scope;
155 static void free_netbios_names_array(void)
157 int i;
159 for (i = 0; i < smb_num_netbios_names; i++)
160 SAFE_FREE(smb_my_netbios_names[i]);
162 SAFE_FREE(smb_my_netbios_names);
163 smb_num_netbios_names = 0;
166 static BOOL allocate_my_netbios_names_array(size_t number)
168 free_netbios_names_array();
170 smb_num_netbios_names = number + 1;
171 smb_my_netbios_names = (char **)malloc( sizeof(char *) * smb_num_netbios_names );
173 if (!smb_my_netbios_names)
174 return False;
176 memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
177 return True;
180 static BOOL set_my_netbios_names(const char *name, int i)
182 SAFE_FREE(smb_my_netbios_names[i]);
184 smb_my_netbios_names[i] = strdup(name);
185 if (!smb_my_netbios_names[i])
186 return False;
187 strupper_m(smb_my_netbios_names[i]);
188 return True;
191 const char *my_netbios_names(int i)
193 return smb_my_netbios_names[i];
196 BOOL set_netbios_aliases(const char **str_array)
198 size_t namecount;
200 /* Work out the max number of netbios aliases that we have */
201 for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
204 if ( global_myname() && *global_myname())
205 namecount++;
207 /* Allocate space for the netbios aliases */
208 if (!allocate_my_netbios_names_array(namecount))
209 return False;
211 /* Use the global_myname string first */
212 namecount=0;
213 if ( global_myname() && *global_myname()) {
214 set_my_netbios_names( global_myname(), namecount );
215 namecount++;
218 if (str_array) {
219 size_t i;
220 for ( i = 0; str_array[i] != NULL; i++) {
221 size_t n;
222 BOOL duplicate = False;
224 /* Look for duplicates */
225 for( n=0; n<namecount; n++ ) {
226 if( strequal( str_array[i], my_netbios_names(n) ) ) {
227 duplicate = True;
228 break;
231 if (!duplicate) {
232 if (!set_my_netbios_names(str_array[i], namecount))
233 return False;
234 namecount++;
238 return True;
241 /****************************************************************************
242 Common name initialization code.
243 ****************************************************************************/
245 BOOL init_names(void)
247 extern fstring local_machine;
248 char *p;
249 int n;
251 if (global_myname() == NULL || *global_myname() == '\0') {
252 if (!set_global_myname(myhostname())) {
253 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
254 return False;
258 if (!set_netbios_aliases(lp_netbios_aliases())) {
259 DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
260 return False;
263 fstrcpy( local_machine, global_myname() );
264 trim_char( local_machine, ' ', ' ' );
265 p = strchr( local_machine, ' ' );
266 if (p)
267 *p = 0;
268 strlower_m( local_machine );
270 DEBUG( 5, ("Netbios name list:-\n") );
271 for( n=0; my_netbios_names(n); n++ )
272 DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
274 return( True );
277 /**************************************************************************n
278 Find a suitable temporary directory. The result should be copied immediately
279 as it may be overwritten by a subsequent call.
280 ****************************************************************************/
282 const char *tmpdir(void)
284 char *p;
285 if ((p = getenv("TMPDIR")))
286 return p;
287 return "/tmp";
290 /****************************************************************************
291 Determine whether we are in the specified group.
292 ****************************************************************************/
294 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, const gid_t *groups)
296 int i;
298 if (group == current_gid)
299 return(True);
301 for (i=0;i<ngroups;i++)
302 if (group == groups[i])
303 return(True);
305 return(False);
308 /****************************************************************************
309 Like atoi but gets the value up to the separator character.
310 ****************************************************************************/
312 static const char *Atoic(const char *p, int *n, const char *c)
314 if (!isdigit((int)*p)) {
315 DEBUG(5, ("Atoic: malformed number\n"));
316 return NULL;
319 (*n) = atoi(p);
321 while ((*p) && isdigit((int)*p))
322 p++;
324 if (strchr_m(c, *p) == NULL) {
325 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
326 return NULL;
329 return p;
332 /*************************************************************************
333 Reads a list of numbers.
334 *************************************************************************/
336 const char *get_numlist(const char *p, uint32 **num, int *count)
338 int val;
340 if (num == NULL || count == NULL)
341 return NULL;
343 (*count) = 0;
344 (*num ) = NULL;
346 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
347 uint32 *tn;
349 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
350 if (tn == NULL) {
351 SAFE_FREE(*num);
352 return NULL;
353 } else
354 (*num) = tn;
355 (*num)[(*count)] = val;
356 (*count)++;
357 p++;
360 return p;
363 /*******************************************************************
364 Check if a file exists - call vfs_file_exist for samba files.
365 ********************************************************************/
367 BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
369 SMB_STRUCT_STAT st;
370 if (!sbuf)
371 sbuf = &st;
373 if (sys_stat(fname,sbuf) != 0)
374 return(False);
376 return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
379 /*******************************************************************
380 Check a files mod time.
381 ********************************************************************/
383 time_t file_modtime(const char *fname)
385 SMB_STRUCT_STAT st;
387 if (sys_stat(fname,&st) != 0)
388 return(0);
390 return(st.st_mtime);
393 /*******************************************************************
394 Check if a directory exists.
395 ********************************************************************/
397 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
399 SMB_STRUCT_STAT st2;
400 BOOL ret;
402 if (!st)
403 st = &st2;
405 if (sys_stat(dname,st) != 0)
406 return(False);
408 ret = S_ISDIR(st->st_mode);
409 if(!ret)
410 errno = ENOTDIR;
411 return ret;
414 /*******************************************************************
415 Returns the size in bytes of the named file.
416 ********************************************************************/
418 SMB_OFF_T get_file_size(char *file_name)
420 SMB_STRUCT_STAT buf;
421 buf.st_size = 0;
422 if(sys_stat(file_name,&buf) != 0)
423 return (SMB_OFF_T)-1;
424 return(buf.st_size);
427 /*******************************************************************
428 Return a string representing an attribute for a file.
429 ********************************************************************/
431 char *attrib_string(uint16 mode)
433 static fstring attrstr;
435 attrstr[0] = 0;
437 if (mode & aVOLID) fstrcat(attrstr,"V");
438 if (mode & aDIR) fstrcat(attrstr,"D");
439 if (mode & aARCH) fstrcat(attrstr,"A");
440 if (mode & aHIDDEN) fstrcat(attrstr,"H");
441 if (mode & aSYSTEM) fstrcat(attrstr,"S");
442 if (mode & aRONLY) fstrcat(attrstr,"R");
444 return(attrstr);
447 /*******************************************************************
448 Show a smb message structure.
449 ********************************************************************/
451 void show_msg(char *buf)
453 int i;
454 int bcc=0;
456 if (!DEBUGLVL(5))
457 return;
459 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
460 smb_len(buf),
461 (int)CVAL(buf,smb_com),
462 (int)CVAL(buf,smb_rcls),
463 (int)CVAL(buf,smb_reh),
464 (int)SVAL(buf,smb_err),
465 (int)CVAL(buf,smb_flg),
466 (int)SVAL(buf,smb_flg2)));
467 DEBUGADD(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\n",
468 (int)SVAL(buf,smb_tid),
469 (int)SVAL(buf,smb_pid),
470 (int)SVAL(buf,smb_uid),
471 (int)SVAL(buf,smb_mid)));
472 DEBUGADD(5,("smt_wct=%d\n",(int)CVAL(buf,smb_wct)));
474 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
475 DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
476 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
478 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
480 DEBUGADD(5,("smb_bcc=%d\n",bcc));
482 if (DEBUGLEVEL < 10)
483 return;
485 if (DEBUGLEVEL < 50)
486 bcc = MIN(bcc, 512);
488 dump_data(10, smb_buf(buf), bcc);
491 /*******************************************************************
492 Set the length and marker of an smb packet.
493 ********************************************************************/
495 void smb_setlen(char *buf,int len)
497 _smb_setlen(buf,len);
499 SCVAL(buf,4,0xFF);
500 SCVAL(buf,5,'S');
501 SCVAL(buf,6,'M');
502 SCVAL(buf,7,'B');
505 /*******************************************************************
506 Setup the word count and byte count for a smb message.
507 ********************************************************************/
509 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
511 if (zero)
512 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
513 SCVAL(buf,smb_wct,num_words);
514 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
515 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
516 return (smb_size + num_words*2 + num_bytes);
519 /*******************************************************************
520 Setup only the byte count for a smb message.
521 ********************************************************************/
523 int set_message_bcc(char *buf,int num_bytes)
525 int num_words = CVAL(buf,smb_wct);
526 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
527 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
528 return (smb_size + num_words*2 + num_bytes);
531 /*******************************************************************
532 Setup only the byte count for a smb message, using the end of the
533 message as a marker.
534 ********************************************************************/
536 int set_message_end(void *outbuf,void *end_ptr)
538 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
541 /*******************************************************************
542 Reduce a file name, removing .. elements.
543 ********************************************************************/
545 void dos_clean_name(char *s)
547 char *p=NULL;
549 DEBUG(3,("dos_clean_name [%s]\n",s));
551 /* remove any double slashes */
552 all_string_sub(s, "\\\\", "\\", 0);
554 while ((p = strstr(s,"\\..\\")) != NULL) {
555 pstring s1;
557 *p = 0;
558 pstrcpy(s1,p+3);
560 if ((p=strrchr_m(s,'\\')) != NULL)
561 *p = 0;
562 else
563 *s = 0;
564 pstrcat(s,s1);
567 trim_string(s,NULL,"\\..");
569 all_string_sub(s, "\\.\\", "\\", 0);
572 /*******************************************************************
573 Reduce a file name, removing .. elements.
574 ********************************************************************/
576 void unix_clean_name(char *s)
578 char *p=NULL;
580 DEBUG(3,("unix_clean_name [%s]\n",s));
582 /* remove any double slashes */
583 all_string_sub(s, "//","/", 0);
585 /* Remove leading ./ characters */
586 if(strncmp(s, "./", 2) == 0) {
587 trim_string(s, "./", NULL);
588 if(*s == 0)
589 pstrcpy(s,"./");
592 while ((p = strstr(s,"/../")) != NULL) {
593 pstring s1;
595 *p = 0;
596 pstrcpy(s1,p+3);
598 if ((p=strrchr_m(s,'/')) != NULL)
599 *p = 0;
600 else
601 *s = 0;
602 pstrcat(s,s1);
605 trim_string(s,NULL,"/..");
608 /****************************************************************************
609 Make a dir struct.
610 ****************************************************************************/
612 void make_dir_struct(char *buf, const char *mask, const char *fname,SMB_OFF_T size,int mode,time_t date)
614 char *p;
615 pstring mask2;
617 pstrcpy(mask2,mask);
619 if ((mode & aDIR) != 0)
620 size = 0;
622 memset(buf+1,' ',11);
623 if ((p = strchr_m(mask2,'.')) != NULL) {
624 *p = 0;
625 push_ascii(buf+1,mask2,8, 0);
626 push_ascii(buf+9,p+1,3, 0);
627 *p = '.';
628 } else
629 push_ascii(buf+1,mask2,11, 0);
631 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
632 SCVAL(buf,21,mode);
633 put_dos_date(buf,22,date);
634 SSVAL(buf,26,size & 0xFFFF);
635 SSVAL(buf,28,(size >> 16)&0xFFFF);
636 push_ascii(buf+30,fname,12, case_sensitive ? 0 : STR_UPPER);
637 DEBUG(8,("put name [%s] from [%s] into dir struct\n",buf+30, fname));
640 /*******************************************************************
641 Close the low 3 fd's and open dev/null in their place.
642 ********************************************************************/
644 void close_low_fds(BOOL stderr_too)
646 #ifndef VALGRIND
647 int fd;
648 int i;
650 close(0);
651 close(1);
653 if (stderr_too)
654 close(2);
656 /* try and use up these file descriptors, so silly
657 library routines writing to stdout etc won't cause havoc */
658 for (i=0;i<3;i++) {
659 if (i == 2 && !stderr_too)
660 continue;
662 fd = sys_open("/dev/null",O_RDWR,0);
663 if (fd < 0)
664 fd = sys_open("/dev/null",O_WRONLY,0);
665 if (fd < 0) {
666 DEBUG(0,("Can't open /dev/null\n"));
667 return;
669 if (fd != i) {
670 DEBUG(0,("Didn't get file descriptor %d\n",i));
671 return;
674 #endif
677 /****************************************************************************
678 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
679 else
680 if SYSV use O_NDELAY
681 if BSD use FNDELAY
682 ****************************************************************************/
684 int set_blocking(int fd, BOOL set)
686 int val;
687 #ifdef O_NONBLOCK
688 #define FLAG_TO_SET O_NONBLOCK
689 #else
690 #ifdef SYSV
691 #define FLAG_TO_SET O_NDELAY
692 #else /* BSD */
693 #define FLAG_TO_SET FNDELAY
694 #endif
695 #endif
697 if((val = sys_fcntl_long(fd, F_GETFL, 0)) == -1)
698 return -1;
699 if(set) /* Turn blocking on - ie. clear nonblock flag */
700 val &= ~FLAG_TO_SET;
701 else
702 val |= FLAG_TO_SET;
703 return sys_fcntl_long( fd, F_SETFL, val);
704 #undef FLAG_TO_SET
707 /****************************************************************************
708 Transfer some data between two fd's.
709 ****************************************************************************/
711 #ifndef TRANSFER_BUF_SIZE
712 #define TRANSFER_BUF_SIZE 65536
713 #endif
715 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
716 ssize_t (*write_fn)(int, const void *, size_t))
718 char *buf;
719 size_t total = 0;
720 ssize_t read_ret;
721 ssize_t write_ret;
722 size_t num_to_read_thistime;
723 size_t num_written = 0;
725 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
726 return -1;
728 while (total < n) {
729 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
731 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
732 if (read_ret == -1) {
733 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
734 SAFE_FREE(buf);
735 return -1;
737 if (read_ret == 0)
738 break;
740 num_written = 0;
742 while (num_written < read_ret) {
743 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
745 if (write_ret == -1) {
746 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
747 SAFE_FREE(buf);
748 return -1;
750 if (write_ret == 0)
751 return (ssize_t)total;
753 num_written += (size_t)write_ret;
756 total += (size_t)read_ret;
759 SAFE_FREE(buf);
760 return (ssize_t)total;
763 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
765 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, sys_read, sys_write);
768 /*******************************************************************
769 Sleep for a specified number of milliseconds.
770 ********************************************************************/
772 void msleep(unsigned int t)
774 unsigned int tdiff=0;
775 struct timeval tval,t1,t2;
776 fd_set fds;
778 GetTimeOfDay(&t1);
779 GetTimeOfDay(&t2);
781 while (tdiff < t) {
782 tval.tv_sec = (t-tdiff)/1000;
783 tval.tv_usec = 1000*((t-tdiff)%1000);
785 /* Never wait for more than 1 sec. */
786 if (tval.tv_sec > 1) {
787 tval.tv_sec = 1;
788 tval.tv_usec = 0;
791 FD_ZERO(&fds);
792 errno = 0;
793 sys_select_intr(0,&fds,NULL,NULL,&tval);
795 GetTimeOfDay(&t2);
796 if (t2.tv_sec < t1.tv_sec) {
797 /* Someone adjusted time... */
798 t1 = t2;
801 tdiff = TvalDiff(&t1,&t2);
805 /****************************************************************************
806 Become a daemon, discarding the controlling terminal.
807 ****************************************************************************/
809 void become_daemon(BOOL Fork)
811 if (Fork) {
812 if (sys_fork()) {
813 _exit(0);
817 /* detach from the terminal */
818 #ifdef HAVE_SETSID
819 setsid();
820 #elif defined(TIOCNOTTY)
822 int i = sys_open("/dev/tty", O_RDWR, 0);
823 if (i != -1) {
824 ioctl(i, (int) TIOCNOTTY, (char *)0);
825 close(i);
828 #endif /* HAVE_SETSID */
830 /* Close fd's 0,1,2. Needed if started by rsh */
831 close_low_fds(False); /* Don't close stderr, let the debug system
832 attach it to the logfile */
835 /****************************************************************************
836 Put up a yes/no prompt.
837 ****************************************************************************/
839 BOOL yesno(char *p)
841 pstring ans;
842 printf("%s",p);
844 if (!fgets(ans,sizeof(ans)-1,stdin))
845 return(False);
847 if (*ans == 'y' || *ans == 'Y')
848 return(True);
850 return(False);
853 /****************************************************************************
854 Expand a pointer to be a particular size.
855 ****************************************************************************/
857 void *Realloc(void *p,size_t size)
859 void *ret=NULL;
861 if (size == 0) {
862 SAFE_FREE(p);
863 DEBUG(5,("Realloc asked for 0 bytes\n"));
864 return NULL;
867 if (!p)
868 ret = (void *)malloc(size);
869 else
870 ret = (void *)realloc(p,size);
872 if (!ret)
873 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
875 return(ret);
878 void *Realloc_zero(void *ptr, size_t size)
880 void *tptr = NULL;
882 tptr = Realloc(ptr, size);
883 if(tptr == NULL)
884 return NULL;
886 memset((char *)tptr,'\0',size);
888 return tptr;
891 /****************************************************************************
892 Free memory, checks for NULL.
893 Use directly SAFE_FREE()
894 Exists only because we need to pass a function pointer somewhere --SSS
895 ****************************************************************************/
897 void safe_free(void *p)
899 SAFE_FREE(p);
902 /****************************************************************************
903 Get my own name and IP.
904 ****************************************************************************/
906 BOOL get_myname(char *my_name)
908 pstring hostname;
910 *hostname = 0;
912 /* get my host name */
913 if (gethostname(hostname, sizeof(hostname)) == -1) {
914 DEBUG(0,("gethostname failed\n"));
915 return False;
918 /* Ensure null termination. */
919 hostname[sizeof(hostname)-1] = '\0';
921 if (my_name) {
922 /* split off any parts after an initial . */
923 char *p = strchr_m(hostname,'.');
925 if (p)
926 *p = 0;
928 fstrcpy(my_name,hostname);
931 return(True);
934 /****************************************************************************
935 Get my own name, including domain.
936 ****************************************************************************/
938 BOOL get_myfullname(char *my_name)
940 pstring hostname;
942 *hostname = 0;
944 /* get my host name */
945 if (gethostname(hostname, sizeof(hostname)) == -1) {
946 DEBUG(0,("gethostname failed\n"));
947 return False;
950 /* Ensure null termination. */
951 hostname[sizeof(hostname)-1] = '\0';
953 if (my_name)
954 fstrcpy(my_name, hostname);
955 return True;
958 /****************************************************************************
959 Get my own domain name.
960 ****************************************************************************/
962 BOOL get_mydomname(fstring my_domname)
964 pstring hostname;
965 char *p;
966 struct hostent *hp;
968 *hostname = 0;
969 /* get my host name */
970 if (gethostname(hostname, sizeof(hostname)) == -1) {
971 DEBUG(0,("gethostname failed\n"));
972 return False;
975 /* Ensure null termination. */
976 hostname[sizeof(hostname)-1] = '\0';
979 p = strchr_m(hostname, '.');
981 if (p) {
982 p++;
984 if (my_domname)
985 fstrcpy(my_domname, p);
988 if (!(hp = sys_gethostbyname(hostname))) {
989 return False;
992 p = strchr_m(hp->h_name, '.');
994 if (p) {
995 p++;
997 if (my_domname)
998 fstrcpy(my_domname, p);
999 return True;
1002 return False;
1005 /****************************************************************************
1006 Interpret a protocol description string, with a default.
1007 ****************************************************************************/
1009 int interpret_protocol(const char *str,int def)
1011 if (strequal(str,"NT1"))
1012 return(PROTOCOL_NT1);
1013 if (strequal(str,"LANMAN2"))
1014 return(PROTOCOL_LANMAN2);
1015 if (strequal(str,"LANMAN1"))
1016 return(PROTOCOL_LANMAN1);
1017 if (strequal(str,"CORE"))
1018 return(PROTOCOL_CORE);
1019 if (strequal(str,"COREPLUS"))
1020 return(PROTOCOL_COREPLUS);
1021 if (strequal(str,"CORE+"))
1022 return(PROTOCOL_COREPLUS);
1024 DEBUG(0,("Unrecognised protocol level %s\n",str));
1026 return(def);
1029 /****************************************************************************
1030 Return true if a string could be a pure IP address.
1031 ****************************************************************************/
1033 BOOL is_ipaddress(const char *str)
1035 BOOL pure_address = True;
1036 int i;
1038 for (i=0; pure_address && str[i]; i++)
1039 if (!(isdigit((int)str[i]) || str[i] == '.'))
1040 pure_address = False;
1042 /* Check that a pure number is not misinterpreted as an IP */
1043 pure_address = pure_address && (strchr_m(str, '.') != NULL);
1045 return pure_address;
1048 /****************************************************************************
1049 Interpret an internet address or name into an IP address in 4 byte form.
1050 ****************************************************************************/
1052 uint32 interpret_addr(const char *str)
1054 struct hostent *hp;
1055 uint32 res;
1057 if (strcmp(str,"0.0.0.0") == 0)
1058 return(0);
1059 if (strcmp(str,"255.255.255.255") == 0)
1060 return(0xFFFFFFFF);
1062 /* if it's in the form of an IP address then get the lib to interpret it */
1063 if (is_ipaddress(str)) {
1064 res = inet_addr(str);
1065 } else {
1066 /* otherwise assume it's a network name of some sort and use
1067 sys_gethostbyname */
1068 if ((hp = sys_gethostbyname(str)) == 0) {
1069 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
1070 return 0;
1073 if(hp->h_addr == NULL) {
1074 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
1075 return 0;
1077 putip((char *)&res,(char *)hp->h_addr);
1080 if (res == (uint32)-1)
1081 return(0);
1083 return(res);
1086 /*******************************************************************
1087 A convenient addition to interpret_addr().
1088 ******************************************************************/
1090 struct in_addr *interpret_addr2(const char *str)
1092 static struct in_addr ret;
1093 uint32 a = interpret_addr(str);
1094 ret.s_addr = a;
1095 return(&ret);
1098 /*******************************************************************
1099 Check if an IP is the 0.0.0.0.
1100 ******************************************************************/
1102 BOOL is_zero_ip(struct in_addr ip)
1104 uint32 a;
1105 putip((char *)&a,(char *)&ip);
1106 return(a == 0);
1109 /*******************************************************************
1110 Set an IP to 0.0.0.0.
1111 ******************************************************************/
1113 void zero_ip(struct in_addr *ip)
1115 static BOOL init;
1116 static struct in_addr ipzero;
1118 if (!init) {
1119 ipzero = *interpret_addr2("0.0.0.0");
1120 init = True;
1123 *ip = ipzero;
1126 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
1127 /******************************************************************
1128 Remove any mount options such as -rsize=2048,wsize=2048 etc.
1129 Based on a fix from <Thomas.Hepper@icem.de>.
1130 *******************************************************************/
1132 static void strip_mount_options( pstring *str)
1134 if (**str == '-') {
1135 char *p = *str;
1136 while(*p && !isspace(*p))
1137 p++;
1138 while(*p && isspace(*p))
1139 p++;
1140 if(*p) {
1141 pstring tmp_str;
1143 pstrcpy(tmp_str, p);
1144 pstrcpy(*str, tmp_str);
1149 /*******************************************************************
1150 Patch from jkf@soton.ac.uk
1151 Split Luke's automount_server into YP lookup and string splitter
1152 so can easily implement automount_path().
1153 As we may end up doing both, cache the last YP result.
1154 *******************************************************************/
1156 #ifdef WITH_NISPLUS_HOME
1157 char *automount_lookup(const char *user_name)
1159 static fstring last_key = "";
1160 static pstring last_value = "";
1162 char *nis_map = (char *)lp_nis_home_map_name();
1164 char buffer[NIS_MAXATTRVAL + 1];
1165 nis_result *result;
1166 nis_object *object;
1167 entry_obj *entry;
1169 if (strcmp(user_name, last_key)) {
1170 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
1171 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
1173 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
1174 if (result->status != NIS_SUCCESS) {
1175 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
1176 fstrcpy(last_key, ""); pstrcpy(last_value, "");
1177 } else {
1178 object = result->objects.objects_val;
1179 if (object->zo_data.zo_type == ENTRY_OBJ) {
1180 entry = &object->zo_data.objdata_u.en_data;
1181 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
1182 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
1184 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
1185 pstring_sub(last_value, "&", user_name);
1186 fstrcpy(last_key, user_name);
1190 nis_freeresult(result);
1193 strip_mount_options(&last_value);
1195 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
1196 return last_value;
1198 #else /* WITH_NISPLUS_HOME */
1200 char *automount_lookup(const char *user_name)
1202 static fstring last_key = "";
1203 static pstring last_value = "";
1205 int nis_error; /* returned by yp all functions */
1206 char *nis_result; /* yp_match inits this */
1207 int nis_result_len; /* and set this */
1208 char *nis_domain; /* yp_get_default_domain inits this */
1209 char *nis_map = (char *)lp_nis_home_map_name();
1211 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
1212 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
1213 return last_value;
1216 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
1218 if (!strcmp(user_name, last_key)) {
1219 nis_result = last_value;
1220 nis_result_len = strlen(last_value);
1221 nis_error = 0;
1222 } else {
1223 if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
1224 &nis_result, &nis_result_len)) == 0) {
1225 if (!nis_error && nis_result_len >= sizeof(pstring)) {
1226 nis_result_len = sizeof(pstring)-1;
1228 fstrcpy(last_key, user_name);
1229 strncpy(last_value, nis_result, nis_result_len);
1230 last_value[nis_result_len] = '\0';
1231 strip_mount_options(&last_value);
1233 } else if(nis_error == YPERR_KEY) {
1235 /* If Key lookup fails user home server is not in nis_map
1236 use default information for server, and home directory */
1237 last_value[0] = 0;
1238 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
1239 user_name, nis_map));
1240 DEBUG(3, ("using defaults for server and home directory\n"));
1241 } else {
1242 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
1243 yperr_string(nis_error), user_name, nis_map));
1247 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
1248 return last_value;
1250 #endif /* WITH_NISPLUS_HOME */
1251 #endif
1253 /*******************************************************************
1254 Are two IPs on the same subnet?
1255 ********************************************************************/
1257 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
1259 uint32 net1,net2,nmask;
1261 nmask = ntohl(mask.s_addr);
1262 net1 = ntohl(ip1.s_addr);
1263 net2 = ntohl(ip2.s_addr);
1265 return((net1 & nmask) == (net2 & nmask));
1269 /****************************************************************************
1270 Check if a process exists. Does this work on all unixes?
1271 ****************************************************************************/
1273 BOOL process_exists(pid_t pid)
1275 /* Doing kill with a non-positive pid causes messages to be
1276 * sent to places we don't want. */
1277 SMB_ASSERT(pid > 0);
1278 return(kill(pid,0) == 0 || errno != ESRCH);
1281 /*******************************************************************
1282 Convert a uid into a user name.
1283 ********************************************************************/
1285 const char *uidtoname(uid_t uid)
1287 static fstring name;
1288 struct passwd *pass;
1290 pass = getpwuid_alloc(uid);
1291 if (pass) {
1292 fstrcpy(name, pass->pw_name);
1293 passwd_free(&pass);
1294 } else {
1295 slprintf(name, sizeof(name) - 1, "%ld",(long int)uid);
1297 return name;
1301 /*******************************************************************
1302 Convert a gid into a group name.
1303 ********************************************************************/
1305 char *gidtoname(gid_t gid)
1307 static fstring name;
1308 struct group *grp;
1310 grp = getgrgid(gid);
1311 if (grp)
1312 return(grp->gr_name);
1313 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1314 return(name);
1317 /*******************************************************************
1318 Convert a user name into a uid.
1319 ********************************************************************/
1321 uid_t nametouid(const char *name)
1323 struct passwd *pass;
1324 char *p;
1325 uid_t u;
1327 pass = getpwnam_alloc(name);
1328 if (pass) {
1329 u = pass->pw_uid;
1330 passwd_free(&pass);
1331 return u;
1334 u = (uid_t)strtol(name, &p, 0);
1335 if ((p != name) && (*p == '\0'))
1336 return u;
1338 return (uid_t)-1;
1341 /*******************************************************************
1342 Convert a name to a gid_t if possible. Return -1 if not a group.
1343 ********************************************************************/
1345 gid_t nametogid(const char *name)
1347 struct group *grp;
1348 char *p;
1349 gid_t g;
1351 g = (gid_t)strtol(name, &p, 0);
1352 if ((p != name) && (*p == '\0'))
1353 return g;
1355 grp = sys_getgrnam(name);
1356 if (grp)
1357 return(grp->gr_gid);
1358 return (gid_t)-1;
1361 /*******************************************************************
1362 Something really nasty happened - panic !
1363 ********************************************************************/
1365 void smb_panic(const char *why)
1367 char *cmd;
1368 int result;
1369 #ifdef HAVE_BACKTRACE_SYMBOLS
1370 void *backtrace_stack[BACKTRACE_STACK_SIZE];
1371 size_t backtrace_size;
1372 char **backtrace_strings;
1373 #endif
1375 #ifdef DEVELOPER
1377 extern char *global_clobber_region_function;
1378 extern unsigned int global_clobber_region_line;
1380 if (global_clobber_region_function) {
1381 DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
1382 global_clobber_region_function,
1383 global_clobber_region_line));
1386 #endif
1388 cmd = lp_panic_action();
1389 if (cmd && *cmd) {
1390 DEBUG(0, ("smb_panic(): calling panic action [%s]\n", cmd));
1391 result = system(cmd);
1393 if (result == -1)
1394 DEBUG(0, ("smb_panic(): fork failed in panic action: %s\n",
1395 strerror(errno)));
1396 else
1397 DEBUG(0, ("smb_panic(): action returned status %d\n",
1398 WEXITSTATUS(result)));
1400 DEBUG(0,("PANIC: %s\n", why));
1402 #ifdef HAVE_BACKTRACE_SYMBOLS
1403 /* get the backtrace (stack frames) */
1404 backtrace_size = backtrace(backtrace_stack,BACKTRACE_STACK_SIZE);
1405 backtrace_strings = backtrace_symbols(backtrace_stack, backtrace_size);
1407 DEBUG(0, ("BACKTRACE: %lu stack frames:\n",
1408 (unsigned long)backtrace_size));
1410 if (backtrace_strings) {
1411 int i;
1413 for (i = 0; i < backtrace_size; i++)
1414 DEBUGADD(0, (" #%u %s\n", i, backtrace_strings[i]));
1416 SAFE_FREE(backtrace_strings);
1419 #endif
1421 dbgflush();
1422 abort();
1425 /*******************************************************************
1426 A readdir wrapper which just returns the file name.
1427 ********************************************************************/
1429 const char *readdirname(DIR *p)
1431 SMB_STRUCT_DIRENT *ptr;
1432 char *dname;
1434 if (!p)
1435 return(NULL);
1437 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1438 if (!ptr)
1439 return(NULL);
1441 dname = ptr->d_name;
1443 #ifdef NEXT2
1444 if (telldir(p) < 0)
1445 return(NULL);
1446 #endif
1448 #ifdef HAVE_BROKEN_READDIR
1449 /* using /usr/ucb/cc is BAD */
1450 dname = dname - 2;
1451 #endif
1454 static pstring buf;
1455 int len = NAMLEN(ptr);
1456 memcpy(buf, dname, len);
1457 buf[len] = 0;
1458 dname = buf;
1461 return(dname);
1464 /*******************************************************************
1465 Utility function used to decide if the last component
1466 of a path matches a (possibly wildcarded) entry in a namelist.
1467 ********************************************************************/
1469 BOOL is_in_path(const char *name, name_compare_entry *namelist)
1471 pstring last_component;
1472 char *p;
1474 DEBUG(8, ("is_in_path: %s\n", name));
1476 /* if we have no list it's obviously not in the path */
1477 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL))) {
1478 DEBUG(8,("is_in_path: no name list.\n"));
1479 return False;
1482 /* Get the last component of the unix name. */
1483 p = strrchr_m(name, '/');
1484 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1485 last_component[sizeof(last_component)-1] = '\0';
1487 for(; namelist->name != NULL; namelist++) {
1488 if(namelist->is_wild) {
1489 if (mask_match(last_component, namelist->name, case_sensitive)) {
1490 DEBUG(8,("is_in_path: mask match succeeded\n"));
1491 return True;
1493 } else {
1494 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1495 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
1496 DEBUG(8,("is_in_path: match succeeded\n"));
1497 return True;
1501 DEBUG(8,("is_in_path: match not found\n"));
1503 return False;
1506 /*******************************************************************
1507 Strip a '/' separated list into an array of
1508 name_compare_enties structures suitable for
1509 passing to is_in_path(). We do this for
1510 speed so we can pre-parse all the names in the list
1511 and don't do it for each call to is_in_path().
1512 namelist is modified here and is assumed to be
1513 a copy owned by the caller.
1514 We also check if the entry contains a wildcard to
1515 remove a potentially expensive call to mask_match
1516 if possible.
1517 ********************************************************************/
1519 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1521 char *name_end;
1522 char *nameptr = namelist;
1523 int num_entries = 0;
1524 int i;
1526 (*ppname_array) = NULL;
1528 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1529 return;
1531 /* We need to make two passes over the string. The
1532 first to count the number of elements, the second
1533 to split it.
1536 while(*nameptr) {
1537 if ( *nameptr == '/' ) {
1538 /* cope with multiple (useless) /s) */
1539 nameptr++;
1540 continue;
1542 /* find the next / */
1543 name_end = strchr_m(nameptr, '/');
1545 /* oops - the last check for a / didn't find one. */
1546 if (name_end == NULL)
1547 break;
1549 /* next segment please */
1550 nameptr = name_end + 1;
1551 num_entries++;
1554 if(num_entries == 0)
1555 return;
1557 if(( (*ppname_array) = (name_compare_entry *)malloc(
1558 (num_entries + 1) * sizeof(name_compare_entry))) == NULL) {
1559 DEBUG(0,("set_namearray: malloc fail\n"));
1560 return;
1563 /* Now copy out the names */
1564 nameptr = namelist;
1565 i = 0;
1566 while(*nameptr) {
1567 if ( *nameptr == '/' ) {
1568 /* cope with multiple (useless) /s) */
1569 nameptr++;
1570 continue;
1572 /* find the next / */
1573 if ((name_end = strchr_m(nameptr, '/')) != NULL)
1574 *name_end = 0;
1576 /* oops - the last check for a / didn't find one. */
1577 if(name_end == NULL)
1578 break;
1580 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1581 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL) {
1582 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1583 return;
1586 /* next segment please */
1587 nameptr = name_end + 1;
1588 i++;
1591 (*ppname_array)[i].name = NULL;
1593 return;
1596 /****************************************************************************
1597 Routine to free a namearray.
1598 ****************************************************************************/
1600 void free_namearray(name_compare_entry *name_array)
1602 int i;
1604 if(name_array == NULL)
1605 return;
1607 for(i=0; name_array[i].name!=NULL; i++)
1608 SAFE_FREE(name_array[i].name);
1609 SAFE_FREE(name_array);
1612 /****************************************************************************
1613 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1614 is dealt with in posix.c
1615 ****************************************************************************/
1617 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1619 SMB_STRUCT_FLOCK lock;
1620 int ret;
1622 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1624 lock.l_type = type;
1625 lock.l_whence = SEEK_SET;
1626 lock.l_start = offset;
1627 lock.l_len = count;
1628 lock.l_pid = 0;
1630 ret = sys_fcntl_ptr(fd,op,&lock);
1632 if (ret == -1 && errno != 0)
1633 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1635 /* a lock query */
1636 if (op == SMB_F_GETLK) {
1637 if ((ret != -1) &&
1638 (lock.l_type != F_UNLCK) &&
1639 (lock.l_pid != 0) &&
1640 (lock.l_pid != sys_getpid())) {
1641 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1642 return(True);
1645 /* it must be not locked or locked by me */
1646 return(False);
1649 /* a lock set or unset */
1650 if (ret == -1) {
1651 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1652 (double)offset,(double)count,op,type,strerror(errno)));
1653 return(False);
1656 /* everything went OK */
1657 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1659 return(True);
1662 /*******************************************************************
1663 Is the name specified one of my netbios names.
1664 Returns true if it is equal, false otherwise.
1665 ********************************************************************/
1667 BOOL is_myname(const char *s)
1669 int n;
1670 BOOL ret = False;
1672 for (n=0; my_netbios_names(n); n++) {
1673 if (strequal(my_netbios_names(n), s)) {
1674 ret=True;
1675 break;
1678 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1679 return(ret);
1682 /********************************************************************
1683 Return only the first IP address of our configured interfaces
1684 as a string
1685 *******************************************************************/
1687 const char* get_my_primary_ip (void)
1689 static fstring ip_string;
1690 int n;
1691 struct iface_struct nics[MAX_INTERFACES];
1693 if ((n=get_interfaces(nics, MAX_INTERFACES)) <= 0)
1694 return NULL;
1696 fstrcpy(ip_string, inet_ntoa(nics[0].ip));
1697 return ip_string;
1700 BOOL is_myname_or_ipaddr(const char *s)
1702 /* optimize for the common case */
1703 if (strequal(s, global_myname()))
1704 return True;
1706 /* maybe its an IP address? */
1707 if (is_ipaddress(s)) {
1708 struct iface_struct nics[MAX_INTERFACES];
1709 int i, n;
1710 uint32 ip;
1712 ip = interpret_addr(s);
1713 if ((ip==0) || (ip==0xffffffff))
1714 return False;
1716 n = get_interfaces(nics, MAX_INTERFACES);
1717 for (i=0; i<n; i++) {
1718 if (ip == nics[i].ip.s_addr)
1719 return True;
1723 /* check for an alias */
1724 if (is_myname(s))
1725 return True;
1727 /* no match */
1728 return False;
1731 /*******************************************************************
1732 Is the name specified our workgroup/domain.
1733 Returns true if it is equal, false otherwise.
1734 ********************************************************************/
1736 BOOL is_myworkgroup(const char *s)
1738 BOOL ret = False;
1740 if (strequal(s, lp_workgroup())) {
1741 ret=True;
1744 DEBUG(8, ("is_myworkgroup(\"%s\") returns %d\n", s, ret));
1745 return(ret);
1748 /*******************************************************************
1749 we distinguish between 2K and XP by the "Native Lan Manager" string
1750 WinXP => "Windows 2002 5.1"
1751 Win2k => "Windows 2000 5.0"
1752 NT4 => "Windows NT 4.0"
1753 Win9x => "Windows 4.0"
1754 ********************************************************************/
1756 void ra_lanman_string( const char *native_lanman )
1758 if ( 0 == strcmp( native_lanman, "Windows 2002 5.1" ) )
1759 set_remote_arch( RA_WINXP );
1760 else if ( 0 == strcmp( native_lanman, "Windows .NET 5.2" ) )
1761 set_remote_arch( RA_WIN2K3 );
1764 /*******************************************************************
1765 Set the horrid remote_arch string based on an enum.
1766 ********************************************************************/
1768 void set_remote_arch(enum remote_arch_types type)
1770 extern fstring remote_arch;
1771 ra_type = type;
1772 switch( type ) {
1773 case RA_WFWG:
1774 fstrcpy(remote_arch, "WfWg");
1775 return;
1776 case RA_OS2:
1777 fstrcpy(remote_arch, "OS2");
1778 return;
1779 case RA_WIN95:
1780 fstrcpy(remote_arch, "Win95");
1781 return;
1782 case RA_WINNT:
1783 fstrcpy(remote_arch, "WinNT");
1784 return;
1785 case RA_WIN2K:
1786 fstrcpy(remote_arch, "Win2K");
1787 return;
1788 case RA_WINXP:
1789 fstrcpy(remote_arch, "WinXP");
1790 return;
1791 case RA_WIN2K3:
1792 fstrcpy(remote_arch, "Win2K3");
1793 return;
1794 case RA_SAMBA:
1795 fstrcpy(remote_arch,"Samba");
1796 return;
1797 default:
1798 ra_type = RA_UNKNOWN;
1799 fstrcpy(remote_arch, "UNKNOWN");
1800 break;
1804 /*******************************************************************
1805 Get the remote_arch type.
1806 ********************************************************************/
1808 enum remote_arch_types get_remote_arch(void)
1810 return ra_type;
1813 void print_asc(int level, const unsigned char *buf,int len)
1815 int i;
1816 for (i=0;i<len;i++)
1817 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1820 void dump_data(int level, const char *buf1,int len)
1822 const unsigned char *buf = (const unsigned char *)buf1;
1823 int i=0;
1824 if (len<=0) return;
1826 if (!DEBUGLVL(level)) return;
1828 DEBUGADD(level,("[%03X] ",i));
1829 for (i=0;i<len;) {
1830 DEBUGADD(level,("%02X ",(int)buf[i]));
1831 i++;
1832 if (i%8 == 0) DEBUGADD(level,(" "));
1833 if (i%16 == 0) {
1834 print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
1835 print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
1836 if (i<len) DEBUGADD(level,("[%03X] ",i));
1839 if (i%16) {
1840 int n;
1841 n = 16 - (i%16);
1842 DEBUGADD(level,(" "));
1843 if (n>8) DEBUGADD(level,(" "));
1844 while (n--) DEBUGADD(level,(" "));
1845 n = MIN(8,i%16);
1846 print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
1847 n = (i%16) - n;
1848 if (n>0) print_asc(level,&buf[i-n],n);
1849 DEBUGADD(level,("\n"));
1853 void dump_data_pw(const char *msg, const uchar * data, size_t len)
1855 #ifdef DEBUG_PASSWORD
1856 DEBUG(11, ("%s", msg));
1857 if (data != NULL && len > 0)
1859 dump_data(11, data, len);
1861 #endif
1864 char *tab_depth(int depth)
1866 static pstring spaces;
1867 memset(spaces, ' ', depth * 4);
1868 spaces[depth * 4] = 0;
1869 return spaces;
1872 /*****************************************************************************
1873 Provide a checksum on a string
1875 Input: s - the null-terminated character string for which the checksum
1876 will be calculated.
1878 Output: The checksum value calculated for s.
1879 *****************************************************************************/
1881 int str_checksum(const char *s)
1883 int res = 0;
1884 int c;
1885 int i=0;
1887 while(*s) {
1888 c = *s;
1889 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1890 s++;
1891 i++;
1893 return(res);
1896 /*****************************************************************
1897 Zero a memory area then free it. Used to catch bugs faster.
1898 *****************************************************************/
1900 void zero_free(void *p, size_t size)
1902 memset(p, 0, size);
1903 SAFE_FREE(p);
1906 /*****************************************************************
1907 Set our open file limit to a requested max and return the limit.
1908 *****************************************************************/
1910 int set_maxfiles(int requested_max)
1912 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1913 struct rlimit rlp;
1914 int saved_current_limit;
1916 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1917 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1918 strerror(errno) ));
1919 /* just guess... */
1920 return requested_max;
1924 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1925 * account for the extra fd we need
1926 * as well as the log files and standard
1927 * handles etc. Save the limit we want to set in case
1928 * we are running on an OS that doesn't support this limit (AIX)
1929 * which always returns RLIM_INFINITY for rlp.rlim_max.
1932 /* Try raising the hard (max) limit to the requested amount. */
1934 #if defined(RLIM_INFINITY)
1935 if (rlp.rlim_max != RLIM_INFINITY) {
1936 int orig_max = rlp.rlim_max;
1938 if ( rlp.rlim_max < requested_max )
1939 rlp.rlim_max = requested_max;
1941 /* This failing is not an error - many systems (Linux) don't
1942 support our default request of 10,000 open files. JRA. */
1944 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1945 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1946 (int)rlp.rlim_max, strerror(errno) ));
1948 /* Set failed - restore original value from get. */
1949 rlp.rlim_max = orig_max;
1952 #endif
1954 /* Now try setting the soft (current) limit. */
1956 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1958 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1959 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1960 (int)rlp.rlim_cur, strerror(errno) ));
1961 /* just guess... */
1962 return saved_current_limit;
1965 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1966 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1967 strerror(errno) ));
1968 /* just guess... */
1969 return saved_current_limit;
1972 #if defined(RLIM_INFINITY)
1973 if(rlp.rlim_cur == RLIM_INFINITY)
1974 return saved_current_limit;
1975 #endif
1977 if((int)rlp.rlim_cur > saved_current_limit)
1978 return saved_current_limit;
1980 return rlp.rlim_cur;
1981 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1983 * No way to know - just guess...
1985 return requested_max;
1986 #endif
1989 /*****************************************************************
1990 Splits out the start of the key (HKLM or HKU) and the rest of the key.
1991 *****************************************************************/
1993 BOOL reg_split_key(const char *full_keyname, uint32 *reg_type, char *key_name)
1995 pstring tmp;
1997 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1998 return False;
2000 (*reg_type) = 0;
2002 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
2004 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
2005 (*reg_type) = HKEY_LOCAL_MACHINE;
2006 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
2007 (*reg_type) = HKEY_USERS;
2008 else {
2009 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
2010 return False;
2013 if (next_token(&full_keyname, tmp, "\n\r", sizeof(tmp)))
2014 fstrcpy(key_name, tmp);
2015 else
2016 key_name[0] = 0;
2018 DEBUG(10, ("reg_split_key: name %s\n", key_name));
2020 return True;
2023 /*****************************************************************
2024 Possibly replace mkstemp if it is broken.
2025 *****************************************************************/
2027 int smb_mkstemp(char *template)
2029 #if HAVE_SECURE_MKSTEMP
2030 return mkstemp(template);
2031 #else
2032 /* have a reasonable go at emulating it. Hope that
2033 the system mktemp() isn't completly hopeless */
2034 char *p = mktemp(template);
2035 if (!p)
2036 return -1;
2037 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
2038 #endif
2041 /*****************************************************************
2042 malloc that aborts with smb_panic on fail or zero size.
2043 *****************************************************************/
2045 void *smb_xmalloc(size_t size)
2047 void *p;
2048 if (size == 0)
2049 smb_panic("smb_xmalloc: called with zero size.\n");
2050 if ((p = malloc(size)) == NULL) {
2051 DEBUG(0, ("smb_xmalloc() failed to allocate %lu bytes\n", (unsigned long)size));
2052 smb_panic("smb_xmalloc: malloc fail.\n");
2054 return p;
2058 Memdup with smb_panic on fail.
2061 void *smb_xmemdup(const void *p, size_t size)
2063 void *p2;
2064 p2 = smb_xmalloc(size);
2065 memcpy(p2, p, size);
2066 return p2;
2070 strdup that aborts on malloc fail.
2073 char *smb_xstrdup(const char *s)
2075 char *s1 = strdup(s);
2076 if (!s1)
2077 smb_panic("smb_xstrdup: malloc fail\n");
2078 return s1;
2082 strndup that aborts on malloc fail.
2085 char *smb_xstrndup(const char *s, size_t n)
2087 char *s1 = strndup(s, n);
2088 if (!s1)
2089 smb_panic("smb_xstrndup: malloc fail\n");
2090 return s1;
2094 vasprintf that aborts on malloc fail
2097 int smb_xvasprintf(char **ptr, const char *format, va_list ap)
2099 int n;
2100 va_list ap2;
2102 VA_COPY(ap2, ap);
2104 n = vasprintf(ptr, format, ap2);
2105 if (n == -1 || ! *ptr)
2106 smb_panic("smb_xvasprintf: out of memory");
2107 return n;
2110 /*****************************************************************
2111 Like strdup but for memory.
2112 *****************************************************************/
2114 void *memdup(const void *p, size_t size)
2116 void *p2;
2117 if (size == 0)
2118 return NULL;
2119 p2 = malloc(size);
2120 if (!p2)
2121 return NULL;
2122 memcpy(p2, p, size);
2123 return p2;
2126 /*****************************************************************
2127 Get local hostname and cache result.
2128 *****************************************************************/
2130 char *myhostname(void)
2132 static pstring ret;
2133 if (ret[0] == 0)
2134 get_myname(ret);
2135 return ret;
2138 /*****************************************************************
2139 A useful function for returning a path in the Samba lock directory.
2140 *****************************************************************/
2142 char *lock_path(const char *name)
2144 static pstring fname;
2146 pstrcpy(fname,lp_lockdir());
2147 trim_char(fname,'\0','/');
2149 if (!directory_exist(fname,NULL))
2150 mkdir(fname,0755);
2152 pstrcat(fname,"/");
2153 pstrcat(fname,name);
2155 return fname;
2158 /*****************************************************************
2159 A useful function for returning a path in the Samba pid directory.
2160 *****************************************************************/
2162 char *pid_path(const char *name)
2164 static pstring fname;
2166 pstrcpy(fname,lp_piddir());
2167 trim_char(fname,'\0','/');
2169 if (!directory_exist(fname,NULL))
2170 mkdir(fname,0755);
2172 pstrcat(fname,"/");
2173 pstrcat(fname,name);
2175 return fname;
2179 * @brief Returns an absolute path to a file in the Samba lib directory.
2181 * @param name File to find, relative to LIBDIR.
2183 * @retval Pointer to a static #pstring containing the full path.
2186 char *lib_path(const char *name)
2188 static pstring fname;
2189 fstr_sprintf(fname, "%s/%s", dyn_LIBDIR, name);
2190 return fname;
2194 * @brief Returns the platform specific shared library extension.
2196 * @retval Pointer to a static #fstring containing the extension.
2199 const char *shlib_ext(void)
2201 return dyn_SHLIBEXT;
2204 /*******************************************************************
2205 Given a filename - get its directory name
2206 NB: Returned in static storage. Caveats:
2207 o Not safe in thread environment.
2208 o Caller must not free.
2209 o If caller wishes to preserve, they should copy.
2210 ********************************************************************/
2212 char *parent_dirname(const char *path)
2214 static pstring dirpath;
2215 char *p;
2217 if (!path)
2218 return(NULL);
2220 pstrcpy(dirpath, path);
2221 p = strrchr_m(dirpath, '/'); /* Find final '/', if any */
2222 if (!p) {
2223 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
2224 } else {
2225 if (p == dirpath)
2226 ++p; /* For root "/", leave "/" in place */
2227 *p = '\0';
2229 return dirpath;
2233 /*******************************************************************
2234 Determine if a pattern contains any Microsoft wildcard characters.
2235 *******************************************************************/
2237 BOOL ms_has_wild(char *s)
2239 char c;
2240 while ((c = *s++)) {
2241 switch (c) {
2242 case '*':
2243 case '?':
2244 case '<':
2245 case '>':
2246 case '"':
2247 return True;
2250 return False;
2253 BOOL ms_has_wild_w(const smb_ucs2_t *s)
2255 smb_ucs2_t c;
2256 if (!s) return False;
2257 while ((c = *s++)) {
2258 switch (c) {
2259 case UCS2_CHAR('*'):
2260 case UCS2_CHAR('?'):
2261 case UCS2_CHAR('<'):
2262 case UCS2_CHAR('>'):
2263 case UCS2_CHAR('"'):
2264 return True;
2267 return False;
2270 /*******************************************************************
2271 A wrapper that handles case sensitivity and the special handling
2272 of the ".." name.
2273 *******************************************************************/
2275 BOOL mask_match(const char *string, char *pattern, BOOL is_case_sensitive)
2277 if (strcmp(string,"..") == 0)
2278 string = ".";
2279 if (strcmp(pattern,".") == 0)
2280 return False;
2282 return ms_fnmatch(pattern, string, Protocol, is_case_sensitive) == 0;
2285 /*********************************************************
2286 Recursive routine that is called by unix_wild_match.
2287 *********************************************************/
2289 static BOOL unix_do_match(const char *regexp, const char *str)
2291 const char *p;
2293 for( p = regexp; *p && *str; ) {
2295 switch(*p) {
2296 case '?':
2297 str++;
2298 p++;
2299 break;
2301 case '*':
2304 * Look for a character matching
2305 * the one after the '*'.
2307 p++;
2308 if(!*p)
2309 return True; /* Automatic match */
2310 while(*str) {
2312 while(*str && (*p != *str))
2313 str++;
2316 * Patch from weidel@multichart.de. In the case of the regexp
2317 * '*XX*' we want to ensure there are at least 2 'X' characters
2318 * in the string after the '*' for a match to be made.
2322 int matchcount=0;
2325 * Eat all the characters that match, but count how many there were.
2328 while(*str && (*p == *str)) {
2329 str++;
2330 matchcount++;
2334 * Now check that if the regexp had n identical characters that
2335 * matchcount had at least that many matches.
2338 while ( *(p+1) && (*(p+1) == *p)) {
2339 p++;
2340 matchcount--;
2343 if ( matchcount <= 0 )
2344 return False;
2347 str--; /* We've eaten the match char after the '*' */
2349 if(unix_do_match(p, str))
2350 return True;
2352 if(!*str)
2353 return False;
2354 else
2355 str++;
2357 return False;
2359 default:
2360 if(*str != *p)
2361 return False;
2362 str++;
2363 p++;
2364 break;
2368 if(!*p && !*str)
2369 return True;
2371 if (!*p && str[0] == '.' && str[1] == 0)
2372 return(True);
2374 if (!*str && *p == '?') {
2375 while (*p == '?')
2376 p++;
2377 return(!*p);
2380 if(!*str && (*p == '*' && p[1] == '\0'))
2381 return True;
2383 return False;
2386 /*******************************************************************
2387 Simple case insensitive interface to a UNIX wildcard matcher.
2388 *******************************************************************/
2390 BOOL unix_wild_match(const char *pattern, const char *string)
2392 pstring p2, s2;
2393 char *p;
2395 pstrcpy(p2, pattern);
2396 pstrcpy(s2, string);
2397 strlower_m(p2);
2398 strlower_m(s2);
2400 /* Remove any *? and ** from the pattern as they are meaningless */
2401 for(p = p2; *p; p++)
2402 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2403 pstrcpy( &p[1], &p[2]);
2405 if (strequal(p2,"*"))
2406 return True;
2408 return unix_do_match(p2, s2) == 0;
2412 #ifdef __INSURE__
2414 /*******************************************************************
2415 This routine is a trick to immediately catch errors when debugging
2416 with insure. A xterm with a gdb is popped up when insure catches
2417 a error. It is Linux specific.
2418 ********************************************************************/
2420 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
2422 static int (*fn)();
2423 int ret;
2424 char pidstr[10];
2425 /* you can get /usr/bin/backtrace from
2426 http://samba.org/ftp/unpacked/junkcode/backtrace */
2427 pstring cmd = "/usr/bin/backtrace %d";
2429 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
2430 pstring_sub(cmd, "%d", pidstr);
2432 if (!fn) {
2433 static void *h;
2434 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
2435 fn = dlsym(h, "_Insure_trap_error");
2437 if (!h || h == _Insure_trap_error) {
2438 h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
2439 fn = dlsym(h, "_Insure_trap_error");
2443 ret = fn(a1, a2, a3, a4, a5, a6);
2445 system(cmd);
2447 return ret;
2449 #endif