2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1995
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 int Protocol = PROTOCOL_COREPLUS;
33 /* a default finfo structure to ensure all fields are sensible */
34 file_info def_finfo = {-1,0,0,0,0,0,0,""};
36 /* these are some file handles where debug info will be stored */
39 /* the client file descriptor */
42 /* info on the client */
43 struct from_host Client_info=
44 {"UNKNOWN","0.0.0.0",NULL};
46 /* the last IP received from */
47 struct in_addr lastip;
49 /* the last port received from */
55 case handling on filenames
57 int case_default = CASE_LOWER;
59 pstring debugf = "/tmp/log.samba";
62 /* the following control case operations - they are put here so the
63 client can link easily */
66 BOOL use_mangled_map = False;
67 BOOL short_case_preserve;
70 fstring remote_machine="";
71 fstring local_machine="";
72 fstring remote_arch="UNKNOWN";
73 fstring remote_proto="UNKNOWN";
74 pstring myhostname="";
75 pstring user_socket_options="";
76 pstring sesssetup_user="";
79 static char *filename_dos(char *path,char *buf);
81 static BOOL stdout_logging = False;
84 /*******************************************************************
85 get ready for syslog stuff
86 ******************************************************************/
87 void setup_logging(char *pname,BOOL interactive)
91 char *p = strrchr(pname,'/');
93 openlog(pname, LOG_PID, LOG_DAEMON);
97 stdout_logging = True;
103 BOOL append_log=False;
106 /****************************************************************************
108 ****************************************************************************/
109 void reopen_logs(void)
116 strcpy(fname,debugf);
117 if (lp_loaded() && (*lp_logfile()))
118 strcpy(fname,lp_logfile());
120 if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
122 strcpy(debugf,fname);
123 if (dbf) fclose(dbf);
125 dbf = fopen(debugf,"a");
127 dbf = fopen(debugf,"w");
128 if (dbf) setbuf(dbf,NULL);
142 /*******************************************************************
143 check if the log has grown too big
144 ********************************************************************/
145 static void check_log_size(void)
147 static int debug_count=0;
151 if (debug_count++ < 100) return;
153 maxlog = lp_max_log_size() * 1024;
154 if (!dbf || maxlog <= 0) return;
156 if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
157 fclose(dbf); dbf = NULL;
159 if (dbf && file_size(debugf) > maxlog) {
161 fclose(dbf); dbf = NULL;
162 sprintf(name,"%s.old",debugf);
163 sys_rename(debugf,name);
171 /*******************************************************************
172 write an debug message on the debugfile. This is called by the DEBUG
174 ********************************************************************/
176 int Debug1(char *format_str, ...)
186 if (stdout_logging) {
188 va_start(ap, format_str);
191 format_str = va_arg(ap,char *);
193 vfprintf(dbf,format_str,ap);
199 if (!lp_syslog_only())
204 dbf = fopen(debugf,"w");
213 if (syslog_level < lp_syslog())
216 * map debug levels to syslog() priorities
217 * note that not all DEBUG(0, ...) calls are
220 static int priority_map[] = {
229 if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
231 priority = LOG_DEBUG;
233 priority = priority_map[syslog_level];
236 va_start(ap, format_str);
239 format_str = va_arg(ap,char *);
241 vsprintf(msgbuf, format_str, ap);
245 syslog(priority, "%s", msgbuf);
250 if (!lp_syslog_only())
254 va_start(ap, format_str);
257 format_str = va_arg(ap,char *);
259 vfprintf(dbf,format_str,ap);
269 /****************************************************************************
270 routine to do file locking
271 ****************************************************************************/
272 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
279 uint32 mask = 0xC0000000;
281 /* make sure the count is reasonable, we might kill the lockd otherwise */
284 /* the offset is often strange - remove 2 of its bits if either of
285 the top two bits are set. Shift the top ones by two bits. This
286 still allows OLE2 apps to operate, but should stop lockd from
288 if ((offset & mask) != 0)
289 offset = (offset & ~mask) | ((offset & mask) >> 2);
291 unsigned long mask = ((unsigned)1<<31);
293 /* interpret negative counts as large numbers */
297 /* no negative offsets */
300 /* count + offset must be in range */
301 while ((offset < 0 || (offset + count < 0)) && mask)
309 DEBUG(5,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
312 lock.l_whence = SEEK_SET;
313 lock.l_start = (int)offset;
314 lock.l_len = (int)count;
319 ret = fcntl(fd,op,&lock);
322 DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
328 (lock.l_type != F_UNLCK) &&
330 (lock.l_pid != getpid()))
332 DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
336 /* it must be not locked or locked by me */
340 /* a lock set or unset */
343 DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
344 offset,count,op,type,strerror(errno)));
346 /* perhaps it doesn't support this sort of locking?? */
349 DEBUG(3,("locking not supported? returning True\n"));
356 /* everything went OK */
357 DEBUG(5,("Lock call successful\n"));
365 /*******************************************************************
366 lock a file - returning a open file descriptor or -1 on failure
367 The timeout is in seconds. 0 means no timeout
368 ********************************************************************/
369 int file_lock(char *name,int timeout)
371 int fd = open(name,O_RDWR|O_CREAT,0666);
373 if (fd < 0) return(-1);
376 if (timeout) t = time(NULL);
377 while (!timeout || (time(NULL)-t < timeout)) {
378 if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);
379 msleep(LOCK_RETRY_TIMEOUT);
387 /*******************************************************************
388 unlock a file locked by file_lock
389 ********************************************************************/
390 void file_unlock(int fd)
394 fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
399 /****************************************************************************
400 determine if a file descriptor is in fact a socket
401 ****************************************************************************/
402 BOOL is_a_socket(int fd)
406 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
410 static char *last_ptr=NULL;
412 /****************************************************************************
413 Get the next token from a string, return False if none found
414 handles double-quotes.
415 Based on a routine by GJC@VILLAGE.COM.
416 Extensively modified by Andrew.Tridgell@anu.edu.au
417 ****************************************************************************/
418 BOOL next_token(char **ptr,char *buff,char *sep)
423 if (!ptr) ptr = &last_ptr;
424 if (!ptr) return(False);
428 /* default to simple separators */
429 if (!sep) sep = " \t\n\r";
431 /* find the first non sep char */
432 while(*s && strchr(sep,*s)) s++;
435 if (! *s) return(False);
437 /* copy over the token */
438 for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
446 *ptr = (*s) ? s+1 : s;
453 /****************************************************************************
454 Convert list of tokens to array; dependent on above routine.
455 Uses last_ptr from above - bit of a hack.
456 ****************************************************************************/
457 char **toktocliplist(int *ctok, char *sep)
463 if (!sep) sep = " \t\n\r";
465 while(*s && strchr(sep,*s)) s++;
468 if (!*s) return(NULL);
472 while(*s && (!strchr(sep,*s))) s++;
473 while(*s && strchr(sep,*s)) *s++=0;
479 if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
491 /*******************************************************************
492 safely copies memory, ensuring no overlap problems.
493 this is only used if the machine does not have it's own memmove().
494 this is not the fastest algorithm in town, but it will do for our
496 ********************************************************************/
497 void *MemMove(void *dest,void *src,int size)
501 if (dest==src || !size) return(dest);
503 d = (unsigned long)dest;
504 s = (unsigned long)src;
506 if ((d >= (s+size)) || (s >= (d+size))) {
508 memcpy(dest,src,size);
514 /* we can forward copy */
515 if (s-d >= sizeof(int) &&
516 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
517 /* do it all as words */
518 int *idest = (int *)dest;
519 int *isrc = (int *)src;
521 for (i=0;i<size;i++) idest[i] = isrc[i];
524 char *cdest = (char *)dest;
525 char *csrc = (char *)src;
526 for (i=0;i<size;i++) cdest[i] = csrc[i];
531 /* must backward copy */
532 if (d-s >= sizeof(int) &&
533 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
534 /* do it all as words */
535 int *idest = (int *)dest;
536 int *isrc = (int *)src;
538 for (i=size-1;i>=0;i--) idest[i] = isrc[i];
541 char *cdest = (char *)dest;
542 char *csrc = (char *)src;
543 for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
551 /****************************************************************************
552 prompte a dptr (to make it recently used)
553 ****************************************************************************/
554 void array_promote(char *array,int elsize,int element)
560 p = (char *)malloc(elsize);
564 DEBUG(5,("Ahh! Can't malloc\n"));
567 memcpy(p,array + element * elsize, elsize);
568 memmove(array + elsize,array,elsize*element);
569 memcpy(array,p,elsize);
573 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
582 } socket_options[] = {
583 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
584 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
585 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
587 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
589 #ifdef IPTOS_LOWDELAY
590 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
592 #ifdef IPTOS_THROUGHPUT
593 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
596 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
599 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
602 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
605 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
611 /****************************************************************************
612 set user socket options
613 ****************************************************************************/
614 void set_socket_options(int fd, char *options)
618 while (next_token(&options,tok," \t,"))
623 BOOL got_value = False;
625 if ((p = strchr(tok,'=')))
632 for (i=0;socket_options[i].name;i++)
633 if (strequal(socket_options[i].name,tok))
636 if (!socket_options[i].name)
638 DEBUG(0,("Unknown socket option %s\n",tok));
642 switch (socket_options[i].opttype)
646 ret = setsockopt(fd,socket_options[i].level,
647 socket_options[i].option,(char *)&value,sizeof(int));
652 DEBUG(0,("syntax error - %s does not take a value\n",tok));
655 int on = socket_options[i].value;
656 ret = setsockopt(fd,socket_options[i].level,
657 socket_options[i].option,(char *)&on,sizeof(int));
663 DEBUG(0,("Failed to set socket option %s\n",tok));
669 /****************************************************************************
670 close the socket communication
671 ****************************************************************************/
672 void close_sockets(void )
678 /****************************************************************************
679 determine whether we are in the specified group
680 ****************************************************************************/
681 BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
685 if (group == current_gid) return(True);
687 for (i=0;i<ngroups;i++)
688 if (group == groups[i])
694 /****************************************************************************
695 this is a safer strcpy(), meant to prevent core dumps when nasty things happen
696 ****************************************************************************/
697 char *StrCpy(char *dest,char *src)
702 /* I don't want to get lazy with these ... */
704 DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
709 if (!dest) return(NULL);
714 while ((*d++ = *src++)) ;
718 /****************************************************************************
719 line strncpy but always null terminates. Make sure there is room!
720 ****************************************************************************/
721 char *StrnCpy(char *dest,const char *src,int n)
724 if (!dest) return(NULL);
729 while (n-- && (*d++ = *src++)) ;
735 /*******************************************************************
736 copy an IP address from one buffer to another
737 ********************************************************************/
738 void putip(void *dest,void *src)
744 /****************************************************************************
745 interpret the weird netbios "name". Return the name type
746 ****************************************************************************/
747 static int name_interpret(char *in,char *out)
750 int len = (*in++) / 2;
754 if (len > 30 || len<1) return(0);
758 if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
762 *out = ((in[0]-'A')<<4) + (in[1]-'A');
770 /* Handle any scope names */
773 *out++ = '.'; /* Scope names are separated by periods */
774 len = *(unsigned char *)in++;
775 StrnCpy(out, in, len);
784 /****************************************************************************
785 mangle a name into netbios format
786 ****************************************************************************/
787 int name_mangle(char *In,char *Out,char name_type)
791 char *in = (char *)&buf[0];
792 char *out = (char *)Out;
797 StrnCpy(name,In,sizeof(name)-1);
798 sprintf(buf,"%-15.15s%c",name,name_type);
801 memset(&buf[1],0,16);
806 char c = toupper(in[i]);
807 out[i*2] = (c>>4) + 'A';
808 out[i*2+1] = (c & 0xF) + 'A';
816 p = strchr(label, '.');
818 p = label + strlen(label);
820 memcpy(out, label, p - label);
822 label += p - label + (*p == '.');
825 return(name_len(Out));
829 /*******************************************************************
830 check if a file exists
831 ********************************************************************/
832 BOOL file_exist(char *fname,struct stat *sbuf)
835 if (!sbuf) sbuf = &st;
837 if (sys_stat(fname,sbuf) != 0)
840 return(S_ISREG(sbuf->st_mode));
843 /*******************************************************************
844 check a files mod time
845 ********************************************************************/
846 time_t file_modtime(char *fname)
850 if (sys_stat(fname,&st) != 0)
856 /*******************************************************************
857 check if a directory exists
858 ********************************************************************/
859 BOOL directory_exist(char *dname,struct stat *st)
864 if (sys_stat(dname,st) != 0)
867 return(S_ISDIR(st->st_mode));
870 /*******************************************************************
871 returns the size in bytes of the named file
872 ********************************************************************/
873 uint32 file_size(char *file_name)
877 sys_stat(file_name,&buf);
881 /*******************************************************************
882 return a string representing an attribute for a file
883 ********************************************************************/
884 char *attrib_string(int mode)
886 static char attrstr[10];
890 if (mode & aVOLID) strcat(attrstr,"V");
891 if (mode & aDIR) strcat(attrstr,"D");
892 if (mode & aARCH) strcat(attrstr,"A");
893 if (mode & aHIDDEN) strcat(attrstr,"H");
894 if (mode & aSYSTEM) strcat(attrstr,"S");
895 if (mode & aRONLY) strcat(attrstr,"R");
901 /*******************************************************************
902 case insensitive string compararison
903 ********************************************************************/
904 int StrCaseCmp(char *s, char *t)
906 for (; tolower(*s) == tolower(*t); ++s, ++t)
909 return tolower(*s) - tolower(*t);
912 /*******************************************************************
913 case insensitive string compararison, length limited
914 ********************************************************************/
915 int StrnCaseCmp(char *s, char *t, int n)
917 while (n-- && *s && *t) {
918 if (tolower(*s) != tolower(*t)) return(tolower(*s) - tolower(*t));
921 if (n) return(tolower(*s) - tolower(*t));
926 /*******************************************************************
928 ********************************************************************/
929 BOOL strequal(char *s1,char *s2)
931 if (s1 == s2) return(True);
932 if (!s1 || !s2) return(False);
934 return(StrCaseCmp(s1,s2)==0);
937 /*******************************************************************
938 compare 2 strings up to and including the nth char.
939 ******************************************************************/
940 BOOL strnequal(char *s1,char *s2,int n)
942 if (s1 == s2) return(True);
943 if (!s1 || !s2 || !n) return(False);
945 return(StrnCaseCmp(s1,s2,n)==0);
948 /*******************************************************************
949 compare 2 strings (case sensitive)
950 ********************************************************************/
951 BOOL strcsequal(char *s1,char *s2)
953 if (s1 == s2) return(True);
954 if (!s1 || !s2) return(False);
956 return(strcmp(s1,s2)==0);
960 /*******************************************************************
961 convert a string to lower case
962 ********************************************************************/
963 void strlower(char *s)
968 if (is_shift_jis (*s)) {
970 } else if (is_kana (*s)) {
985 /*******************************************************************
986 convert a string to upper case
987 ********************************************************************/
988 void strupper(char *s)
993 if (is_shift_jis (*s)) {
995 } else if (is_kana (*s)) {
1010 /*******************************************************************
1011 convert a string to "normal" form
1012 ********************************************************************/
1013 void strnorm(char *s)
1015 if (case_default == CASE_UPPER)
1021 /*******************************************************************
1022 check if a string is in "normal" case
1023 ********************************************************************/
1024 BOOL strisnormal(char *s)
1026 if (case_default == CASE_UPPER)
1027 return(!strhaslower(s));
1029 return(!strhasupper(s));
1033 /****************************************************************************
1035 ****************************************************************************/
1036 void string_replace(char *s,char oldc,char newc)
1041 if (is_shift_jis (*s)) {
1043 } else if (is_kana (*s)) {
1058 /****************************************************************************
1059 make a file into unix format
1060 ****************************************************************************/
1061 void unix_format(char *fname)
1064 string_replace(fname,'\\','/');
1066 dos2unix_format(fname, True);
1071 strcpy(namecopy,fname);
1073 strcat(fname,namecopy);
1077 /****************************************************************************
1078 make a file into dos format
1079 ****************************************************************************/
1080 void dos_format(char *fname)
1083 unix2dos_format(fname, True);
1085 string_replace(fname,'/','\\');
1089 /*******************************************************************
1090 show a smb message structure
1091 ********************************************************************/
1092 void show_msg(char *buf)
1099 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
1101 (int)CVAL(buf,smb_com),
1102 (int)CVAL(buf,smb_rcls),
1103 (int)CVAL(buf,smb_reh),
1104 (int)SVAL(buf,smb_err),
1105 (int)CVAL(buf,smb_flg),
1106 (int)SVAL(buf,smb_flg2)));
1107 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
1108 (int)SVAL(buf,smb_tid),
1109 (int)SVAL(buf,smb_pid),
1110 (int)SVAL(buf,smb_uid),
1111 (int)SVAL(buf,smb_mid),
1112 (int)CVAL(buf,smb_wct)));
1113 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
1114 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
1115 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
1116 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
1117 DEBUG(5,("smb_bcc=%d\n",bcc));
1118 if (DEBUGLEVEL < 10)
1120 for (i=0;i<MIN(bcc,128);i++)
1121 DEBUG(10,("%X ",CVAL(smb_buf(buf),i)));
1125 /*******************************************************************
1126 return the length of an smb packet
1127 ********************************************************************/
1128 int smb_len(char *buf)
1130 return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
1133 /*******************************************************************
1134 set the length of an smb packet
1135 ********************************************************************/
1136 void _smb_setlen(char *buf,int len)
1139 buf[1] = (len&0x10000)>>16;
1140 buf[2] = (len&0xFF00)>>8;
1144 /*******************************************************************
1145 set the length and marker of an smb packet
1146 ********************************************************************/
1147 void smb_setlen(char *buf,int len)
1149 _smb_setlen(buf,len);
1157 /*******************************************************************
1158 setup the word count and byte count for a smb message
1159 ********************************************************************/
1160 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
1163 bzero(buf + smb_size,num_words*2 + num_bytes);
1164 CVAL(buf,smb_wct) = num_words;
1165 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
1166 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
1167 return (smb_size + num_words*2 + num_bytes);
1170 /*******************************************************************
1171 return the number of smb words
1172 ********************************************************************/
1173 int smb_numwords(char *buf)
1175 return (CVAL(buf,smb_wct));
1178 /*******************************************************************
1179 return the size of the smb_buf region of a message
1180 ********************************************************************/
1181 int smb_buflen(char *buf)
1183 return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
1186 /*******************************************************************
1187 return a pointer to the smb_buf data area
1188 ********************************************************************/
1189 int smb_buf_ofs(char *buf)
1191 return (smb_size + CVAL(buf,smb_wct)*2);
1194 /*******************************************************************
1195 return a pointer to the smb_buf data area
1196 ********************************************************************/
1197 char *smb_buf(char *buf)
1199 return (buf + smb_buf_ofs(buf));
1202 /*******************************************************************
1203 return the SMB offset into an SMB buffer
1204 ********************************************************************/
1205 int smb_offset(char *p,char *buf)
1207 return(PTR_DIFF(p,buf+4));
1211 /*******************************************************************
1212 skip past some strings in a buffer
1213 ********************************************************************/
1214 char *skip_string(char *buf,int n)
1217 buf += strlen(buf) + 1;
1221 /*******************************************************************
1222 trim the specified elements off the front and back of a string
1223 ********************************************************************/
1224 BOOL trim_string(char *s,char *front,char *back)
1227 while (front && *front && strncmp(s,front,strlen(front)) == 0)
1233 if (!(*p = p[strlen(front)]))
1238 while (back && *back && strlen(s) >= strlen(back) &&
1239 (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))
1242 s[strlen(s)-strlen(back)] = 0;
1248 /*******************************************************************
1249 reduce a file name, removing .. elements.
1250 ********************************************************************/
1251 void dos_clean_name(char *s)
1255 DEBUG(3,("dos_clean_name [%s]\n",s));
1257 /* remove any double slashes */
1258 string_sub(s, "\\\\", "\\");
1260 while ((p = strstr(s,"\\..\\")) != NULL)
1267 if ((p=strrchr(s,'\\')) != NULL)
1274 trim_string(s,NULL,"\\..");
1276 string_sub(s, "\\.\\", "\\");
1279 /*******************************************************************
1280 reduce a file name, removing .. elements.
1281 ********************************************************************/
1282 void unix_clean_name(char *s)
1286 DEBUG(3,("unix_clean_name [%s]\n",s));
1288 /* remove any double slashes */
1289 string_sub(s, "//","/");
1291 while ((p = strstr(s,"/../")) != NULL)
1298 if ((p=strrchr(s,'/')) != NULL)
1305 trim_string(s,NULL,"/..");
1309 /*******************************************************************
1310 a wrapper for the normal chdir() function
1311 ********************************************************************/
1312 int ChDir(char *path)
1315 static pstring LastDir="";
1317 if (strcsequal(path,".")) return(0);
1319 if (*path == '/' && strcsequal(LastDir,path)) return(0);
1320 DEBUG(3,("chdir to %s\n",path));
1321 res = sys_chdir(path);
1323 strcpy(LastDir,path);
1328 /*******************************************************************
1329 return the absolute current directory path. A dumb version.
1330 ********************************************************************/
1331 static char *Dumb_GetWd(char *s)
1334 return ((char *)getcwd(s,sizeof(pstring)));
1336 return ((char *)getwd(s));
1341 /* number of list structures for a caching GetWd function. */
1342 #define MAX_GETWDCACHE (50)
1350 } ino_list[MAX_GETWDCACHE];
1352 BOOL use_getwd_cache=True;
1354 /*******************************************************************
1355 return the absolute current directory path
1356 ********************************************************************/
1357 char *GetWd(char *str)
1360 static BOOL getwd_cache_init = False;
1361 struct stat st, st2;
1366 if (!use_getwd_cache)
1367 return(Dumb_GetWd(str));
1369 /* init the cache */
1370 if (!getwd_cache_init)
1372 getwd_cache_init = True;
1373 for (i=0;i<MAX_GETWDCACHE;i++)
1375 string_init(&ino_list[i].text,"");
1376 ino_list[i].valid = False;
1380 /* Get the inode of the current directory, if this doesn't work we're
1383 if (stat(".",&st) == -1)
1385 DEBUG(0,("Very strange, couldn't stat \".\"\n"));
1386 return(Dumb_GetWd(str));
1390 for (i=0; i<MAX_GETWDCACHE; i++)
1391 if (ino_list[i].valid)
1394 /* If we have found an entry with a matching inode and dev number
1395 then find the inode number for the directory in the cached string.
1396 If this agrees with that returned by the stat for the current
1397 directory then all is o.k. (but make sure it is a directory all
1400 if (st.st_ino == ino_list[i].inode &&
1401 st.st_dev == ino_list[i].dev)
1403 if (stat(ino_list[i].text,&st2) == 0)
1405 if (st.st_ino == st2.st_ino &&
1406 st.st_dev == st2.st_dev &&
1407 (st2.st_mode & S_IFMT) == S_IFDIR)
1409 strcpy (str, ino_list[i].text);
1411 /* promote it for future use */
1412 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1417 /* If the inode is different then something's changed,
1418 scrub the entry and start from scratch. */
1419 ino_list[i].valid = False;
1426 /* We don't have the information to hand so rely on traditional methods.
1427 The very slow getcwd, which spawns a process on some systems, or the
1428 not quite so bad getwd. */
1432 DEBUG(0,("Getwd failed, errno %d\n",errno));
1438 DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
1440 /* add it to the cache */
1441 i = MAX_GETWDCACHE - 1;
1442 string_set(&ino_list[i].text,s);
1443 ino_list[i].dev = st.st_dev;
1444 ino_list[i].inode = st.st_ino;
1445 ino_list[i].valid = True;
1447 /* put it at the top of the list */
1448 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1455 /*******************************************************************
1456 reduce a file name, removing .. elements and checking that
1457 it is below dir in the heirachy. This uses GetWd() and so must be run
1458 on the system that has the referenced file system.
1460 widelinks are allowed if widelinks is true
1461 ********************************************************************/
1462 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
1464 #ifndef REDUCE_PATHS
1472 BOOL relative = (*s != '/');
1474 *dir2 = *wd = *basename = *newname = 0;
1479 /* can't have a leading .. */
1480 if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
1482 DEBUG(3,("Illegal file name? (%s)\n",s));
1488 DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
1490 /* remove any double slashes */
1491 string_sub(s,"//","/");
1494 p = strrchr(basename,'/');
1501 DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
1505 if (ChDir(dir) != 0)
1507 DEBUG(0,("couldn't chdir to %s\n",dir));
1513 DEBUG(0,("couldn't getwd for %s\n",dir));
1519 if (p && (p != basename))
1522 if (strcmp(p+1,".")==0)
1524 if (strcmp(p+1,"..")==0)
1528 if (ChDir(basename) != 0)
1531 DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,basename));
1535 if (!GetWd(newname))
1538 DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
1542 if (p && (p != basename))
1544 strcat(newname,"/");
1545 strcat(newname,p+1);
1549 int l = strlen(dir2);
1550 if (dir2[l-1] == '/')
1553 if (strncmp(newname,dir2,l) != 0)
1556 DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
1562 if (newname[l] == '/')
1563 strcpy(s,newname + l + 1);
1565 strcpy(s,newname+l);
1576 DEBUG(3,("reduced to %s\n",s));
1581 /****************************************************************************
1583 ****************************************************************************/
1584 static void expand_one(char *Mask,int len)
1587 while ((p1 = strchr(Mask,'*')) != NULL)
1589 int lfill = (len+1) - strlen(Mask);
1590 int l1= (p1 - Mask);
1593 memset(tmp+l1,'?',lfill);
1594 strcpy(tmp + l1 + lfill,Mask + l1 + 1);
1599 /****************************************************************************
1600 expand a wildcard expression, replacing *s with ?s
1601 ****************************************************************************/
1602 void expand_mask(char *Mask,BOOL doext)
1607 BOOL hasdot = False;
1609 BOOL absolute = (*Mask == '\\');
1611 *mbeg = *mext = *dirpart = *filepart = 0;
1613 /* parse the directory and filename */
1614 if (strchr(Mask,'\\'))
1615 dirname_dos(Mask,dirpart);
1617 filename_dos(Mask,filepart);
1619 strcpy(mbeg,filepart);
1620 if ((p1 = strchr(mbeg,'.')) != NULL)
1630 if (strlen(mbeg) > 8)
1632 strcpy(mext,mbeg + 8);
1638 strcpy(mbeg,"????????");
1639 if ((*mext == 0) && doext && !hasdot)
1642 if (strequal(mbeg,"*") && *mext==0)
1650 strcpy(Mask,dirpart);
1651 if (*dirpart || absolute) strcat(Mask,"\\");
1656 DEBUG(6,("Mask expanded to [%s]\n",Mask));
1660 /****************************************************************************
1661 does a string have any uppercase chars in it?
1662 ****************************************************************************/
1663 BOOL strhasupper(char *s)
1668 if (is_shift_jis (*s)) {
1670 } else if (is_kana (*s)) {
1673 if (isupper(*s)) return(True);
1677 if (isupper(*s)) return(True);
1684 /****************************************************************************
1685 does a string have any lowercase chars in it?
1686 ****************************************************************************/
1687 BOOL strhaslower(char *s)
1692 if (is_shift_jis (*s)) {
1694 } else if (is_kana (*s)) {
1697 if (islower(*s)) return(True);
1701 if (islower(*s)) return(True);
1708 /****************************************************************************
1709 find the number of chars in a string
1710 ****************************************************************************/
1711 int count_chars(char *s,char c)
1724 /****************************************************************************
1726 ****************************************************************************/
1727 void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
1734 if ((mode & aDIR) != 0)
1737 memset(buf+1,' ',11);
1738 if ((p = strchr(mask2,'.')) != NULL)
1741 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
1742 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
1746 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
1748 bzero(buf+21,DIR_STRUCT_SIZE-21);
1749 CVAL(buf,21) = mode;
1750 put_dos_date(buf,22,date);
1751 SSVAL(buf,26,size & 0xFFFF);
1752 SSVAL(buf,28,size >> 16);
1753 StrnCpy(buf+30,fname,12);
1754 if (!case_sensitive)
1756 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
1760 /*******************************************************************
1761 close the low 3 fd's and open dev/null in their place
1762 ********************************************************************/
1763 void close_low_fds(void)
1767 close(0); close(1); close(2);
1768 /* try and use up these file descriptors, so silly
1769 library routines writing to stdout etc won't cause havoc */
1771 fd = open("/dev/null",O_RDWR,0);
1772 if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
1774 DEBUG(0,("Can't open /dev/null\n"));
1778 DEBUG(0,("Didn't get file descriptor %d\n",i));
1785 /****************************************************************************
1787 ****************************************************************************/
1788 int write_socket(int fd,char *buf,int len)
1794 DEBUG(6,("write_socket(%d,%d)\n",fd,len));
1795 ret = write_data(fd,buf,len);
1797 DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
1801 /****************************************************************************
1803 ****************************************************************************/
1804 int read_udp_socket(int fd,char *buf,int len)
1807 struct sockaddr sock;
1810 socklen = sizeof(sock);
1811 bzero((char *)&sock,socklen);
1812 bzero((char *)&lastip,sizeof(lastip));
1813 ret = recvfrom(fd,buf,len,0,&sock,&socklen);
1815 DEBUG(2,("read socket failed. ERRNO=%d\n",errno));
1819 lastip = *(struct in_addr *) &sock.sa_data[2];
1820 lastport = ntohs(((struct sockaddr_in *)&sock)->sin_port);
1825 /****************************************************************************
1826 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
1828 if SYSV use O_NDELAY
1830 ****************************************************************************/
1831 int set_blocking(int fd, BOOL set)
1835 #define FLAG_TO_SET O_NONBLOCK
1838 #define FLAG_TO_SET O_NDELAY
1840 #define FLAG_TO_SET FNDELAY
1844 if((val = fcntl(fd, F_GETFL, 0))==-1)
1846 if(set) /* Turn blocking on - ie. clear nonblock flag */
1847 val &= ~FLAG_TO_SET;
1850 return fcntl( fd, F_SETFL, val);
1855 /****************************************************************************
1856 Calculate the difference in timeout values. Return 1 if val1 > val2,
1857 0 if val1 == val2, -1 if val1 < val2. Stores result in retval. retval
1858 may be == val1 or val2
1859 ****************************************************************************/
1860 static int tval_sub( struct timeval *retval, struct timeval *val1, struct timeval *val2)
1862 int usecdiff = val1->tv_usec - val2->tv_usec;
1863 int secdiff = val1->tv_sec - val2->tv_sec;
1865 usecdiff = 1000000 + usecdiff;
1868 retval->tv_sec = secdiff;
1869 retval->tv_usec = usecdiff;
1874 return (usecdiff < 0 ) ? -1 : ((usecdiff > 0 ) ? 1 : 0);
1877 /****************************************************************************
1878 read data from a device with a timout in msec.
1879 mincount = if timeout, minimum to read before returning
1880 maxcount = number to be read.
1881 ****************************************************************************/
1882 int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out,BOOL exact)
1888 struct timeval timeout, tval1, tval2, tvaldiff;
1889 int error_limit = 5;
1891 /* just checking .... */
1892 if (maxcnt <= 0) return(0);
1895 time_out = DEFAULT_PIPE_TIMEOUT;
1899 if (mincnt == 0) mincnt = maxcnt;
1901 while (nread < mincnt)
1903 readret = read(fd, buf + nread, maxcnt - nread);
1904 if (readret <= 0) return(nread);
1910 /* Non blocking read */
1912 set_blocking(fd, False);
1913 nread = read_data(fd, buf, mincnt);
1915 nread += read(fd,buf+nread,maxcnt-nread);
1916 if(nread == -1 && errno == EWOULDBLOCK)
1918 set_blocking(fd,True);
1922 /* Most difficult - timeout read */
1923 /* If this is ever called on a disk file and
1924 mincnt is greater then the filesize then
1925 system performance will suffer severely as
1926 select always return true on disk files */
1928 /* Set initial timeout */
1929 timeout.tv_sec = time_out / 1000;
1930 timeout.tv_usec = 1000 * (time_out % 1000);
1932 /* As most UNIXes don't modify the value of timeout
1933 when they return from select we need to get the timeofday (in usec)
1934 now, and also after the select returns so we know
1935 how much time has elapsed */
1938 GetTimeOfDay( &tval1);
1939 nread = 0; /* Number of bytes we have read */
1946 selrtn = sys_select(&fds,&timeout);
1948 /* Check if error */
1953 /* Did we timeout ? */
1955 if (nread < mincnt) return -1;
1959 readret = read(fd, buf+nread, maxcnt-nread);
1960 if (readret == 0 && nread < mincnt) {
1961 /* error_limit should not really be needed, but some systems
1962 do strange things ... I don't want to just continue
1963 indefinately in case we get an infinite loop */
1964 if (error_limit--) continue;
1969 /* force a particular error number for
1971 DEBUG(5,("read gave error %s\n",strerror(errno)));
1977 /* If we have read more than mincnt then return */
1978 if (nread >= mincnt)
1981 /* We need to do another select - but first reduce the
1982 time_out by the amount of time already elapsed - if
1983 this is less than zero then return */
1985 GetTimeOfDay(&tval2);
1986 (void)tval_sub( &tvaldiff, &tval2, &tval1);
1988 if (tval_sub(&timeout, &timeout, &tvaldiff) <= 0)
1989 break; /* We timed out */
1992 /* Save the time of day as we need to do the select
1993 again (saves a system call) */
1997 /* Return the number we got */
2001 /****************************************************************************
2002 read data from the client. Maxtime is in milliseconds
2003 ****************************************************************************/
2004 int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
2009 struct timeval timeout;
2014 timeout.tv_sec = maxtime / 1000;
2015 timeout.tv_usec = (maxtime % 1000) * 1000;
2017 selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
2019 if (!FD_ISSET(fd,&fds))
2022 nread = read_udp_socket(fd, buffer, bufsize);
2024 /* return the number got */
2028 /*******************************************************************
2029 find the difference in milliseconds between two struct timeval
2031 ********************************************************************/
2032 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
2034 return((tvalnew->tv_sec - tvalold->tv_sec)*1000 +
2035 ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);
2038 /****************************************************************************
2039 send a keepalive packet (rfc1002)
2040 ****************************************************************************/
2041 BOOL send_keepalive(int client)
2043 unsigned char buf[4];
2046 buf[1] = buf[2] = buf[3] = 0;
2048 return(write_data(client,(char *)buf,4) == 4);
2053 /****************************************************************************
2054 read data from the client, reading exactly N bytes.
2055 ****************************************************************************/
2056 int read_data(int fd,char *buffer,int N)
2063 ret = read(fd,buffer + total,N - total);
2073 /****************************************************************************
2075 ****************************************************************************/
2076 int write_data(int fd,char *buffer,int N)
2083 ret = write(fd,buffer + total,N - total);
2094 /****************************************************************************
2095 transfer some data between two fd's
2096 ****************************************************************************/
2097 int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
2099 static char *buf=NULL;
2104 DEBUG(4,("transfer_file %d (head=%d) called\n",n,headlen));
2107 size = lp_readsize();
2108 size = MAX(size,1024);
2111 while (!buf && size>0) {
2112 buf = (char *)Realloc(buf,size+8);
2113 if (!buf) size /= 2;
2117 DEBUG(0,("Can't allocate transfer buffer!\n"));
2121 abuf = buf + (align%8);
2128 int s = MIN(n,size);
2133 if (header && (headlen >= MIN(s,1024))) {
2143 if (header && headlen > 0)
2145 ret = MIN(headlen,size);
2146 memcpy(buf1,header,ret);
2149 if (headlen <= 0) header = NULL;
2153 ret += read(infd,buf1+ret,s-ret);
2157 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
2158 if (ret2 > 0) total += ret2;
2159 /* if we can't write then dump excess data */
2161 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
2163 if (ret <= 0 || ret2 != ret)
2171 /****************************************************************************
2172 read 4 bytes of a smb packet and return the smb length of the packet
2173 possibly store the result in the buffer
2174 ****************************************************************************/
2175 int read_smb_length(int fd,char *inbuf,int timeout)
2179 int len=0, msg_type;
2190 ok = (read_with_timeout(fd,buffer,4,4,timeout,False) == 4);
2192 ok = (read_data(fd,buffer,4) == 4);
2198 DEBUG(10,("select timeout (%d)\n", timeout));
2203 DEBUG(6,("couldn't read from client\n"));
2208 len = smb_len(buffer);
2209 msg_type = CVAL(buffer,0);
2211 if (msg_type == 0x85)
2213 DEBUG(5,( "Got keepalive packet\n"));
2218 DEBUG(10,("got smb length of %d\n",len));
2225 /****************************************************************************
2226 read an smb from a fd and return it's length
2227 The timeout is in milli seconds
2228 ****************************************************************************/
2229 BOOL receive_smb(int fd,char *buffer,int timeout)
2234 bzero(buffer,smb_size + 100);
2236 len = read_smb_length(fd,buffer,timeout);
2240 if (len > BUFFER_SIZE) {
2241 DEBUG(0,("Invalid packet length! (%d bytes)\n",len));
2242 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
2246 ok = (read_data(fd,buffer+4,len) == len);
2258 /****************************************************************************
2260 ****************************************************************************/
2261 BOOL send_smb(int fd,char *buffer)
2265 len = smb_len(buffer) + 4;
2267 while (nwritten < len)
2269 ret = write_socket(fd,buffer+nwritten,len - nwritten);
2272 DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2284 /****************************************************************************
2285 find a pointer to a netbios name
2286 ****************************************************************************/
2287 char *name_ptr(char *buf,int ofs)
2289 unsigned char c = *(unsigned char *)(buf+ofs);
2291 if ((c & 0xC0) == 0xC0)
2295 memcpy(p,buf+ofs,2);
2298 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2305 /****************************************************************************
2306 extract a netbios name from a buf
2307 ****************************************************************************/
2308 int name_extract(char *buf,int ofs,char *name)
2310 char *p = name_ptr(buf,ofs);
2311 int d = PTR_DIFF(p,buf+ofs);
2313 if (d < -50 || d > 50) return(0);
2314 return(name_interpret(p,name));
2318 /****************************************************************************
2319 return the total storage length of a mangled name
2320 ****************************************************************************/
2321 int name_len(char *s)
2324 unsigned char c = *(unsigned char *)s;
2325 if ((c & 0xC0) == 0xC0)
2327 while (*s) s += (*s)+1;
2328 return(PTR_DIFF(s,s0)+1);
2331 /****************************************************************************
2332 send a single packet to a port on another machine
2333 ****************************************************************************/
2334 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2338 struct sockaddr_in sock_out;
2343 /* create a socket to write to */
2344 out_fd = socket(AF_INET, type, 0);
2347 DEBUG(0,("socket failed"));
2351 /* set the address and port */
2352 bzero((char *)&sock_out,sizeof(sock_out));
2353 putip((char *)&sock_out.sin_addr,(char *)&ip);
2354 sock_out.sin_port = htons( port );
2355 sock_out.sin_family = AF_INET;
2358 DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2359 len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2362 ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2365 DEBUG(0,("Packet send to %s(%d) failed ERRNO=%d\n",
2366 inet_ntoa(ip),port,errno));
2372 /*******************************************************************
2373 sleep for a specified number of milliseconds
2374 ********************************************************************/
2378 struct timeval tval,t1,t2;
2385 tval.tv_sec = (t-tdiff)/1000;
2386 tval.tv_usec = 1000*((t-tdiff)%1000);
2390 sys_select(&fds,&tval);
2393 tdiff = TvalDiff(&t1,&t2);
2397 /****************************************************************************
2398 check if a string is part of a list
2399 ****************************************************************************/
2400 BOOL in_list(char *s,char *list,BOOL casesensitive)
2405 if (!list) return(False);
2407 while (next_token(&p,tok,LIST_SEP))
2409 if (casesensitive) {
2410 if (strcmp(tok,s) == 0)
2413 if (StrCaseCmp(tok,s) == 0)
2420 /* this is used to prevent lots of mallocs of size 1 */
2421 static char *null_string = NULL;
2423 /****************************************************************************
2424 set a string value, allocing the space for the string
2425 ****************************************************************************/
2426 BOOL string_init(char **dest,char *src)
2437 null_string = (char *)malloc(1);
2440 *dest = null_string;
2444 *dest = (char *)malloc(l+1);
2450 /****************************************************************************
2452 ****************************************************************************/
2453 void string_free(char **s)
2455 if (!s || !(*s)) return;
2456 if (*s == null_string)
2462 /****************************************************************************
2463 set a string value, allocing the space for the string, and deallocating any
2465 ****************************************************************************/
2466 BOOL string_set(char **dest,char *src)
2470 return(string_init(dest,src));
2473 /****************************************************************************
2474 substitute a string for a pattern in another string. Make sure there is
2477 This routine looks for pattern in s and replaces it with
2478 insert. It may do multiple replacements.
2480 return True if a substitution was done.
2481 ****************************************************************************/
2482 BOOL string_sub(char *s,char *pattern,char *insert)
2488 if (!insert || !pattern || !s) return(False);
2491 lp = strlen(pattern);
2492 li = strlen(insert);
2494 if (!*pattern) return(False);
2496 while (lp <= ls && (p = strstr(s,pattern)))
2499 memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
2500 memcpy(p,insert,li);
2509 /*********************************************************
2510 * Recursive routine that is called by mask_match.
2511 * Does the actual matching.
2512 *********************************************************/
2513 BOOL do_match(char *str, char *regexp, int case_sig)
2517 for( p = regexp; *p && *str; ) {
2524 /* Look for a character matching
2525 the one after the '*' */
2528 return True; /* Automatic match */
2530 while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
2532 if(do_match(str,p,case_sig))
2546 if(toupper(*str) != toupper(*p))
2556 if (!*p && str[0] == '.' && str[1] == 0)
2559 if (!*str && *p == '?')
2561 while (*p == '?') p++;
2565 if(!*str && (*p == '*' && p[1] == '\0'))
2571 /*********************************************************
2572 * Routine to match a given string with a regexp - uses
2573 * simplified regexp that takes * and ? only. Case can be
2574 * significant or not.
2575 *********************************************************/
2576 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
2580 fstring ebase,eext,sbase,sext;
2584 /* Make local copies of str and regexp */
2585 StrnCpy(p1,regexp,sizeof(pstring)-1);
2586 StrnCpy(p2,str,sizeof(pstring)-1);
2588 if (!strchr(p2,'.')) {
2593 if (!strchr(p1,'.')) {
2601 string_sub(p1,"*.*","*");
2602 string_sub(p1,".*","*");
2606 /* Remove any *? and ** as they are meaningless */
2607 for(p = p1; *p; p++)
2608 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2609 (void)strcpy( &p[1], &p[2]);
2611 if (strequal(p1,"*")) return(True);
2613 DEBUG(5,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
2619 if ((p=strrchr(p1,'.'))) {
2628 if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
2638 matched = do_match(sbase,ebase,case_sig) &&
2639 (trans2 || do_match(sext,eext,case_sig));
2641 DEBUG(5,("mask_match returning %d\n", matched));
2648 /****************************************************************************
2649 become a daemon, discarding the controlling terminal
2650 ****************************************************************************/
2651 void become_daemon(void)
2653 #ifndef NO_FORK_DEBUG
2657 /* detach from the terminal */
2663 int i = open("/dev/tty", O_RDWR);
2666 ioctl(i, (int) TIOCNOTTY, (char *)0);
2676 /****************************************************************************
2677 put up a yes/no prompt
2678 ****************************************************************************/
2684 if (!fgets(ans,sizeof(ans)-1,stdin))
2687 if (*ans == 'y' || *ans == 'Y')
2693 /****************************************************************************
2694 read a line from a file with possible \ continuation chars.
2695 Blanks at the start or end of a line are stripped.
2696 The string will be allocated if s2 is NULL
2697 ****************************************************************************/
2698 char *fgets_slash(char *s2,int maxlen,FILE *f)
2703 BOOL start_of_line = True;
2710 maxlen = MIN(maxlen,8);
2711 s = (char *)Realloc(s,maxlen);
2714 if (!s || maxlen < 2) return(NULL);
2718 while (len < maxlen-1)
2726 while (len > 0 && s[len-1] == ' ')
2730 if (len > 0 && s[len-1] == '\\')
2733 start_of_line = True;
2738 if (len <= 0 && !s2)
2740 return(len>0?s:NULL);
2745 start_of_line = False;
2749 if (!s2 && len > maxlen-3)
2752 s = (char *)Realloc(s,maxlen);
2753 if (!s) return(NULL);
2761 /****************************************************************************
2762 set the length of a file from a filedescriptor.
2763 Returns 0 on success, -1 on failure.
2764 ****************************************************************************/
2765 int set_filelen(int fd, long len)
2767 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
2768 extend a file with ftruncate. Provide alternate implementation
2771 #if FTRUNCATE_CAN_EXTEND
2772 return ftruncate(fd, len);
2776 long currpos = lseek(fd, 0L, SEEK_CUR);
2780 /* Do an fstat to see if the file is longer than
2781 the requested size (call ftruncate),
2782 or shorter, in which case seek to len - 1 and write 1
2784 if(fstat(fd, &st)<0)
2788 if (S_ISFIFO(st.st_mode)) return 0;
2791 if(st.st_size == len)
2793 if(st.st_size > len)
2794 return ftruncate(fd, len);
2796 if(lseek(fd, len-1, SEEK_SET) != len -1)
2798 if(write(fd, &c, 1)!=1)
2800 /* Seek to where we were */
2801 lseek(fd, currpos, SEEK_SET);
2807 /****************************************************************************
2808 return the byte checksum of some data
2809 ****************************************************************************/
2810 int byte_checksum(char *buf,int len)
2812 unsigned char *p = (unsigned char *)buf;
2822 /****************************************************************************
2823 this is a version of setbuffer() for those machines that only have setvbuf
2824 ****************************************************************************/
2825 void setbuffer(FILE *f,char *buf,int bufsize)
2827 setvbuf(f,buf,_IOFBF,bufsize);
2832 /****************************************************************************
2833 parse out a directory name from a path name. Assumes dos style filenames.
2834 ****************************************************************************/
2835 char *dirname_dos(char *path,char *buf)
2837 char *p = strrchr(path,'\\');
2852 /****************************************************************************
2853 parse out a filename from a path name. Assumes dos style filenames.
2854 ****************************************************************************/
2855 static char *filename_dos(char *path,char *buf)
2857 char *p = strrchr(path,'\\');
2869 /****************************************************************************
2870 expand a pointer to be a particular size
2871 ****************************************************************************/
2872 void *Realloc(void *p,int size)
2878 DEBUG(5,("Realloc asked for 0 bytes\n"));
2883 ret = (void *)malloc(size);
2885 ret = (void *)realloc(p,size);
2888 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
2894 /****************************************************************************
2896 ****************************************************************************/
2897 char *strdup(char *s)
2900 if (!s) return(NULL);
2901 ret = (char *)malloc(strlen(s)+1);
2902 if (!ret) return(NULL);
2909 /****************************************************************************
2910 Signal handler for SIGPIPE (write on a disconnected socket)
2911 ****************************************************************************/
2914 DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
2919 #ifdef REPLACE_STRLEN
2920 /****************************************************************************
2921 a replacement strlen() that returns int for solaris
2922 ****************************************************************************/
2934 /*******************************************************************
2935 ftruncate for operating systems that don't have it
2936 ********************************************************************/
2937 int ftruncate(int f,long l)
2944 fl.l_type = F_WRLCK;
2945 return fcntl(f, F_FREESP, &fl);
2951 /****************************************************************************
2952 get my own name and IP
2953 ****************************************************************************/
2954 BOOL get_myname(char *myname,struct in_addr *ip)
2961 /* get my host name */
2962 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
2964 DEBUG(0,("gethostname failed\n"));
2969 if ((hp = Get_Hostbyname(hostname)) == 0)
2971 DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
2977 /* split off any parts after an initial . */
2978 char *p = strchr(hostname,'.');
2981 strcpy(myname,hostname);
2985 putip((char *)ip,(char *)hp->h_addr);
2991 /****************************************************************************
2992 true if two IP addresses are equal
2993 ****************************************************************************/
2994 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
2996 unsigned long a1,a2;
2997 a1 = ntohl(ip1.s_addr);
2998 a2 = ntohl(ip2.s_addr);
3003 /****************************************************************************
3004 open a socket of the specified type, port and address for incoming data
3005 ****************************************************************************/
3006 int open_socket_in(int type, int port, int dlevel)
3009 struct sockaddr_in sock;
3013 /* get my host name */
3014 if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
3015 { DEBUG(0,("gethostname failed\n")); return -1; }
3018 if ((hp = Get_Hostbyname(host_name)) == 0)
3020 DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
3024 bzero((char *)&sock,sizeof(sock));
3025 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
3026 #if defined(__FreeBSD__) || defined(NETBSD) /* XXX not the right ifdef */
3027 sock.sin_len = sizeof(sock);
3029 sock.sin_port = htons( port );
3030 sock.sin_family = hp->h_addrtype;
3031 sock.sin_addr.s_addr = INADDR_ANY;
3032 res = socket(hp->h_addrtype, type, 0);
3034 { DEBUG(0,("socket failed\n")); return -1; }
3038 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
3041 /* now we've got a socket - we need to bind it */
3042 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
3045 if (port == SMB_PORT || port == NMB_PORT)
3046 DEBUG(dlevel,("bind failed on port %d (%s)\n",
3047 port,strerror(errno)));
3050 if (dlevel > 0 && port < 1000)
3053 if (port >= 1000 && port < 9000)
3054 return(open_socket_in(type,port+1,dlevel));
3059 DEBUG(3,("bind succeeded on port %d\n",port));
3065 /****************************************************************************
3066 create an outgoing socket
3067 **************************************************************************/
3068 int open_socket_out(int type, struct in_addr *addr, int port )
3070 struct sockaddr_in sock_out;
3073 /* create a socket to write to */
3074 res = socket(PF_INET, type, 0);
3076 { DEBUG(0,("socket error\n")); return -1; }
3078 if (type != SOCK_STREAM) return(res);
3080 bzero((char *)&sock_out,sizeof(sock_out));
3081 putip((char *)&sock_out.sin_addr,(char *)addr);
3083 sock_out.sin_port = htons( port );
3084 sock_out.sin_family = PF_INET;
3086 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3088 /* and connect it to the destination */
3089 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out))<0) {
3090 DEBUG(0,("connect error: %s\n",strerror(errno)));
3099 /****************************************************************************
3100 interpret a protocol description string, with a default
3101 ****************************************************************************/
3102 int interpret_protocol(char *str,int def)
3104 if (strequal(str,"NT1"))
3105 return(PROTOCOL_NT1);
3106 if (strequal(str,"LANMAN2"))
3107 return(PROTOCOL_LANMAN2);
3108 if (strequal(str,"LANMAN1"))
3109 return(PROTOCOL_LANMAN1);
3110 if (strequal(str,"CORE"))
3111 return(PROTOCOL_CORE);
3112 if (strequal(str,"COREPLUS"))
3113 return(PROTOCOL_COREPLUS);
3114 if (strequal(str,"CORE+"))
3115 return(PROTOCOL_COREPLUS);
3117 DEBUG(0,("Unrecognised protocol level %s\n",str));
3122 /****************************************************************************
3123 interpret a security level
3124 ****************************************************************************/
3125 int interpret_security(char *str,int def)
3127 if (strequal(str,"SERVER"))
3129 if (strequal(str,"USER"))
3131 if (strequal(str,"SHARE"))
3134 DEBUG(0,("Unrecognised security level %s\n",str));
3140 /****************************************************************************
3141 interpret an internet address or name into an IP address in 4 byte form
3142 ****************************************************************************/
3143 unsigned long interpret_addr(char *str)
3148 if (strcmp(str,"0.0.0.0") == 0) return(0);
3149 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3151 /* if it's in the form of an IP address then get the lib to interpret it */
3152 if (isdigit(str[0])) {
3153 res = inet_addr(str);
3155 /* otherwise assume it's a network name of some sort and use Get_Hostbyname */
3156 if ((hp = Get_Hostbyname(str)) == 0) {
3157 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3160 putip((char *)&res,(char *)hp->h_addr);
3163 if (res == (unsigned long)-1) return(0);
3168 /*******************************************************************
3169 a convenient addition to interpret_addr()
3170 ******************************************************************/
3171 struct in_addr *interpret_addr2(char *str)
3173 static struct in_addr ret;
3174 unsigned long a = interpret_addr(str);
3179 /*******************************************************************
3180 check if an IP is the 0.0.0.0
3181 ******************************************************************/
3182 BOOL zero_ip(struct in_addr ip)
3185 putip((char *)&a,(char *)&ip);
3189 /*******************************************************************
3190 sub strings with useful parameters
3191 ********************************************************************/
3192 void standard_sub_basic(char *s)
3194 if (!strchr(s,'%')) return;
3196 string_sub(s,"%R",remote_proto);
3197 string_sub(s,"%a",remote_arch);
3198 string_sub(s,"%m",remote_machine);
3199 string_sub(s,"%L",local_machine);
3201 if (!strchr(s,'%')) return;
3203 string_sub(s,"%v",VERSION);
3204 string_sub(s,"%h",myhostname);
3205 string_sub(s,"%U",sesssetup_user);
3207 if (!strchr(s,'%')) return;
3209 string_sub(s,"%I",Client_info.addr);
3210 string_sub(s,"%M",Client_info.name);
3211 string_sub(s,"%T",timestring());
3213 if (!strchr(s,'%')) return;
3217 sprintf(pidstr,"%d",(int)getpid());
3218 string_sub(s,"%d",pidstr);
3221 if (!strchr(s,'%')) return;
3224 struct passwd *pass = Get_Pwnam(sesssetup_user,False);
3226 string_sub(s,"%G",gidtoname(pass->pw_gid));
3232 /*******************************************************************
3233 are two IPs on the same subnet?
3234 ********************************************************************/
3235 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
3237 unsigned long net1,net2,nmask;
3239 nmask = ntohl(mask.s_addr);
3240 net1 = ntohl(ip1.s_addr);
3241 net2 = ntohl(ip2.s_addr);
3243 return((net1 & nmask) == (net2 & nmask));
3247 /*******************************************************************
3248 write a string in unicoode format
3249 ********************************************************************/
3250 int PutUniCode(char *dst,char *src)
3254 dst[ret++] = src[0];
3263 /****************************************************************************
3264 a wrapper for gethostbyname() that tries with all lower and all upper case
3265 if the initial name fails
3266 ****************************************************************************/
3267 struct hostent *Get_Hostbyname(char *name)
3269 char *name2 = strdup(name);
3270 struct hostent *ret;
3274 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
3278 if (!isalnum(*name2))
3284 ret = gethostbyname(name2);
3291 /* try with all lowercase */
3293 ret = gethostbyname(name2);
3300 /* try with all uppercase */
3302 ret = gethostbyname(name2);
3309 /* nothing works :-( */
3315 /****************************************************************************
3316 check if a process exists. Does this work on all unixes?
3317 ****************************************************************************/
3318 BOOL process_exists(int pid)
3322 sprintf(s,"/proc/%d",pid);
3323 return(directory_exist(s,NULL));
3326 static BOOL tested=False;
3327 static BOOL ok=False;
3331 sprintf(s,"/proc/%05d",getpid());
3332 ok = file_exist(s,NULL);
3335 sprintf(s,"/proc/%05d",pid);
3336 return(file_exist(s,NULL));
3340 /* a best guess for non root access */
3341 if (geteuid() != 0) return(True);
3343 /* otherwise use kill */
3344 return(pid == getpid() || kill(pid,0) == 0);
3349 /*******************************************************************
3350 turn a uid into a user name
3351 ********************************************************************/
3352 char *uidtoname(int uid)
3354 static char name[40];
3355 struct passwd *pass = getpwuid(uid);
3356 if (pass) return(pass->pw_name);
3357 sprintf(name,"%d",uid);
3361 /*******************************************************************
3362 turn a gid into a group name
3363 ********************************************************************/
3364 char *gidtoname(int gid)
3366 static char name[40];
3367 struct group *grp = getgrgid(gid);
3368 if (grp) return(grp->gr_name);
3369 sprintf(name,"%d",gid);
3373 /*******************************************************************
3375 ********************************************************************/
3376 void BlockSignals(BOOL block)
3379 int block_mask = (sigmask(SIGTERM)|sigmask(SIGQUIT)|sigmask(SIGSEGV)
3380 |sigmask(SIGCHLD)|sigmask(SIGQUIT)|sigmask(SIGBUS)|
3383 sigblock(block_mask);
3385 sigunblock(block_mask);
3390 /*******************************************************************
3391 my own panic function - not suitable for general use
3392 ********************************************************************/
3393 void ajt_panic(void)
3395 system("/usr/bin/X11/xedit -display :0 /tmp/ERROR_FAULT");
3400 #define DIRECT direct
3402 #define DIRECT dirent
3405 /*******************************************************************
3406 a readdir wrapper which just returns the file name
3407 also return the inode number if requested
3408 ********************************************************************/
3409 char *readdirname(void *p)
3414 if (!p) return(NULL);
3416 ptr = (struct DIRECT *)readdir(p);
3417 if (!ptr) return(NULL);
3419 dname = ptr->d_name;
3425 unix_to_dos(buf, True);
3431 if (telldir(p) < 0) return(NULL);
3435 /* this handles a broken compiler setup, causing a mixture
3436 of BSD and SYSV headers and libraries */
3438 static BOOL broken_readdir = False;
3439 if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
3441 DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
3442 broken_readdir = True;
3454 #if (defined(SecureWare) && defined(SCO))
3455 /* This is needed due to needing the nap() function but we don't want
3456 to include the Xenix libraries since that will break other things...
3457 BTW: system call # 0x0c28 is the same as calling nap() */
3458 long nap(long milliseconds) {
3459 return syscall(0x0c28, milliseconds);
3463 #ifdef NO_INITGROUPS
3464 #include <sys/types.h>
3469 #define NULL (void *)0
3472 /****************************************************************************
3473 some systems don't have an initgroups call
3474 ****************************************************************************/
3475 int initgroups(char *name,gid_t id)
3478 /* yikes! no SETGROUPS or INITGROUPS? how can this work? */
3481 gid_t grouplst[NGROUPS_MAX];
3488 while (i < NGROUPS_MAX &&
3489 ((g = (struct group *)getgrent()) != (struct group *)NULL))
3491 if (g->gr_gid == id)
3495 while (gr && (*gr != (char)NULL)) {
3496 if (strcmp(name,gr) == 0) {
3497 grouplst[i] = g->gr_gid;
3502 gr = g->gr_mem[++j];
3506 return(setgroups(i,grouplst));
3514 /* undo the wrapping temporarily */
3519 /****************************************************************************
3520 wrapper for malloc() to catch memory errors
3521 ****************************************************************************/
3522 void *malloc_wrapped(int size,char *file,int line)
3524 #ifdef xx_old_malloc
3525 void *res = xx_old_malloc(size);
3527 void *res = malloc(size);
3529 DEBUG(3,("Malloc called from %s(%d) with size=%d gave ptr=0x%X\n",
3531 size,(unsigned int)res));
3535 /****************************************************************************
3536 wrapper for realloc() to catch memory errors
3537 ****************************************************************************/
3538 void *realloc_wrapped(void *ptr,int size,char *file,int line)
3540 #ifdef xx_old_realloc
3541 void *res = xx_old_realloc(ptr,size);
3543 void *res = realloc(ptr,size);
3545 DEBUG(3,("Realloc\n"));
3546 DEBUG(3,("free called from %s(%d) with ptr=0x%X\n",
3548 (unsigned int)ptr));
3549 DEBUG(3,("Malloc called from %s(%d) with size=%d gave ptr=0x%X\n",
3551 size,(unsigned int)res));
3555 /****************************************************************************
3556 wrapper for free() to catch memory errors
3557 ****************************************************************************/
3558 void free_wrapped(void *ptr,char *file,int line)
3565 DEBUG(3,("free called from %s(%d) with ptr=0x%X\n",
3566 file,line,(unsigned int)ptr));
3570 /* and re-do the define for spots lower in this file */
3571 #define malloc(size) malloc_wrapped(size,__FILE__,__LINE__)
3572 #define realloc(ptr,size) realloc_wrapped(ptr,size,__FILE__,__LINE__)
3573 #define free(ptr) free_wrapped(ptr,__FILE__,__LINE__)
3577 #ifdef REPLACE_STRSTR
3578 /****************************************************************************
3579 Mips version of strstr doesn't seem to work correctly.
3580 There is a #define in includes.h to redirect calls to this function.
3581 ****************************************************************************/
3582 char *Strstr(char *s, char *p)
3584 int len = strlen(p);
3586 while ( *s != '\0' ) {
3587 if ( strncmp(s, p, len) == 0 )
3594 #endif /* REPLACE_STRSTR */
3597 #ifdef REPLACE_MKTIME
3598 /*******************************************************************
3599 a mktime() replacement for those who don't have it - contributed by
3600 C.A. Lademann <cal@zls.com>
3601 ********************************************************************/
3603 #define HOUR 60*MINUTE
3605 #define YEAR 365*DAY
3606 time_t Mktime(struct tm *t)
3610 int mon [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
3616 epoch = (t->tm_year - 70) * YEAR +
3617 (t->tm_year / 4 - 70 / 4 - t->tm_year / 100) * DAY;
3622 for(i = 0; i < t->tm_mon; i++) {
3623 epoch += mon [m] * DAY;
3624 if(m == 1 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0))
3633 epoch += (t->tm_mday - 1) * DAY;
3634 epoch += t->tm_hour * HOUR + t->tm_min * MINUTE + t->tm_sec;
3636 if((u = localtime(&epoch)) != NULL) {
3637 t->tm_sec = u->tm_sec;
3638 t->tm_min = u->tm_min;
3639 t->tm_hour = u->tm_hour;
3640 t->tm_mday = u->tm_mday;
3641 t->tm_mon = u->tm_mon;
3642 t->tm_year = u->tm_year;
3643 t->tm_wday = u->tm_wday;
3644 t->tm_yday = u->tm_yday;
3645 t->tm_isdst = u->tm_isdst;
3647 memcpy(t->tm_name, u->tm_name, LTZNMAX);
3653 #endif /* REPLACE_MKTIME */
3657 #ifdef REPLACE_RENAME
3658 /* Rename a file. (from libiberty in GNU binutils) */
3659 int rename (zfrom, zto)
3663 if (link (zfrom, zto) < 0)
3665 if (errno != EEXIST)
3667 if (unlink (zto) < 0
3668 || link (zfrom, zto) < 0)
3671 return unlink (zfrom);
3676 #ifdef REPLACE_INNETGR
3678 * Search for a match in a netgroup. This replaces it on broken systems.
3680 int InNetGr(char *group,char *host,char *user,char *dom)
3682 char *hst, *usr, *dm;
3685 while (getnetgrent(&hst, &usr, &dm))
3686 if (((host == 0) || (hst == 0) || !strcmp(host, hst)) &&
3687 ((user == 0) || (usr == 0) || !strcmp(user, usr)) &&
3688 ((dom == 0) || (dm == 0) || !strcmp(dom, dm))) {
3700 /*******************************************************************
3701 a wrapper around memcpy for diagnostic purposes
3702 ********************************************************************/
3703 void *memcpy_wrapped(void *d,void *s,int l,char *fname,int line)
3705 if (l>64 && (((int)d)%4) != (((int)s)%4))
3706 DEBUG(4,("Misaligned memcpy(0x%X,0x%X,%d) at %s(%d)\n",d,s,l,fname,line));
3707 #ifdef xx_old_memcpy
3708 return(xx_old_memcpy(d,s,l));
3710 return(memcpy(d,s,l));
3713 #define memcpy(d,s,l) memcpy_wrapped(d,s,l,__FILE__,__LINE__)