preparing for release of 2.2.3a
[Samba.git] / source / lib / util.c
blob9aad4f976aa1de3cdd3993e44aef89b905caeeaa
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
6 Copyright (C) Jeremy Allison 2001
7 Copyright (C) Simo Sorce 2001
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 #endif /* WITH_NISPLUS_HOME */
50 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
52 #ifdef WITH_SSL
53 #include <openssl/ssl.h>
54 #undef Realloc /* SSLeay defines this and samba has a function of this name */
55 extern SSL *ssl;
56 extern int sslFd;
57 #endif /* WITH_SSL */
59 int Protocol = PROTOCOL_COREPLUS;
61 /* a default finfo structure to ensure all fields are sensible */
62 file_info def_finfo = {-1,0,0,0,0,0,0,"",""};
64 /* this is used by the chaining code */
65 int chain_size = 0;
67 int trans_num = 0;
70 case handling on filenames
72 int case_default = CASE_LOWER;
74 /* the following control case operations - they are put here so the
75 client can link easily */
76 BOOL case_sensitive;
77 BOOL case_preserve;
78 BOOL use_mangled_map = False;
79 BOOL short_case_preserve;
80 BOOL case_mangle;
82 static enum remote_arch_types ra_type = RA_UNKNOWN;
83 pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;
85 pstring global_myname = "";
86 fstring global_myworkgroup = "";
87 char **my_netbios_names;
90 /****************************************************************************
91 Find a suitable temporary directory. The result should be copied immediately
92 as it may be overwritten by a subsequent call.
93 ****************************************************************************/
95 char *tmpdir(void)
97 char *p;
98 if ((p = getenv("TMPDIR")))
99 return p;
100 return "/tmp";
103 /****************************************************************************
104 Determine whether we are in the specified group.
105 ****************************************************************************/
107 BOOL in_group(gid_t group, gid_t current_gid, int ngroups, gid_t *groups)
109 int i;
111 if (group == current_gid)
112 return(True);
114 for (i=0;i<ngroups;i++)
115 if (group == groups[i])
116 return(True);
118 return(False);
121 /****************************************************************************
122 Like atoi but gets the value up to the separater character.
123 ****************************************************************************/
125 char *Atoic(char *p, int *n, char *c)
127 if (!isdigit((int)*p)) {
128 DEBUG(5, ("Atoic: malformed number\n"));
129 return NULL;
132 (*n) = atoi(p);
134 while ((*p) && isdigit((int)*p))
135 p++;
137 if (strchr(c, *p) == NULL) {
138 DEBUG(5, ("Atoic: no separator characters (%s) not found\n", c));
139 return NULL;
142 return p;
145 /*************************************************************************
146 Reads a list of numbers.
147 *************************************************************************/
149 char *get_numlist(char *p, uint32 **num, int *count)
151 int val;
153 if (num == NULL || count == NULL)
154 return NULL;
156 (*count) = 0;
157 (*num ) = NULL;
159 while ((p = Atoic(p, &val, ":,")) != NULL && (*p) != ':') {
160 uint32 *tn;
162 tn = Realloc((*num), ((*count)+1) * sizeof(uint32));
163 if (tn == NULL)
165 SAFE_FREE(*num);
166 return NULL;
167 } else
168 (*num) = tn;
169 (*num)[(*count)] = val;
170 (*count)++;
171 p++;
174 return p;
177 /*******************************************************************
178 Check if a file exists - call vfs_file_exist for samba files.
179 ********************************************************************/
181 BOOL file_exist(char *fname,SMB_STRUCT_STAT *sbuf)
183 SMB_STRUCT_STAT st;
184 if (!sbuf)
185 sbuf = &st;
187 if (sys_stat(fname,sbuf) != 0)
188 return(False);
190 return(S_ISREG(sbuf->st_mode));
193 /*******************************************************************
194 Check a files mod time.
195 ********************************************************************/
197 time_t file_modtime(char *fname)
199 SMB_STRUCT_STAT st;
201 if (sys_stat(fname,&st) != 0)
202 return(0);
204 return(st.st_mtime);
207 /*******************************************************************
208 Check if a directory exists.
209 ********************************************************************/
211 BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
213 SMB_STRUCT_STAT st2;
214 BOOL ret;
216 if (!st) st = &st2;
218 if (sys_stat(dname,st) != 0)
219 return(False);
221 ret = S_ISDIR(st->st_mode);
222 if(!ret)
223 errno = ENOTDIR;
224 return ret;
227 /*******************************************************************
228 returns the size in bytes of the named file
229 ********************************************************************/
230 SMB_OFF_T get_file_size(char *file_name)
232 SMB_STRUCT_STAT buf;
233 buf.st_size = 0;
234 if(sys_stat(file_name,&buf) != 0)
235 return (SMB_OFF_T)-1;
236 return(buf.st_size);
239 /*******************************************************************
240 return a string representing an attribute for a file
241 ********************************************************************/
242 char *attrib_string(uint16 mode)
244 static fstring attrstr;
246 attrstr[0] = 0;
248 if (mode & aVOLID) fstrcat(attrstr,"V");
249 if (mode & aDIR) fstrcat(attrstr,"D");
250 if (mode & aARCH) fstrcat(attrstr,"A");
251 if (mode & aHIDDEN) fstrcat(attrstr,"H");
252 if (mode & aSYSTEM) fstrcat(attrstr,"S");
253 if (mode & aRONLY) fstrcat(attrstr,"R");
255 return(attrstr);
258 /*******************************************************************
259 show a smb message structure
260 ********************************************************************/
261 void show_msg(char *buf)
263 int i;
264 int bcc=0;
266 if (DEBUGLEVEL < 5) return;
268 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
269 smb_len(buf),
270 (int)CVAL(buf,smb_com),
271 (int)CVAL(buf,smb_rcls),
272 (int)CVAL(buf,smb_reh),
273 (int)SVAL(buf,smb_err),
274 (int)CVAL(buf,smb_flg),
275 (int)SVAL(buf,smb_flg2)));
276 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
277 (int)SVAL(buf,smb_tid),
278 (int)SVAL(buf,smb_pid),
279 (int)SVAL(buf,smb_uid),
280 (int)SVAL(buf,smb_mid),
281 (int)CVAL(buf,smb_wct)));
283 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
285 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
286 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
289 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
291 DEBUG(5,("smb_bcc=%d\n",bcc));
293 if (DEBUGLEVEL < 10) return;
295 if (DEBUGLEVEL < 50)
297 bcc = MIN(bcc, 512);
300 dump_data(10, smb_buf(buf), bcc);
303 /*******************************************************************
304 set the length and marker of an smb packet
305 ********************************************************************/
306 void smb_setlen(char *buf,int len)
308 _smb_setlen(buf,len);
310 SCVAL(buf,4,0xFF);
311 SCVAL(buf,5,'S');
312 SCVAL(buf,6,'M');
313 SCVAL(buf,7,'B');
316 /*******************************************************************
317 setup the word count and byte count for a smb message
318 ********************************************************************/
319 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
321 if (zero)
322 memset(buf + smb_size,'\0',num_words*2 + num_bytes);
323 SCVAL(buf,smb_wct,num_words);
324 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
325 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
326 return (smb_size + num_words*2 + num_bytes);
329 /*******************************************************************
330 setup only the byte count for a smb message
331 ********************************************************************/
332 int set_message_bcc(char *buf,int num_bytes)
334 int num_words = CVAL(buf,smb_wct);
335 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
336 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
337 return (smb_size + num_words*2 + num_bytes);
340 /*******************************************************************
341 setup only the byte count for a smb message, using the end of the
342 message as a marker
343 ********************************************************************/
344 int set_message_end(void *outbuf,void *end_ptr)
346 return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
349 /*******************************************************************
350 reduce a file name, removing .. elements.
351 ********************************************************************/
352 void dos_clean_name(char *s)
354 char *p=NULL;
356 DEBUG(3,("dos_clean_name [%s]\n",s));
358 /* remove any double slashes */
359 all_string_sub(s, "\\\\", "\\", 0);
361 while ((p = strstr(s,"\\..\\")) != NULL)
363 pstring s1;
365 *p = 0;
366 pstrcpy(s1,p+3);
368 if ((p=strrchr(s,'\\')) != NULL)
369 *p = 0;
370 else
371 *s = 0;
372 pstrcat(s,s1);
375 trim_string(s,NULL,"\\..");
377 all_string_sub(s, "\\.\\", "\\", 0);
380 /*******************************************************************
381 reduce a file name, removing .. elements.
382 ********************************************************************/
383 void unix_clean_name(char *s)
385 char *p=NULL;
387 DEBUG(3,("unix_clean_name [%s]\n",s));
389 /* remove any double slashes */
390 all_string_sub(s, "//","/", 0);
392 /* Remove leading ./ characters */
393 if(strncmp(s, "./", 2) == 0) {
394 trim_string(s, "./", NULL);
395 if(*s == 0)
396 pstrcpy(s,"./");
399 while ((p = strstr(s,"/../")) != NULL)
401 pstring s1;
403 *p = 0;
404 pstrcpy(s1,p+3);
406 if ((p=strrchr(s,'/')) != NULL)
407 *p = 0;
408 else
409 *s = 0;
410 pstrcat(s,s1);
413 trim_string(s,NULL,"/..");
416 /****************************************************************************
417 make a dir struct
418 ****************************************************************************/
419 void make_dir_struct(char *buf,char *mask,char *fname,SMB_OFF_T size,int mode,time_t date)
421 char *p;
422 pstring mask2;
424 pstrcpy(mask2,mask);
426 if ((mode & aDIR) != 0)
427 size = 0;
429 memset(buf+1,' ',11);
430 if ((p = strchr(mask2,'.')) != NULL)
432 *p = 0;
433 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
434 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
435 *p = '.';
437 else
438 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
440 memset(buf+21,'\0',DIR_STRUCT_SIZE-21);
441 SCVAL(buf,21,mode);
442 put_dos_date(buf,22,date);
443 SSVAL(buf,26,size & 0xFFFF);
444 SSVAL(buf,28,(size >> 16)&0xFFFF);
445 StrnCpy(buf+30,fname,12);
446 if (!case_sensitive)
447 strupper(buf+30);
448 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
452 /*******************************************************************
453 close the low 3 fd's and open dev/null in their place
454 ********************************************************************/
455 void close_low_fds(void)
457 int fd;
458 int i;
459 close(0); close(1);
460 #ifndef __INSURE__
461 close(2);
462 #endif
463 /* try and use up these file descriptors, so silly
464 library routines writing to stdout etc won't cause havoc */
465 for (i=0;i<3;i++) {
466 fd = sys_open("/dev/null",O_RDWR,0);
467 if (fd < 0) fd = sys_open("/dev/null",O_WRONLY,0);
468 if (fd < 0) {
469 DEBUG(0,("Can't open /dev/null\n"));
470 return;
472 if (fd != i) {
473 DEBUG(0,("Didn't get file descriptor %d\n",i));
474 return;
479 /****************************************************************************
480 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
481 else
482 if SYSV use O_NDELAY
483 if BSD use FNDELAY
484 ****************************************************************************/
485 int set_blocking(int fd, BOOL set)
487 int val;
488 #ifdef O_NONBLOCK
489 #define FLAG_TO_SET O_NONBLOCK
490 #else
491 #ifdef SYSV
492 #define FLAG_TO_SET O_NDELAY
493 #else /* BSD */
494 #define FLAG_TO_SET FNDELAY
495 #endif
496 #endif
498 if((val = fcntl(fd, F_GETFL, 0)) == -1)
499 return -1;
500 if(set) /* Turn blocking on - ie. clear nonblock flag */
501 val &= ~FLAG_TO_SET;
502 else
503 val |= FLAG_TO_SET;
504 return fcntl( fd, F_SETFL, val);
505 #undef FLAG_TO_SET
508 /****************************************************************************
509 Transfer some data between two fd's.
510 ****************************************************************************/
512 #ifndef TRANSFER_BUF_SIZE
513 #define TRANSFER_BUF_SIZE 65536
514 #endif
516 ssize_t transfer_file_internal(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
517 ssize_t (*write_fn)(int, const void *, size_t))
519 char *buf;
520 size_t total = 0;
521 ssize_t read_ret;
522 ssize_t write_ret;
523 size_t num_to_read_thistime;
524 size_t num_written = 0;
526 if ((buf = malloc(TRANSFER_BUF_SIZE)) == NULL)
527 return -1;
529 while (total < n) {
530 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
532 read_ret = (*read_fn)(infd, buf, num_to_read_thistime);
533 if (read_ret == -1) {
534 DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
535 SAFE_FREE(buf);
536 return -1;
538 if (read_ret == 0)
539 break;
541 num_written = 0;
543 while (num_written < read_ret) {
544 write_ret = (*write_fn)(outfd,buf + num_written, read_ret - num_written);
546 if (write_ret == -1) {
547 DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
548 SAFE_FREE(buf);
549 return -1;
551 if (write_ret == 0)
552 return (ssize_t)total;
554 num_written += (size_t)write_ret;
557 total += (size_t)read_ret;
560 SAFE_FREE(buf);
561 return (ssize_t)total;
564 SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
566 return (SMB_OFF_T)transfer_file_internal(infd, outfd, (size_t)n, read, write);
569 /*******************************************************************
570 Sleep for a specified number of milliseconds.
571 ********************************************************************/
573 void msleep(int t)
575 int tdiff=0;
576 struct timeval tval,t1,t2;
577 fd_set fds;
579 GetTimeOfDay(&t1);
580 GetTimeOfDay(&t2);
582 while (tdiff < t) {
583 tval.tv_sec = (t-tdiff)/1000;
584 tval.tv_usec = 1000*((t-tdiff)%1000);
586 FD_ZERO(&fds);
587 errno = 0;
588 sys_select_intr(0,&fds,NULL,NULL,&tval);
590 GetTimeOfDay(&t2);
591 tdiff = TvalDiff(&t1,&t2);
595 /****************************************************************************
596 Become a daemon, discarding the controlling terminal.
597 ****************************************************************************/
599 void become_daemon(void)
601 if (sys_fork()) {
602 _exit(0);
605 /* detach from the terminal */
606 #ifdef HAVE_SETSID
607 setsid();
608 #elif defined(TIOCNOTTY)
610 int i = sys_open("/dev/tty", O_RDWR, 0);
611 if (i != -1) {
612 ioctl(i, (int) TIOCNOTTY, (char *)0);
613 close(i);
616 #endif /* HAVE_SETSID */
618 /* Close fd's 0,1,2. Needed if started by rsh */
619 close_low_fds();
622 /****************************************************************************
623 Put up a yes/no prompt
624 ****************************************************************************/
626 BOOL yesno(char *p)
628 pstring ans;
629 printf("%s",p);
631 if (!fgets(ans,sizeof(ans)-1,stdin))
632 return(False);
634 if (*ans == 'y' || *ans == 'Y')
635 return(True);
637 return(False);
640 /****************************************************************************
641 Expand a pointer to be a particular size.
642 ****************************************************************************/
644 void *Realloc(void *p,size_t size)
646 void *ret=NULL;
648 if (size == 0) {
649 SAFE_FREE(p);
650 DEBUG(5,("Realloc asked for 0 bytes\n"));
651 return NULL;
654 if (!p)
655 ret = (void *)malloc(size);
656 else
657 ret = (void *)realloc(p,size);
659 if (!ret)
660 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
662 return(ret);
665 /****************************************************************************
666 Free memory, checks for NULL.
667 use directly SAFE_FREE()
668 exist only because we need to pass a function pointer somewhere --SSS
669 ****************************************************************************/
671 void safe_free(void *p)
673 SAFE_FREE(p);
676 /****************************************************************************
677 Get my own name and IP.
678 ****************************************************************************/
680 BOOL get_myname(char *my_name)
682 pstring hostname;
684 *hostname = 0;
686 /* get my host name */
687 if (gethostname(hostname, sizeof(hostname)) == -1) {
688 DEBUG(0,("gethostname failed\n"));
689 return False;
692 /* Ensure null termination. */
693 hostname[sizeof(hostname)-1] = '\0';
695 if (my_name) {
696 /* split off any parts after an initial . */
697 char *p = strchr(hostname,'.');
698 if (p)
699 *p = 0;
701 fstrcpy(my_name,hostname);
704 return(True);
707 /****************************************************************************
708 Interpret a protocol description string, with a default.
709 ****************************************************************************/
711 int interpret_protocol(char *str,int def)
713 if (strequal(str,"NT1"))
714 return(PROTOCOL_NT1);
715 if (strequal(str,"LANMAN2"))
716 return(PROTOCOL_LANMAN2);
717 if (strequal(str,"LANMAN1"))
718 return(PROTOCOL_LANMAN1);
719 if (strequal(str,"CORE"))
720 return(PROTOCOL_CORE);
721 if (strequal(str,"COREPLUS"))
722 return(PROTOCOL_COREPLUS);
723 if (strequal(str,"CORE+"))
724 return(PROTOCOL_COREPLUS);
726 DEBUG(0,("Unrecognised protocol level %s\n",str));
728 return(def);
731 /****************************************************************************
732 Return true if a string could be a pure IP address.
733 ****************************************************************************/
735 BOOL is_ipaddress(const char *str)
737 BOOL pure_address = True;
738 int i;
740 for (i=0; pure_address && str[i]; i++)
741 if (!(isdigit((int)str[i]) || str[i] == '.'))
742 pure_address = False;
744 /* Check that a pure number is not misinterpreted as an IP */
745 pure_address = pure_address && (strchr(str, '.') != NULL);
747 return pure_address;
750 /****************************************************************************
751 interpret an internet address or name into an IP address in 4 byte form
752 ****************************************************************************/
754 uint32 interpret_addr(const char *str)
756 struct hostent *hp;
757 uint32 res;
759 if (strcmp(str,"0.0.0.0") == 0) return(0);
760 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
762 /* if it's in the form of an IP address then get the lib to interpret it */
763 if (is_ipaddress(str)) {
764 res = inet_addr(str);
765 } else {
766 /* otherwise assume it's a network name of some sort and use
767 sys_gethostbyname */
768 if ((hp = sys_gethostbyname(str)) == 0) {
769 DEBUG(3,("sys_gethostbyname: Unknown host. %s\n",str));
770 return 0;
772 if(hp->h_addr == NULL) {
773 DEBUG(3,("sys_gethostbyname: host address is invalid for host %s\n",str));
774 return 0;
776 putip((char *)&res,(char *)hp->h_addr);
779 if (res == (uint32)-1) return(0);
781 return(res);
784 /*******************************************************************
785 a convenient addition to interpret_addr()
786 ******************************************************************/
787 struct in_addr *interpret_addr2(const char *str)
789 static struct in_addr ret;
790 uint32 a = interpret_addr(str);
791 ret.s_addr = a;
792 return(&ret);
795 /*******************************************************************
796 check if an IP is the 0.0.0.0
797 ******************************************************************/
798 BOOL zero_ip(struct in_addr ip)
800 uint32 a;
801 putip((char *)&a,(char *)&ip);
802 return(a == 0);
806 #if (defined(HAVE_NETGROUP) && defined(WITH_AUTOMOUNT))
807 /******************************************************************
808 Remove any mount options such as -rsize=2048,wsize=2048 etc.
809 Based on a fix from <Thomas.Hepper@icem.de>.
810 *******************************************************************/
812 static void strip_mount_options( pstring *str)
814 if (**str == '-')
816 char *p = *str;
817 while(*p && !isspace(*p))
818 p++;
819 while(*p && isspace(*p))
820 p++;
821 if(*p) {
822 pstring tmp_str;
824 pstrcpy(tmp_str, p);
825 pstrcpy(*str, tmp_str);
830 /*******************************************************************
831 Patch from jkf@soton.ac.uk
832 Split Luke's automount_server into YP lookup and string splitter
833 so can easily implement automount_path().
834 As we may end up doing both, cache the last YP result.
835 *******************************************************************/
837 #ifdef WITH_NISPLUS_HOME
838 char *automount_lookup(char *user_name)
840 static fstring last_key = "";
841 static pstring last_value = "";
843 char *nis_map = (char *)lp_nis_home_map_name();
845 char buffer[NIS_MAXATTRVAL + 1];
846 nis_result *result;
847 nis_object *object;
848 entry_obj *entry;
850 if (strcmp(user_name, last_key))
852 slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
853 DEBUG(5, ("NIS+ querystring: %s\n", buffer));
855 if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL))
857 if (result->status != NIS_SUCCESS)
859 DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
860 fstrcpy(last_key, ""); pstrcpy(last_value, "");
862 else
864 object = result->objects.objects_val;
865 if (object->zo_data.zo_type == ENTRY_OBJ)
867 entry = &object->zo_data.objdata_u.en_data;
868 DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
869 DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
871 pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
872 pstring_sub(last_value, "&", user_name);
873 fstrcpy(last_key, user_name);
877 nis_freeresult(result);
880 strip_mount_options(&last_value);
882 DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
883 return last_value;
885 #else /* WITH_NISPLUS_HOME */
886 char *automount_lookup(char *user_name)
888 static fstring last_key = "";
889 static pstring last_value = "";
891 int nis_error; /* returned by yp all functions */
892 char *nis_result; /* yp_match inits this */
893 int nis_result_len; /* and set this */
894 char *nis_domain; /* yp_get_default_domain inits this */
895 char *nis_map = (char *)lp_nis_home_map_name();
897 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
898 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
899 return last_value;
902 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
904 if (!strcmp(user_name, last_key)) {
905 nis_result = last_value;
906 nis_result_len = strlen(last_value);
907 nis_error = 0;
909 } else {
911 if ((nis_error = yp_match(nis_domain, nis_map,
912 user_name, strlen(user_name),
913 &nis_result, &nis_result_len)) == 0) {
914 if (!nis_error && nis_result_len >= sizeof(pstring)) {
915 nis_result_len = sizeof(pstring)-1;
917 fstrcpy(last_key, user_name);
918 strncpy(last_value, nis_result, nis_result_len);
919 last_value[nis_result_len] = '\0';
920 strip_mount_options(&last_value);
922 } else if(nis_error == YPERR_KEY) {
924 /* If Key lookup fails user home server is not in nis_map
925 use default information for server, and home directory */
926 last_value[0] = 0;
927 DEBUG(3, ("YP Key not found: while looking up \"%s\" in map \"%s\"\n",
928 user_name, nis_map));
929 DEBUG(3, ("using defaults for server and home directory\n"));
930 } else {
931 DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n",
932 yperr_string(nis_error), user_name, nis_map));
937 DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
938 return last_value;
940 #endif /* WITH_NISPLUS_HOME */
941 #endif
944 /*******************************************************************
945 are two IPs on the same subnet?
946 ********************************************************************/
947 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
949 uint32 net1,net2,nmask;
951 nmask = ntohl(mask.s_addr);
952 net1 = ntohl(ip1.s_addr);
953 net2 = ntohl(ip2.s_addr);
955 return((net1 & nmask) == (net2 & nmask));
959 /****************************************************************************
960 check if a process exists. Does this work on all unixes?
961 ****************************************************************************/
963 BOOL process_exists(pid_t pid)
965 return(kill(pid,0) == 0 || errno != ESRCH);
969 /*******************************************************************
970 Convert a uid into a user name.
971 ********************************************************************/
973 char *uidtoname(uid_t uid)
975 static fstring name;
976 struct passwd *pass;
978 if (winbind_uidtoname(name, uid))
979 return name;
981 pass = sys_getpwuid(uid);
982 if (pass)
983 return(pass->pw_name);
984 slprintf(name, sizeof(name) - 1, "%d",(int)uid);
985 return(name);
989 /*******************************************************************
990 Convert a gid into a group name.
991 ********************************************************************/
993 char *gidtoname(gid_t gid)
995 static fstring name;
996 struct group *grp;
998 if (winbind_gidtoname(name, gid))
999 return name;
1001 grp = getgrgid(gid);
1002 if (grp)
1003 return(grp->gr_name);
1004 slprintf(name,sizeof(name) - 1, "%d",(int)gid);
1005 return(name);
1008 /*******************************************************************
1009 Convert a user name into a uid. If winbindd is present uses this.
1010 ********************************************************************/
1012 uid_t nametouid(char *name)
1014 struct passwd *pass;
1015 char *p;
1016 uid_t u;
1018 u = (uid_t)strtol(name, &p, 0);
1019 if ((p != name) && (*p == '\0'))
1020 return u;
1022 if (winbind_nametouid(&u, name))
1023 return u;
1025 pass = sys_getpwnam(name);
1026 if (pass)
1027 return(pass->pw_uid);
1028 return (uid_t)-1;
1031 /*******************************************************************
1032 Convert a name to a gid_t if possible. Return -1 if not a group. If winbindd
1033 is present does a shortcut lookup...
1034 ********************************************************************/
1036 gid_t nametogid(char *name)
1038 struct group *grp;
1039 char *p;
1040 gid_t g;
1042 g = (gid_t)strtol(name, &p, 0);
1043 if ((p != name) && (*p == '\0'))
1044 return g;
1046 if (winbind_nametogid(&g, name))
1047 return g;
1049 grp = getgrnam(name);
1050 if (grp)
1051 return(grp->gr_gid);
1052 return (gid_t)-1;
1055 /*******************************************************************
1056 something really nasty happened - panic!
1057 ********************************************************************/
1058 void smb_panic(char *why)
1060 char *cmd = lp_panic_action();
1061 if (cmd && *cmd) {
1062 system(cmd);
1064 DEBUG(0,("PANIC: %s\n", why));
1065 dbgflush();
1066 abort();
1070 /*******************************************************************
1071 a readdir wrapper which just returns the file name
1072 ********************************************************************/
1073 char *readdirname(DIR *p)
1075 SMB_STRUCT_DIRENT *ptr;
1076 char *dname;
1078 if (!p) return(NULL);
1080 ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
1081 if (!ptr) return(NULL);
1083 dname = ptr->d_name;
1085 #ifdef NEXT2
1086 if (telldir(p) < 0) return(NULL);
1087 #endif
1089 #ifdef HAVE_BROKEN_READDIR
1090 /* using /usr/ucb/cc is BAD */
1091 dname = dname - 2;
1092 #endif
1095 static pstring buf;
1096 int len = NAMLEN(ptr);
1097 memcpy(buf, dname, len);
1098 buf[len] = 0;
1099 dname = buf;
1102 return(dname);
1105 /*******************************************************************
1106 Utility function used to decide if the last component
1107 of a path matches a (possibly wildcarded) entry in a namelist.
1108 ********************************************************************/
1110 BOOL is_in_path(char *name, name_compare_entry *namelist)
1112 pstring last_component;
1113 char *p;
1115 DEBUG(8, ("is_in_path: %s\n", name));
1117 /* if we have no list it's obviously not in the path */
1118 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
1120 DEBUG(8,("is_in_path: no name list.\n"));
1121 return False;
1124 /* Get the last component of the unix name. */
1125 p = strrchr(name, '/');
1126 strncpy(last_component, p ? ++p : name, sizeof(last_component)-1);
1127 last_component[sizeof(last_component)-1] = '\0';
1129 for(; namelist->name != NULL; namelist++)
1131 if(namelist->is_wild)
1133 if (mask_match(last_component, namelist->name, case_sensitive))
1135 DEBUG(8,("is_in_path: mask match succeeded\n"));
1136 return True;
1139 else
1141 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
1142 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
1144 DEBUG(8,("is_in_path: match succeeded\n"));
1145 return True;
1149 DEBUG(8,("is_in_path: match not found\n"));
1151 return False;
1154 /*******************************************************************
1155 Strip a '/' separated list into an array of
1156 name_compare_enties structures suitable for
1157 passing to is_in_path(). We do this for
1158 speed so we can pre-parse all the names in the list
1159 and don't do it for each call to is_in_path().
1160 namelist is modified here and is assumed to be
1161 a copy owned by the caller.
1162 We also check if the entry contains a wildcard to
1163 remove a potentially expensive call to mask_match
1164 if possible.
1165 ********************************************************************/
1167 void set_namearray(name_compare_entry **ppname_array, char *namelist)
1169 char *name_end;
1170 char *nameptr = namelist;
1171 int num_entries = 0;
1172 int i;
1174 (*ppname_array) = NULL;
1176 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
1177 return;
1179 /* We need to make two passes over the string. The
1180 first to count the number of elements, the second
1181 to split it.
1183 while(*nameptr)
1185 if ( *nameptr == '/' )
1187 /* cope with multiple (useless) /s) */
1188 nameptr++;
1189 continue;
1191 /* find the next / */
1192 name_end = strchr(nameptr, '/');
1194 /* oops - the last check for a / didn't find one. */
1195 if (name_end == NULL)
1196 break;
1198 /* next segment please */
1199 nameptr = name_end + 1;
1200 num_entries++;
1203 if(num_entries == 0)
1204 return;
1206 if(( (*ppname_array) = (name_compare_entry *)malloc(
1207 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
1209 DEBUG(0,("set_namearray: malloc fail\n"));
1210 return;
1213 /* Now copy out the names */
1214 nameptr = namelist;
1215 i = 0;
1216 while(*nameptr)
1218 if ( *nameptr == '/' )
1220 /* cope with multiple (useless) /s) */
1221 nameptr++;
1222 continue;
1224 /* find the next / */
1225 if ((name_end = strchr(nameptr, '/')) != NULL)
1227 *name_end = 0;
1230 /* oops - the last check for a / didn't find one. */
1231 if(name_end == NULL)
1232 break;
1234 (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
1235 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
1237 DEBUG(0,("set_namearray: malloc fail (1)\n"));
1238 return;
1241 /* next segment please */
1242 nameptr = name_end + 1;
1243 i++;
1246 (*ppname_array)[i].name = NULL;
1248 return;
1251 /****************************************************************************
1252 routine to free a namearray.
1253 ****************************************************************************/
1255 void free_namearray(name_compare_entry *name_array)
1257 if(name_array == NULL)
1258 return;
1260 SAFE_FREE(name_array->name);
1261 SAFE_FREE(name_array);
1264 /****************************************************************************
1265 Simple routine to do POSIX file locking. Cruft in NFS and 64->32 bit mapping
1266 is dealt with in posix.c
1267 ****************************************************************************/
1269 BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
1271 SMB_STRUCT_FLOCK lock;
1272 int ret;
1274 DEBUG(8,("fcntl_lock %d %d %.0f %.0f %d\n",fd,op,(double)offset,(double)count,type));
1276 lock.l_type = type;
1277 lock.l_whence = SEEK_SET;
1278 lock.l_start = offset;
1279 lock.l_len = count;
1280 lock.l_pid = 0;
1282 errno = 0;
1284 ret = fcntl(fd,op,&lock);
1286 if (errno != 0)
1287 DEBUG(3,("fcntl_lock: fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
1289 /* a lock query */
1290 if (op == SMB_F_GETLK)
1292 if ((ret != -1) &&
1293 (lock.l_type != F_UNLCK) &&
1294 (lock.l_pid != 0) &&
1295 (lock.l_pid != sys_getpid()))
1297 DEBUG(3,("fcntl_lock: fd %d is locked by pid %d\n",fd,(int)lock.l_pid));
1298 return(True);
1301 /* it must be not locked or locked by me */
1302 return(False);
1305 /* a lock set or unset */
1306 if (ret == -1)
1308 DEBUG(3,("fcntl_lock: lock failed at offset %.0f count %.0f op %d type %d (%s)\n",
1309 (double)offset,(double)count,op,type,strerror(errno)));
1310 return(False);
1313 /* everything went OK */
1314 DEBUG(8,("fcntl_lock: Lock call successful\n"));
1316 return(True);
1319 /*******************************************************************
1320 is the name specified one of my netbios names
1321 returns true is it is equal, false otherwise
1322 ********************************************************************/
1323 BOOL is_myname(char *s)
1325 int n;
1326 BOOL ret = False;
1328 for (n=0; my_netbios_names[n]; n++) {
1329 if (strequal(my_netbios_names[n], s))
1330 ret=True;
1332 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
1333 return(ret);
1336 BOOL is_myname_or_ipaddr(char *s)
1338 char *ptr;
1339 pstring nbname;
1341 /* optimize for the common case */
1342 if (strequal(s, global_myname))
1343 return True;
1345 /* maybe its an IP address? */
1346 if (is_ipaddress(s))
1348 struct iface_struct nics[MAX_INTERFACES];
1349 int i, n;
1350 uint32 ip;
1352 ip = interpret_addr(s);
1353 if ((ip==0) || (ip==0xffffffff))
1354 return False;
1356 n = get_interfaces(nics, MAX_INTERFACES);
1357 for (i=0; i<n; i++) {
1358 if (ip == nics[i].ip.s_addr)
1359 return True;
1363 /* check for an alias */
1364 ptr = lp_netbios_aliases();
1365 while ( next_token(&ptr, nbname, NULL, sizeof(nbname)) )
1367 if (StrCaseCmp(s, nbname) == 0)
1368 return True;
1372 /* no match */
1373 return False;
1378 /*******************************************************************
1379 set the horrid remote_arch string based on an enum.
1380 ********************************************************************/
1381 void set_remote_arch(enum remote_arch_types type)
1383 extern fstring remote_arch;
1384 ra_type = type;
1385 switch( type )
1387 case RA_WFWG:
1388 fstrcpy(remote_arch, "WfWg");
1389 return;
1390 case RA_OS2:
1391 fstrcpy(remote_arch, "OS2");
1392 return;
1393 case RA_WIN95:
1394 fstrcpy(remote_arch, "Win95");
1395 return;
1396 case RA_WINNT:
1397 fstrcpy(remote_arch, "WinNT");
1398 return;
1399 case RA_WIN2K:
1400 fstrcpy(remote_arch, "Win2K");
1401 return;
1402 case RA_SAMBA:
1403 fstrcpy(remote_arch,"Samba");
1404 return;
1405 default:
1406 ra_type = RA_UNKNOWN;
1407 fstrcpy(remote_arch, "UNKNOWN");
1408 break;
1412 /*******************************************************************
1413 Get the remote_arch type.
1414 ********************************************************************/
1415 enum remote_arch_types get_remote_arch(void)
1417 return ra_type;
1421 void out_ascii(FILE *f, unsigned char *buf,int len)
1423 int i;
1424 for (i=0;i<len;i++)
1426 fprintf(f, "%c", isprint(buf[i])?buf[i]:'.');
1430 void out_data(FILE *f,char *buf1,int len, int per_line)
1432 unsigned char *buf = (unsigned char *)buf1;
1433 int i=0;
1434 if (len<=0)
1436 return;
1439 fprintf(f, "[%03X] ",i);
1440 for (i=0;i<len;)
1442 fprintf(f, "%02X ",(int)buf[i]);
1443 i++;
1444 if (i%(per_line/2) == 0) fprintf(f, " ");
1445 if (i%per_line == 0)
1447 out_ascii(f,&buf[i-per_line ],per_line/2); fprintf(f, " ");
1448 out_ascii(f,&buf[i-per_line/2],per_line/2); fprintf(f, "\n");
1449 if (i<len) fprintf(f, "[%03X] ",i);
1452 if ((i%per_line) != 0)
1454 int n;
1456 n = per_line - (i%per_line);
1457 fprintf(f, " ");
1458 if (n>(per_line/2)) fprintf(f, " ");
1459 while (n--)
1461 fprintf(f, " ");
1463 n = MIN(per_line/2,i%per_line);
1464 out_ascii(f,&buf[i-(i%per_line)],n); fprintf(f, " ");
1465 n = (i%per_line) - n;
1466 if (n>0) out_ascii(f,&buf[i-n],n);
1467 fprintf(f, "\n");
1471 void print_asc(int level, unsigned char *buf,int len)
1473 int i;
1474 for (i=0;i<len;i++)
1475 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
1478 void dump_data(int level,char *buf1,int len)
1480 unsigned char *buf = (unsigned char *)buf1;
1481 int i=0;
1482 if (len<=0) return;
1484 DEBUG(level,("[%03X] ",i));
1485 for (i=0;i<len;) {
1486 DEBUG(level,("%02X ",(int)buf[i]));
1487 i++;
1488 if (i%8 == 0) DEBUG(level,(" "));
1489 if (i%16 == 0) {
1490 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
1491 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
1492 if (i<len) DEBUG(level,("[%03X] ",i));
1495 if (i%16) {
1496 int n;
1498 n = 16 - (i%16);
1499 DEBUG(level,(" "));
1500 if (n>8) DEBUG(level,(" "));
1501 while (n--) DEBUG(level,(" "));
1503 n = MIN(8,i%16);
1504 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
1505 n = (i%16) - n;
1506 if (n>0) print_asc(level,&buf[i-n],n);
1507 DEBUG(level,("\n"));
1511 char *tab_depth(int depth)
1513 static pstring spaces;
1514 memset(spaces, ' ', depth * 4);
1515 spaces[depth * 4] = 0;
1516 return spaces;
1519 /*****************************************************************************
1520 * Provide a checksum on a string
1522 * Input: s - the null-terminated character string for which the checksum
1523 * will be calculated.
1525 * Output: The checksum value calculated for s.
1527 * ****************************************************************************
1529 int str_checksum(const char *s)
1531 int res = 0;
1532 int c;
1533 int i=0;
1535 while(*s) {
1536 c = *s;
1537 res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
1538 s++;
1539 i++;
1541 return(res);
1542 } /* str_checksum */
1546 /*****************************************************************
1547 zero a memory area then free it. Used to catch bugs faster
1548 *****************************************************************/
1549 void zero_free(void *p, size_t size)
1551 memset(p, 0, size);
1552 SAFE_FREE(p);
1556 /*****************************************************************
1557 set our open file limit to a requested max and return the limit
1558 *****************************************************************/
1559 int set_maxfiles(int requested_max)
1561 #if (defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE))
1562 struct rlimit rlp;
1563 int saved_current_limit;
1565 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1566 DEBUG(0,("set_maxfiles: getrlimit (1) for RLIMIT_NOFILE failed with error %s\n",
1567 strerror(errno) ));
1568 /* just guess... */
1569 return requested_max;
1573 * Set the fd limit to be real_max_open_files + MAX_OPEN_FUDGEFACTOR to
1574 * account for the extra fd we need
1575 * as well as the log files and standard
1576 * handles etc. Save the limit we want to set in case
1577 * we are running on an OS that doesn't support this limit (AIX)
1578 * which always returns RLIM_INFINITY for rlp.rlim_max.
1581 /* Try raising the hard (max) limit to the requested amount. */
1583 #if defined(RLIM_INFINITY)
1584 if (rlp.rlim_max != RLIM_INFINITY) {
1585 int orig_max = rlp.rlim_max;
1587 if ( rlp.rlim_max < requested_max )
1588 rlp.rlim_max = requested_max;
1590 /* This failing is not an error - many systems (Linux) don't
1591 support our default request of 10,000 open files. JRA. */
1593 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1594 DEBUG(3,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d max files failed with error %s\n",
1595 (int)rlp.rlim_max, strerror(errno) ));
1597 /* Set failed - restore original value from get. */
1598 rlp.rlim_max = orig_max;
1601 #endif
1603 /* Now try setting the soft (current) limit. */
1605 saved_current_limit = rlp.rlim_cur = MIN(requested_max,rlp.rlim_max);
1607 if(setrlimit(RLIMIT_NOFILE, &rlp)) {
1608 DEBUG(0,("set_maxfiles: setrlimit for RLIMIT_NOFILE for %d files failed with error %s\n",
1609 (int)rlp.rlim_cur, strerror(errno) ));
1610 /* just guess... */
1611 return saved_current_limit;
1614 if(getrlimit(RLIMIT_NOFILE, &rlp)) {
1615 DEBUG(0,("set_maxfiles: getrlimit (2) for RLIMIT_NOFILE failed with error %s\n",
1616 strerror(errno) ));
1617 /* just guess... */
1618 return saved_current_limit;
1621 #if defined(RLIM_INFINITY)
1622 if(rlp.rlim_cur == RLIM_INFINITY)
1623 return saved_current_limit;
1624 #endif
1626 if((int)rlp.rlim_cur > saved_current_limit)
1627 return saved_current_limit;
1629 return rlp.rlim_cur;
1630 #else /* !defined(HAVE_GETRLIMIT) || !defined(RLIMIT_NOFILE) */
1632 * No way to know - just guess...
1634 return requested_max;
1635 #endif
1638 /*****************************************************************
1639 splits out the start of the key (HKLM or HKU) and the rest of the key
1640 *****************************************************************/
1641 BOOL reg_split_key(char *full_keyname, uint32 *reg_type, char *key_name)
1643 pstring tmp;
1645 if (!next_token(&full_keyname, tmp, "\\", sizeof(tmp)))
1647 return False;
1650 (*reg_type) = 0;
1652 DEBUG(10, ("reg_split_key: hive %s\n", tmp));
1654 if (strequal(tmp, "HKLM") || strequal(tmp, "HKEY_LOCAL_MACHINE"))
1656 (*reg_type) = HKEY_LOCAL_MACHINE;
1658 else if (strequal(tmp, "HKU") || strequal(tmp, "HKEY_USERS"))
1660 (*reg_type) = HKEY_USERS;
1662 else
1664 DEBUG(10,("reg_split_key: unrecognised hive key %s\n", tmp));
1665 return False;
1668 if (next_token(NULL, tmp, "\n\r", sizeof(tmp)))
1670 fstrcpy(key_name, tmp);
1672 else
1674 key_name[0] = 0;
1677 DEBUG(10, ("reg_split_key: name %s\n", key_name));
1679 return True;
1683 /*****************************************************************
1684 possibly replace mkstemp if it is broken
1685 *****************************************************************/
1686 int smb_mkstemp(char *template)
1688 #if HAVE_SECURE_MKSTEMP
1689 return mkstemp(template);
1690 #else
1691 /* have a reasonable go at emulating it. Hope that
1692 the system mktemp() isn't completly hopeless */
1693 char *p = mktemp(template);
1694 if (!p) return -1;
1695 return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
1696 #endif
1699 /*****************************************************************
1700 malloc that aborts with smb_panic on fail or zero size.
1701 *****************************************************************/
1703 void *smb_xmalloc(size_t size)
1705 void *p;
1706 if (size == 0)
1707 smb_panic("smb_xmalloc: called with zero size.\n");
1708 if ((p = malloc(size)) == NULL)
1709 smb_panic("smb_xmalloc: malloc fail.\n");
1710 return p;
1713 /*****************************************************************
1714 Memdup with smb_panic on fail.
1715 *****************************************************************/
1717 void *xmemdup(const void *p, size_t size)
1719 void *p2;
1720 p2 = smb_xmalloc(size);
1721 memcpy(p2, p, size);
1722 return p2;
1725 /*****************************************************************
1726 strdup that aborts on malloc fail.
1727 *****************************************************************/
1729 char *xstrdup(const char *s)
1731 char *s1 = strdup(s);
1732 if (!s1)
1733 smb_panic("xstrdup: malloc fail\n");
1734 return s1;
1737 /*****************************************************************
1738 like strdup but for memory
1739 *****************************************************************/
1740 void *memdup(void *p, size_t size)
1742 void *p2;
1743 if (size == 0) return NULL;
1744 p2 = malloc(size);
1745 if (!p2) return NULL;
1746 memcpy(p2, p, size);
1747 return p2;
1750 /*****************************************************************
1751 get local hostname and cache result
1752 *****************************************************************/
1753 char *myhostname(void)
1755 static pstring ret;
1756 if (ret[0] == 0) {
1757 get_myname(ret);
1759 return ret;
1763 /*****************************************************************
1764 a useful function for returning a path in the Samba lock directory
1765 *****************************************************************/
1766 char *lock_path(char *name)
1768 static pstring fname;
1770 pstrcpy(fname,lp_lockdir());
1771 trim_string(fname,"","/");
1773 if (!directory_exist(fname,NULL)) {
1774 mkdir(fname,0755);
1777 pstrcat(fname,"/");
1778 pstrcat(fname,name);
1780 return fname;
1783 /*******************************************************************
1784 Given a filename - get its directory name
1785 NB: Returned in static storage. Caveats:
1786 o Not safe in thread environment.
1787 o Caller must not free.
1788 o If caller wishes to preserve, they should copy.
1789 ********************************************************************/
1791 char *parent_dirname(const char *path)
1793 static pstring dirpath;
1794 char *p;
1796 if (!path)
1797 return(NULL);
1799 pstrcpy(dirpath, path);
1800 p = strrchr(dirpath, '/'); /* Find final '/', if any */
1801 if (!p) {
1802 pstrcpy(dirpath, "."); /* No final "/", so dir is "." */
1803 } else {
1804 if (p == dirpath)
1805 ++p; /* For root "/", leave "/" in place */
1806 *p = '\0';
1808 return dirpath;
1812 /*******************************************************************
1813 determine if a pattern contains any Microsoft wildcard characters
1814 *******************************************************************/
1815 BOOL ms_has_wild(char *s)
1817 char c;
1818 while ((c = *s++)) {
1819 switch (c) {
1820 case '*':
1821 case '?':
1822 case '<':
1823 case '>':
1824 case '"':
1825 return True;
1828 return False;
1831 /*******************************************************************
1832 a wrapper that handles case sensitivity and the special handling
1833 of the ".." name
1834 *******************************************************************/
1835 BOOL mask_match(char *string, char *pattern, BOOL is_case_sensitive)
1837 fstring p2, s2;
1838 if (strcmp(string,"..") == 0) string = ".";
1839 if (strcmp(pattern,".") == 0) return False;
1841 if (is_case_sensitive) {
1842 return ms_fnmatch(pattern, string) == 0;
1845 fstrcpy(p2, pattern);
1846 fstrcpy(s2, string);
1847 strlower(p2);
1848 strlower(s2);
1849 return ms_fnmatch(p2, s2) == 0;
1852 /*********************************************************
1853 Recursive routine that is called by unix_wild_match.
1854 *********************************************************/
1856 static BOOL unix_do_match(char *regexp, char *str)
1858 char *p;
1860 for( p = regexp; *p && *str; ) {
1862 switch(*p) {
1863 case '?':
1864 str++;
1865 p++;
1866 break;
1868 case '*':
1871 * Look for a character matching
1872 * the one after the '*'.
1874 p++;
1875 if(!*p)
1876 return True; /* Automatic match */
1877 while(*str) {
1879 while(*str && (*p != *str))
1880 str++;
1883 * Patch from weidel@multichart.de. In the case of the regexp
1884 * '*XX*' we want to ensure there are at least 2 'X' characters
1885 * in the string after the '*' for a match to be made.
1889 int matchcount=0;
1892 * Eat all the characters that match, but count how many there were.
1895 while(*str && (*p == *str)) {
1896 str++;
1897 matchcount++;
1901 * Now check that if the regexp had n identical characters that
1902 * matchcount had at least that many matches.
1905 while ( *(p+1) && (*(p+1) == *p)) {
1906 p++;
1907 matchcount--;
1910 if ( matchcount <= 0 )
1911 return False;
1914 str--; /* We've eaten the match char after the '*' */
1916 if(unix_do_match(p, str))
1917 return True;
1919 if(!*str)
1920 return False;
1921 else
1922 str++;
1924 return False;
1926 default:
1927 if(*str != *p)
1928 return False;
1929 str++;
1930 p++;
1931 break;
1935 if(!*p && !*str)
1936 return True;
1938 if (!*p && str[0] == '.' && str[1] == 0)
1939 return(True);
1941 if (!*str && *p == '?') {
1942 while (*p == '?')
1943 p++;
1944 return(!*p);
1947 if(!*str && (*p == '*' && p[1] == '\0'))
1948 return True;
1950 return False;
1953 /*******************************************************************
1954 Simple case insensitive interface to a UNIX wildcard matcher.
1955 *******************************************************************/
1957 BOOL unix_wild_match(char *pattern, char *string)
1959 pstring p2, s2;
1960 char *p;
1962 pstrcpy(p2, pattern);
1963 pstrcpy(s2, string);
1964 strlower(p2);
1965 strlower(s2);
1967 /* Remove any *? and ** from the pattern as they are meaningless */
1968 for(p = p2; *p; p++)
1969 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
1970 pstrcpy( &p[1], &p[2]);
1972 if (strequal(p2,"*"))
1973 return True;
1975 return unix_do_match(p2, s2) == 0;
1978 #ifdef __INSURE__
1980 /*******************************************************************
1981 This routine is a trick to immediately catch errors when debugging
1982 with insure. A xterm with a gdb is popped up when insure catches
1983 a error. It is Linux specific.
1984 ********************************************************************/
1985 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1987 static int (*fn)();
1988 int ret;
1989 char pidstr[10];
1990 pstring cmd = "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'";
1992 slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
1993 pstring_sub(cmd, "%d", pidstr);
1995 if (!fn) {
1996 static void *h;
1997 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1998 fn = dlsym(h, "_Insure_trap_error");
2001 ret = fn(a1, a2, a3, a4, a5, a6);
2003 system(cmd);
2005 return ret;
2007 #endif