2 Unix SMB/Netbios implementation.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1997
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.
24 #if (defined(NETGROUP) && defined (AUTOMOUNT))
25 #include "rpcsvc/ypclnt.h"
34 int Protocol = PROTOCOL_COREPLUS;
36 /* a default finfo structure to ensure all fields are sensible */
37 file_info def_finfo = {-1,0,0,0,0,0,0,""};
39 /* these are some file handles where debug info will be stored */
42 /* the client file descriptor */
45 /* the last IP received from */
46 struct in_addr lastip;
48 /* the last port received from */
51 /* this is used by the chaining code */
57 case handling on filenames
59 int case_default = CASE_LOWER;
64 /* the following control case operations - they are put here so the
65 client can link easily */
68 BOOL use_mangled_map = False;
69 BOOL short_case_preserve;
72 fstring remote_machine="";
73 fstring local_machine="";
74 fstring remote_arch="UNKNOWN";
75 static enum remote_arch_types ra_type = RA_UNKNOWN;
76 fstring remote_proto="UNKNOWN";
77 pstring myhostname="";
78 pstring user_socket_options="";
80 pstring sesssetup_user="";
81 pstring samlogon_user="";
83 BOOL sam_logon_in_ssb = False;
86 fstring myworkgroup = "";
87 char **my_netbios_names;
89 int smb_read_error = 0;
91 static BOOL stdout_logging = False;
93 static char *filename_dos(char *path,char *buf);
95 /*******************************************************************
96 get ready for syslog stuff
97 ******************************************************************/
98 void setup_logging(char *pname,BOOL interactive)
102 char *p = strrchr(pname,'/');
105 openlog(pname, LOG_PID, SYSLOG_FACILITY);
106 #else /* for old systems that have no facility codes. */
107 openlog(pname, LOG_PID);
112 stdout_logging = True;
118 BOOL append_log=False;
121 /****************************************************************************
123 ****************************************************************************/
124 void reopen_logs(void)
131 strcpy(fname,debugf);
132 if (lp_loaded() && (*lp_logfile()))
133 strcpy(fname,lp_logfile());
135 if (!strcsequal(fname,debugf) || !dbf || !file_exist(debugf,NULL))
137 int oldumask = umask(022);
138 strcpy(debugf,fname);
139 if (dbf) fclose(dbf);
141 dbf = fopen(debugf,"a");
143 dbf = fopen(debugf,"w");
144 if (dbf) setbuf(dbf,NULL);
159 /*******************************************************************
160 check if the log has grown too big
161 ********************************************************************/
162 static void check_log_size(void)
164 static int debug_count=0;
168 if (debug_count++ < 100 || getuid() != 0) return;
170 maxlog = lp_max_log_size() * 1024;
171 if (!dbf || maxlog <= 0) return;
173 if (fstat(fileno(dbf),&st) == 0 && st.st_size > maxlog) {
174 fclose(dbf); dbf = NULL;
176 if (dbf && file_size(debugf) > maxlog) {
178 fclose(dbf); dbf = NULL;
179 sprintf(name,"%s.old",debugf);
180 sys_rename(debugf,name);
188 /*******************************************************************
189 write an debug message on the debugfile. This is called by the DEBUG
191 ********************************************************************/
193 int Debug1(char *format_str, ...)
202 int old_errno = errno;
204 if (stdout_logging) {
206 va_start(ap, format_str);
209 format_str = va_arg(ap,char *);
211 vfprintf(dbf,format_str,ap);
218 if (!lp_syslog_only())
222 int oldumask = umask(022);
223 dbf = fopen(debugf,"w");
235 if (syslog_level < lp_syslog())
238 * map debug levels to syslog() priorities
239 * note that not all DEBUG(0, ...) calls are
242 static int priority_map[] = {
251 if (syslog_level >= sizeof(priority_map) / sizeof(priority_map[0]) ||
253 priority = LOG_DEBUG;
255 priority = priority_map[syslog_level];
258 va_start(ap, format_str);
261 format_str = va_arg(ap,char *);
263 vsprintf(msgbuf, format_str, ap);
267 syslog(priority, "%s", msgbuf);
272 if (!lp_syslog_only())
276 va_start(ap, format_str);
279 format_str = va_arg(ap,char *);
281 vfprintf(dbf,format_str,ap);
293 /****************************************************************************
294 find a suitable temporary directory. The result should be copied immediately
295 as it may be overwritten by a subsequent call
296 ****************************************************************************/
300 if ((p = getenv("TMPDIR"))) {
308 /****************************************************************************
309 determine if a file descriptor is in fact a socket
310 ****************************************************************************/
311 BOOL is_a_socket(int fd)
315 return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
319 static char *last_ptr=NULL;
321 /****************************************************************************
322 Get the next token from a string, return False if none found
323 handles double-quotes.
324 Based on a routine by GJC@VILLAGE.COM.
325 Extensively modified by Andrew.Tridgell@anu.edu.au
326 ****************************************************************************/
327 BOOL next_token(char **ptr,char *buff,char *sep)
332 if (!ptr) ptr = &last_ptr;
333 if (!ptr) return(False);
337 /* default to simple separators */
338 if (!sep) sep = " \t\n\r";
340 /* find the first non sep char */
341 while(*s && strchr(sep,*s)) s++;
344 if (! *s) return(False);
346 /* copy over the token */
347 for (quoted = False; *s && (quoted || !strchr(sep,*s)); s++)
355 *ptr = (*s) ? s+1 : s;
362 /****************************************************************************
363 Convert list of tokens to array; dependent on above routine.
364 Uses last_ptr from above - bit of a hack.
365 ****************************************************************************/
366 char **toktocliplist(int *ctok, char *sep)
372 if (!sep) sep = " \t\n\r";
374 while(*s && strchr(sep,*s)) s++;
377 if (!*s) return(NULL);
381 while(*s && (!strchr(sep,*s))) s++;
382 while(*s && strchr(sep,*s)) *s++=0;
388 if (!(ret=iret=malloc(ictok*sizeof(char *)))) return NULL;
400 /*******************************************************************
401 safely copies memory, ensuring no overlap problems.
402 this is only used if the machine does not have it's own memmove().
403 this is not the fastest algorithm in town, but it will do for our
405 ********************************************************************/
406 void *MemMove(void *dest,void *src,int size)
410 if (dest==src || !size) return(dest);
412 d = (unsigned long)dest;
413 s = (unsigned long)src;
415 if ((d >= (s+size)) || (s >= (d+size))) {
417 memcpy(dest,src,size);
423 /* we can forward copy */
424 if (s-d >= sizeof(int) &&
425 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
426 /* do it all as words */
427 int *idest = (int *)dest;
428 int *isrc = (int *)src;
430 for (i=0;i<size;i++) idest[i] = isrc[i];
433 char *cdest = (char *)dest;
434 char *csrc = (char *)src;
435 for (i=0;i<size;i++) cdest[i] = csrc[i];
440 /* must backward copy */
441 if (d-s >= sizeof(int) &&
442 !(s%sizeof(int)) && !(d%sizeof(int)) && !(size%sizeof(int))) {
443 /* do it all as words */
444 int *idest = (int *)dest;
445 int *isrc = (int *)src;
447 for (i=size-1;i>=0;i--) idest[i] = isrc[i];
450 char *cdest = (char *)dest;
451 char *csrc = (char *)src;
452 for (i=size-1;i>=0;i--) cdest[i] = csrc[i];
460 /****************************************************************************
461 prompte a dptr (to make it recently used)
462 ****************************************************************************/
463 void array_promote(char *array,int elsize,int element)
469 p = (char *)malloc(elsize);
473 DEBUG(5,("Ahh! Can't malloc\n"));
476 memcpy(p,array + element * elsize, elsize);
477 memmove(array + elsize,array,elsize*element);
478 memcpy(array,p,elsize);
482 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
491 } socket_options[] = {
492 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
493 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
494 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
496 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
498 #ifdef IPTOS_LOWDELAY
499 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
501 #ifdef IPTOS_THROUGHPUT
502 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
505 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
508 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
511 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
514 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
517 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
520 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
526 /****************************************************************************
527 set user socket options
528 ****************************************************************************/
529 void set_socket_options(int fd, char *options)
533 while (next_token(&options,tok," \t,"))
538 BOOL got_value = False;
540 if ((p = strchr(tok,'=')))
547 for (i=0;socket_options[i].name;i++)
548 if (strequal(socket_options[i].name,tok))
551 if (!socket_options[i].name)
553 DEBUG(0,("Unknown socket option %s\n",tok));
557 switch (socket_options[i].opttype)
561 ret = setsockopt(fd,socket_options[i].level,
562 socket_options[i].option,(char *)&value,sizeof(int));
567 DEBUG(0,("syntax error - %s does not take a value\n",tok));
570 int on = socket_options[i].value;
571 ret = setsockopt(fd,socket_options[i].level,
572 socket_options[i].option,(char *)&on,sizeof(int));
578 DEBUG(0,("Failed to set socket option %s\n",tok));
584 /****************************************************************************
585 close the socket communication
586 ****************************************************************************/
587 void close_sockets(void )
593 /****************************************************************************
594 determine whether we are in the specified group
595 ****************************************************************************/
596 BOOL in_group(gid_t group, int current_gid, int ngroups, int *groups)
600 if (group == current_gid) return(True);
602 for (i=0;i<ngroups;i++)
603 if (group == groups[i])
609 /****************************************************************************
610 this is a safer strcpy(), meant to prevent core dumps when nasty things happen
611 ****************************************************************************/
612 char *StrCpy(char *dest,char *src)
617 /* I don't want to get lazy with these ... */
619 DEBUG(0,("ERROR: NULL StrCpy() called!\n"));
624 if (!dest) return(NULL);
629 while ((*d++ = *src++)) ;
633 /****************************************************************************
634 line strncpy but always null terminates. Make sure there is room!
635 ****************************************************************************/
636 char *StrnCpy(char *dest,char *src,int n)
639 if (!dest) return(NULL);
644 while (n-- && (*d++ = *src++)) ;
650 /*******************************************************************
651 copy an IP address from one buffer to another
652 ********************************************************************/
653 void putip(void *dest,void *src)
659 /****************************************************************************
660 interpret the weird netbios "name". Return the name type
661 ****************************************************************************/
662 static int name_interpret(char *in,char *out)
665 int len = (*in++) / 2;
669 if (len > 30 || len<1) return(0);
673 if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') {
677 *out = ((in[0]-'A')<<4) + (in[1]-'A');
685 /* Handle any scope names */
688 *out++ = '.'; /* Scope names are separated by periods */
689 len = *(unsigned char *)in++;
690 StrnCpy(out, in, len);
699 /****************************************************************************
700 mangle a name into netbios format
702 Note: <Out> must be (33 + strlen(scope) + 2) bytes long, at minimum.
703 ****************************************************************************/
704 int name_mangle( char *In, char *Out, char name_type )
712 /* Safely copy the input string, In, into buf[]. */
713 (void)memset( buf, 0, 20 );
717 (void)sprintf( buf, "%-15.15s%c", In, name_type );
719 /* Place the length of the first field into the output buffer. */
723 /* Now convert the name to the rfc1001/1002 format. */
724 for( i = 0; i < 16; i++ )
726 c = toupper( buf[i] );
727 p[i*2] = ( (c >> 4) & 0x000F ) + 'A';
728 p[(i*2)+1] = (c & 0x000F) + 'A';
733 /* Add the scope string. */
734 for( i = 0, len = 0; NULL != scope; i++, len++ )
742 return( name_len(Out) );
754 return( name_len(Out) );
757 /*******************************************************************
758 check if a file exists
759 ********************************************************************/
760 BOOL file_exist(char *fname,struct stat *sbuf)
763 if (!sbuf) sbuf = &st;
765 if (sys_stat(fname,sbuf) != 0)
768 return(S_ISREG(sbuf->st_mode));
771 /*******************************************************************
772 check a files mod time
773 ********************************************************************/
774 time_t file_modtime(char *fname)
778 if (sys_stat(fname,&st) != 0)
784 /*******************************************************************
785 check if a directory exists
786 ********************************************************************/
787 BOOL directory_exist(char *dname,struct stat *st)
794 if (sys_stat(dname,st) != 0)
797 ret = S_ISDIR(st->st_mode);
803 /*******************************************************************
804 returns the size in bytes of the named file
805 ********************************************************************/
806 uint32 file_size(char *file_name)
810 sys_stat(file_name,&buf);
814 /*******************************************************************
815 return a string representing an attribute for a file
816 ********************************************************************/
817 char *attrib_string(int mode)
819 static char attrstr[10];
823 if (mode & aVOLID) strcat(attrstr,"V");
824 if (mode & aDIR) strcat(attrstr,"D");
825 if (mode & aARCH) strcat(attrstr,"A");
826 if (mode & aHIDDEN) strcat(attrstr,"H");
827 if (mode & aSYSTEM) strcat(attrstr,"S");
828 if (mode & aRONLY) strcat(attrstr,"R");
834 /*******************************************************************
835 case insensitive string compararison
836 ********************************************************************/
837 int StrCaseCmp(char *s, char *t)
839 /* compare until we run out of string, either t or s, or find a difference */
840 /* We *must* use toupper rather than tolower here due to the
841 asynchronous upper to lower mapping.
843 #if !defined(KANJI_WIN95_COMPATIBILITY)
844 if(lp_client_code_page() == KANJI_CODEPAGE)
846 /* Win95 treats full width ascii characters as case sensitive. */
851 return toupper (*s) - toupper (*t);
852 else if (is_sj_alph (*s) && is_sj_alph (*t))
854 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
860 else if (is_shift_jis (*s) && is_shift_jis (*t))
862 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
865 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
871 else if (is_shift_jis (*s))
873 else if (is_shift_jis (*t))
877 diff = toupper (*s) - toupper (*t);
886 #endif /* KANJI_WIN95_COMPATIBILITY */
888 while (*s && *t && toupper(*s) == toupper(*t))
894 return(toupper(*s) - toupper(*t));
898 /*******************************************************************
899 case insensitive string compararison, length limited
900 ********************************************************************/
901 int StrnCaseCmp(char *s, char *t, int n)
903 /* compare until we run out of string, either t or s, or chars */
904 /* We *must* use toupper rather than tolower here due to the
905 asynchronous upper to lower mapping.
907 #if !defined(KANJI_WIN95_COMPATIBILITY)
908 if(lp_client_code_page() == KANJI_CODEPAGE)
910 /* Win95 treats full width ascii characters as case sensitive. */
915 return toupper (*s) - toupper (*t);
916 else if (is_sj_alph (*s) && is_sj_alph (*t))
918 diff = sj_toupper2 (*(s+1)) - sj_toupper2 (*(t+1));
925 else if (is_shift_jis (*s) && is_shift_jis (*t))
927 diff = ((int) (unsigned char) *s) - ((int) (unsigned char) *t);
930 diff = ((int) (unsigned char) *(s+1)) - ((int) (unsigned char) *(t+1));
937 else if (is_shift_jis (*s))
939 else if (is_shift_jis (*t))
943 diff = toupper (*s) - toupper (*t);
954 #endif /* KANJI_WIN95_COMPATIBILITY */
956 while (n && *s && *t && toupper(*s) == toupper(*t))
963 /* not run out of chars - strings are different lengths */
965 return(toupper(*s) - toupper(*t));
967 /* identical up to where we run out of chars,
968 and strings are same length */
973 /*******************************************************************
975 ********************************************************************/
976 BOOL strequal(char *s1, char *s2)
978 if (s1 == s2) return(True);
979 if (!s1 || !s2) return(False);
981 return(StrCaseCmp(s1,s2)==0);
984 /*******************************************************************
985 compare 2 strings up to and including the nth char.
986 ******************************************************************/
987 BOOL strnequal(char *s1,char *s2,int n)
989 if (s1 == s2) return(True);
990 if (!s1 || !s2 || !n) return(False);
992 return(StrnCaseCmp(s1,s2,n)==0);
995 /*******************************************************************
996 compare 2 strings (case sensitive)
997 ********************************************************************/
998 BOOL strcsequal(char *s1,char *s2)
1000 if (s1 == s2) return(True);
1001 if (!s1 || !s2) return(False);
1003 return(strcmp(s1,s2)==0);
1007 /*******************************************************************
1008 convert a string to lower case
1009 ********************************************************************/
1010 void strlower(char *s)
1014 #if !defined(KANJI_WIN95_COMPATIBILITY)
1015 if(lp_client_code_page() == KANJI_CODEPAGE)
1017 /* Win95 treats full width ascii characters as case sensitive. */
1018 if (is_shift_jis (*s))
1020 if (is_sj_upper (s[0], s[1]))
1021 s[1] = sj_tolower2 (s[1]);
1024 else if (is_kana (*s))
1036 #endif /* KANJI_WIN95_COMPATIBILITY */
1045 /*******************************************************************
1046 convert a string to upper case
1047 ********************************************************************/
1048 void strupper(char *s)
1052 #if !defined(KANJI_WIN95_COMPATIBILITY)
1053 if(lp_client_code_page() == KANJI_CODEPAGE)
1055 /* Win95 treats full width ascii characters as case sensitive. */
1056 if (is_shift_jis (*s))
1058 if (is_sj_lower (s[0], s[1]))
1059 s[1] = sj_toupper2 (s[1]);
1062 else if (is_kana (*s))
1074 #endif /* KANJI_WIN95_COMPATIBILITY */
1083 /*******************************************************************
1084 convert a string to "normal" form
1085 ********************************************************************/
1086 void strnorm(char *s)
1088 if (case_default == CASE_UPPER)
1094 /*******************************************************************
1095 check if a string is in "normal" case
1096 ********************************************************************/
1097 BOOL strisnormal(char *s)
1099 if (case_default == CASE_UPPER)
1100 return(!strhaslower(s));
1102 return(!strhasupper(s));
1106 /****************************************************************************
1108 ****************************************************************************/
1109 void string_replace(char *s,char oldc,char newc)
1113 #if !defined(KANJI_WIN95_COMPATIBILITY)
1114 if(lp_client_code_page() == KANJI_CODEPAGE)
1116 /* Win95 treats full width ascii characters as case sensitive. */
1117 if (is_shift_jis (*s))
1119 else if (is_kana (*s))
1129 #endif /* KANJI_WIN95_COMPATIBILITY */
1138 /****************************************************************************
1139 make a file into unix format
1140 ****************************************************************************/
1141 void unix_format(char *fname)
1144 string_replace(fname,'\\','/');
1148 pstrcpy(namecopy,fname);
1150 strcat(fname,namecopy);
1154 /****************************************************************************
1155 make a file into dos format
1156 ****************************************************************************/
1157 void dos_format(char *fname)
1159 string_replace(fname,'/','\\');
1163 /*******************************************************************
1164 show a smb message structure
1165 ********************************************************************/
1166 void show_msg(char *buf)
1171 if (DEBUGLEVEL < 5) return;
1173 DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
1175 (int)CVAL(buf,smb_com),
1176 (int)CVAL(buf,smb_rcls),
1177 (int)CVAL(buf,smb_reh),
1178 (int)SVAL(buf,smb_err),
1179 (int)CVAL(buf,smb_flg),
1180 (int)SVAL(buf,smb_flg2)));
1181 DEBUG(5,("smb_tid=%d\nsmb_pid=%d\nsmb_uid=%d\nsmb_mid=%d\nsmt_wct=%d\n",
1182 (int)SVAL(buf,smb_tid),
1183 (int)SVAL(buf,smb_pid),
1184 (int)SVAL(buf,smb_uid),
1185 (int)SVAL(buf,smb_mid),
1186 (int)CVAL(buf,smb_wct)));
1188 for (i=0;i<(int)CVAL(buf,smb_wct);i++)
1189 DEBUG(5,("smb_vwv[%d]=%d (0x%X)\n",i,
1190 SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
1192 bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
1193 DEBUG(5,("smb_bcc=%d\n",bcc));
1195 if (DEBUGLEVEL < 10) return;
1197 dump_data(10, smb_buf(buf), MIN(bcc, 512));
1200 /*******************************************************************
1201 return the length of an smb packet
1202 ********************************************************************/
1203 int smb_len(char *buf)
1205 return( PVAL(buf,3) | (PVAL(buf,2)<<8) | ((PVAL(buf,1)&1)<<16) );
1208 /*******************************************************************
1209 set the length of an smb packet
1210 ********************************************************************/
1211 void _smb_setlen(char *buf,int len)
1214 buf[1] = (len&0x10000)>>16;
1215 buf[2] = (len&0xFF00)>>8;
1219 /*******************************************************************
1220 set the length and marker of an smb packet
1221 ********************************************************************/
1222 void smb_setlen(char *buf,int len)
1224 _smb_setlen(buf,len);
1232 /*******************************************************************
1233 setup the word count and byte count for a smb message
1234 ********************************************************************/
1235 int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
1238 bzero(buf + smb_size,num_words*2 + num_bytes);
1239 CVAL(buf,smb_wct) = num_words;
1240 SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
1241 smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
1242 return (smb_size + num_words*2 + num_bytes);
1245 /*******************************************************************
1246 return the number of smb words
1247 ********************************************************************/
1248 int smb_numwords(char *buf)
1250 return (CVAL(buf,smb_wct));
1253 /*******************************************************************
1254 return the size of the smb_buf region of a message
1255 ********************************************************************/
1256 int smb_buflen(char *buf)
1258 return(SVAL(buf,smb_vwv0 + smb_numwords(buf)*2));
1261 /*******************************************************************
1262 return a pointer to the smb_buf data area
1263 ********************************************************************/
1264 int smb_buf_ofs(char *buf)
1266 return (smb_size + CVAL(buf,smb_wct)*2);
1269 /*******************************************************************
1270 return a pointer to the smb_buf data area
1271 ********************************************************************/
1272 char *smb_buf(char *buf)
1274 return (buf + smb_buf_ofs(buf));
1277 /*******************************************************************
1278 return the SMB offset into an SMB buffer
1279 ********************************************************************/
1280 int smb_offset(char *p,char *buf)
1282 return(PTR_DIFF(p,buf+4) + chain_size);
1286 /*******************************************************************
1287 skip past some strings in a buffer
1288 ********************************************************************/
1289 char *skip_string(char *buf,int n)
1292 buf += strlen(buf) + 1;
1296 /*******************************************************************
1297 trim the specified elements off the front and back of a string
1298 ********************************************************************/
1299 BOOL trim_string(char *s,char *front,char *back)
1302 while (front && *front && strncmp(s,front,strlen(front)) == 0)
1308 if (!(*p = p[strlen(front)]))
1313 while (back && *back && strlen(s) >= strlen(back) &&
1314 (strncmp(s+strlen(s)-strlen(back),back,strlen(back))==0))
1317 s[strlen(s)-strlen(back)] = 0;
1323 /*******************************************************************
1324 reduce a file name, removing .. elements.
1325 ********************************************************************/
1326 void dos_clean_name(char *s)
1330 DEBUG(3,("dos_clean_name [%s]\n",s));
1332 /* remove any double slashes */
1333 string_sub(s, "\\\\", "\\");
1335 while ((p = strstr(s,"\\..\\")) != NULL)
1342 if ((p=strrchr(s,'\\')) != NULL)
1349 trim_string(s,NULL,"\\..");
1351 string_sub(s, "\\.\\", "\\");
1354 /*******************************************************************
1355 reduce a file name, removing .. elements.
1356 ********************************************************************/
1357 void unix_clean_name(char *s)
1361 DEBUG(3,("unix_clean_name [%s]\n",s));
1363 /* remove any double slashes */
1364 string_sub(s, "//","/");
1366 /* Remove leading ./ characters */
1367 if(strncmp(s, "./", 2) == 0) {
1368 trim_string(s, "./", NULL);
1373 while ((p = strstr(s,"/../")) != NULL)
1380 if ((p=strrchr(s,'/')) != NULL)
1387 trim_string(s,NULL,"/..");
1391 /*******************************************************************
1392 a wrapper for the normal chdir() function
1393 ********************************************************************/
1394 int ChDir(char *path)
1397 static pstring LastDir="";
1399 if (strcsequal(path,".")) return(0);
1401 if (*path == '/' && strcsequal(LastDir,path)) return(0);
1402 DEBUG(3,("chdir to %s\n",path));
1403 res = sys_chdir(path);
1405 pstrcpy(LastDir,path);
1409 /* number of list structures for a caching GetWd function. */
1410 #define MAX_GETWDCACHE (50)
1418 } ino_list[MAX_GETWDCACHE];
1420 BOOL use_getwd_cache=True;
1422 /*******************************************************************
1423 return the absolute current directory path
1424 ********************************************************************/
1425 char *GetWd(char *str)
1428 static BOOL getwd_cache_init = False;
1429 struct stat st, st2;
1434 if (!use_getwd_cache)
1435 return(sys_getwd(str));
1437 /* init the cache */
1438 if (!getwd_cache_init)
1440 getwd_cache_init = True;
1441 for (i=0;i<MAX_GETWDCACHE;i++)
1443 string_init(&ino_list[i].text,"");
1444 ino_list[i].valid = False;
1448 /* Get the inode of the current directory, if this doesn't work we're
1451 if (stat(".",&st) == -1)
1453 DEBUG(0,("Very strange, couldn't stat \".\"\n"));
1454 return(sys_getwd(str));
1458 for (i=0; i<MAX_GETWDCACHE; i++)
1459 if (ino_list[i].valid)
1462 /* If we have found an entry with a matching inode and dev number
1463 then find the inode number for the directory in the cached string.
1464 If this agrees with that returned by the stat for the current
1465 directory then all is o.k. (but make sure it is a directory all
1468 if (st.st_ino == ino_list[i].inode &&
1469 st.st_dev == ino_list[i].dev)
1471 if (stat(ino_list[i].text,&st2) == 0)
1473 if (st.st_ino == st2.st_ino &&
1474 st.st_dev == st2.st_dev &&
1475 (st2.st_mode & S_IFMT) == S_IFDIR)
1477 strcpy (str, ino_list[i].text);
1479 /* promote it for future use */
1480 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1485 /* If the inode is different then something's changed,
1486 scrub the entry and start from scratch. */
1487 ino_list[i].valid = False;
1494 /* We don't have the information to hand so rely on traditional methods.
1495 The very slow getcwd, which spawns a process on some systems, or the
1496 not quite so bad getwd. */
1500 DEBUG(0,("Getwd failed, errno %s\n",strerror(errno)));
1506 DEBUG(5,("GetWd %s, inode %d, dev %x\n",s,(int)st.st_ino,(int)st.st_dev));
1508 /* add it to the cache */
1509 i = MAX_GETWDCACHE - 1;
1510 string_set(&ino_list[i].text,s);
1511 ino_list[i].dev = st.st_dev;
1512 ino_list[i].inode = st.st_ino;
1513 ino_list[i].valid = True;
1515 /* put it at the top of the list */
1516 array_promote((char *)&ino_list[0],sizeof(ino_list[0]),i);
1523 /*******************************************************************
1524 reduce a file name, removing .. elements and checking that
1525 it is below dir in the heirachy. This uses GetWd() and so must be run
1526 on the system that has the referenced file system.
1528 widelinks are allowed if widelinks is true
1529 ********************************************************************/
1530 BOOL reduce_name(char *s,char *dir,BOOL widelinks)
1532 #ifndef REDUCE_PATHS
1540 BOOL relative = (*s != '/');
1542 *dir2 = *wd = *basename = *newname = 0;
1547 /* can't have a leading .. */
1548 if (strncmp(s,"..",2) == 0 && (s[2]==0 || s[2]=='/'))
1550 DEBUG(3,("Illegal file name? (%s)\n",s));
1560 DEBUG(3,("reduce_name [%s] [%s]\n",s,dir));
1562 /* remove any double slashes */
1563 string_sub(s,"//","/");
1565 pstrcpy(basename,s);
1566 p = strrchr(basename,'/');
1573 DEBUG(0,("couldn't getwd for %s %s\n",s,dir));
1577 if (ChDir(dir) != 0)
1579 DEBUG(0,("couldn't chdir to %s\n",dir));
1585 DEBUG(0,("couldn't getwd for %s\n",dir));
1591 if (p && (p != basename))
1594 if (strcmp(p+1,".")==0)
1596 if (strcmp(p+1,"..")==0)
1600 if (ChDir(basename) != 0)
1603 DEBUG(3,("couldn't chdir for %s %s basename=%s\n",s,dir,basename));
1607 if (!GetWd(newname))
1610 DEBUG(2,("couldn't get wd for %s %s\n",s,dir2));
1614 if (p && (p != basename))
1616 strcat(newname,"/");
1617 strcat(newname,p+1);
1621 int l = strlen(dir2);
1622 if (dir2[l-1] == '/')
1625 if (strncmp(newname,dir2,l) != 0)
1628 DEBUG(2,("Bad access attempt? s=%s dir=%s newname=%s l=%d\n",s,dir2,newname,l));
1634 if (newname[l] == '/')
1635 pstrcpy(s,newname + l + 1);
1637 pstrcpy(s,newname+l);
1648 DEBUG(3,("reduced to %s\n",s));
1653 /****************************************************************************
1655 ****************************************************************************/
1656 static void expand_one(char *Mask,int len)
1659 while ((p1 = strchr(Mask,'*')) != NULL)
1661 int lfill = (len+1) - strlen(Mask);
1662 int l1= (p1 - Mask);
1665 memset(tmp+l1,'?',lfill);
1666 pstrcpy(tmp + l1 + lfill,Mask + l1 + 1);
1671 /****************************************************************************
1672 expand a wildcard expression, replacing *s with ?s
1673 ****************************************************************************/
1674 void expand_mask(char *Mask,BOOL doext)
1679 BOOL hasdot = False;
1681 BOOL absolute = (*Mask == '\\');
1683 *mbeg = *mext = *dirpart = *filepart = 0;
1685 /* parse the directory and filename */
1686 if (strchr(Mask,'\\'))
1687 dirname_dos(Mask,dirpart);
1689 filename_dos(Mask,filepart);
1691 pstrcpy(mbeg,filepart);
1692 if ((p1 = strchr(mbeg,'.')) != NULL)
1702 if (strlen(mbeg) > 8)
1704 pstrcpy(mext,mbeg + 8);
1710 strcpy(mbeg,"????????");
1711 if ((*mext == 0) && doext && !hasdot)
1714 if (strequal(mbeg,"*") && *mext==0)
1722 pstrcpy(Mask,dirpart);
1723 if (*dirpart || absolute) strcat(Mask,"\\");
1728 DEBUG(6,("Mask expanded to [%s]\n",Mask));
1732 /****************************************************************************
1733 does a string have any uppercase chars in it?
1734 ****************************************************************************/
1735 BOOL strhasupper(char *s)
1739 #if !defined(KANJI_WIN95_COMPATIBILITY)
1740 if(lp_client_code_page() == KANJI_CODEPAGE)
1742 /* Win95 treats full width ascii characters as case sensitive. */
1743 if (is_shift_jis (*s))
1745 else if (is_kana (*s))
1755 #endif /* KANJI_WIN95_COMPATIBILITY */
1765 /****************************************************************************
1766 does a string have any lowercase chars in it?
1767 ****************************************************************************/
1768 BOOL strhaslower(char *s)
1772 #if !defined(KANJI_WIN95_COMPATIBILITY)
1773 if(lp_client_code_page() == KANJI_CODEPAGE)
1775 /* Win95 treats full width ascii characters as case sensitive. */
1776 if (is_shift_jis (*s))
1778 if (is_sj_upper (s[0], s[1]))
1780 if (is_sj_lower (s[0], s[1]))
1784 else if (is_kana (*s))
1796 #endif /* KANJI_WIN95_COMPATIBILITY */
1806 /****************************************************************************
1807 find the number of chars in a string
1808 ****************************************************************************/
1809 int count_chars(char *s,char c)
1813 #if !defined(KANJI_WIN95_COMPATIBILITY)
1814 if(lp_client_code_page() == KANJI_CODEPAGE)
1816 /* Win95 treats full width ascii characters as case sensitive. */
1819 if (is_shift_jis (*s))
1830 #endif /* KANJI_WIN95_COMPATIBILITY */
1843 /****************************************************************************
1845 ****************************************************************************/
1846 void make_dir_struct(char *buf,char *mask,char *fname,unsigned int size,int mode,time_t date)
1851 pstrcpy(mask2,mask);
1853 if ((mode & aDIR) != 0)
1856 memset(buf+1,' ',11);
1857 if ((p = strchr(mask2,'.')) != NULL)
1860 memcpy(buf+1,mask2,MIN(strlen(mask2),8));
1861 memcpy(buf+9,p+1,MIN(strlen(p+1),3));
1865 memcpy(buf+1,mask2,MIN(strlen(mask2),11));
1867 bzero(buf+21,DIR_STRUCT_SIZE-21);
1868 CVAL(buf,21) = mode;
1869 put_dos_date(buf,22,date);
1870 SSVAL(buf,26,size & 0xFFFF);
1871 SSVAL(buf,28,size >> 16);
1872 StrnCpy(buf+30,fname,12);
1873 if (!case_sensitive)
1875 DEBUG(8,("put name [%s] into dir struct\n",buf+30));
1879 /*******************************************************************
1880 close the low 3 fd's and open dev/null in their place
1881 ********************************************************************/
1882 void close_low_fds(void)
1886 close(0); close(1); close(2);
1887 /* try and use up these file descriptors, so silly
1888 library routines writing to stdout etc won't cause havoc */
1890 fd = open("/dev/null",O_RDWR,0);
1891 if (fd < 0) fd = open("/dev/null",O_WRONLY,0);
1893 DEBUG(0,("Can't open /dev/null\n"));
1897 DEBUG(0,("Didn't get file descriptor %d\n",i));
1903 /****************************************************************************
1904 Set a fd into blocking/nonblocking mode. Uses POSIX O_NONBLOCK if available,
1906 if SYSV use O_NDELAY
1908 ****************************************************************************/
1909 int set_blocking(int fd, BOOL set)
1913 #define FLAG_TO_SET O_NONBLOCK
1916 #define FLAG_TO_SET O_NDELAY
1918 #define FLAG_TO_SET FNDELAY
1922 if((val = fcntl(fd, F_GETFL, 0)) == -1)
1924 if(set) /* Turn blocking on - ie. clear nonblock flag */
1925 val &= ~FLAG_TO_SET;
1928 return fcntl( fd, F_SETFL, val);
1933 /****************************************************************************
1935 ****************************************************************************/
1936 int write_socket(int fd,char *buf,int len)
1942 DEBUG(6,("write_socket(%d,%d)\n",fd,len));
1943 ret = write_data(fd,buf,len);
1945 DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,len,ret));
1949 /****************************************************************************
1951 ****************************************************************************/
1952 int read_udp_socket(int fd,char *buf,int len)
1955 struct sockaddr sock;
1958 socklen = sizeof(sock);
1959 bzero((char *)&sock,socklen);
1960 bzero((char *)&lastip,sizeof(lastip));
1961 ret = recvfrom(fd,buf,len,0,&sock,&socklen);
1963 DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
1967 lastip = *(struct in_addr *) &sock.sa_data[2];
1968 lastport = ntohs(((struct sockaddr_in *)&sock)->sin_port);
1970 DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
1971 inet_ntoa(lastip), lastport, ret));
1976 /****************************************************************************
1977 read data from a device with a timout in msec.
1978 mincount = if timeout, minimum to read before returning
1979 maxcount = number to be read.
1980 ****************************************************************************/
1981 int read_with_timeout(int fd,char *buf,int mincnt,int maxcnt,long time_out)
1987 struct timeval timeout;
1989 /* just checking .... */
1990 if (maxcnt <= 0) return(0);
1995 if (time_out <= 0) {
1996 if (mincnt == 0) mincnt = maxcnt;
1998 while (nread < mincnt) {
1999 readret = read(fd, buf + nread, maxcnt - nread);
2001 smb_read_error = READ_EOF;
2005 if (readret == -1) {
2006 smb_read_error = READ_ERROR;
2014 /* Most difficult - timeout read */
2015 /* If this is ever called on a disk file and
2016 mincnt is greater then the filesize then
2017 system performance will suffer severely as
2018 select always return true on disk files */
2020 /* Set initial timeout */
2021 timeout.tv_sec = time_out / 1000;
2022 timeout.tv_usec = 1000 * (time_out % 1000);
2024 for (nread=0; nread<mincnt; )
2029 selrtn = sys_select(&fds,&timeout);
2031 /* Check if error */
2033 /* something is wrong. Maybe the socket is dead? */
2034 smb_read_error = READ_ERROR;
2038 /* Did we timeout ? */
2040 smb_read_error = READ_TIMEOUT;
2044 readret = read(fd, buf+nread, maxcnt-nread);
2046 /* we got EOF on the file descriptor */
2047 smb_read_error = READ_EOF;
2051 if (readret == -1) {
2052 /* the descriptor is probably dead */
2053 smb_read_error = READ_ERROR;
2060 /* Return the number we got */
2064 /****************************************************************************
2065 read data from the client. Maxtime is in milliseconds
2066 ****************************************************************************/
2067 int read_max_udp(int fd,char *buffer,int bufsize,int maxtime)
2072 struct timeval timeout;
2077 timeout.tv_sec = maxtime / 1000;
2078 timeout.tv_usec = (maxtime % 1000) * 1000;
2080 selrtn = sys_select(&fds,maxtime>0?&timeout:NULL);
2082 if (!FD_ISSET(fd,&fds))
2085 nread = read_udp_socket(fd, buffer, bufsize);
2087 /* return the number got */
2091 /*******************************************************************
2092 find the difference in milliseconds between two struct timeval
2094 ********************************************************************/
2095 int TvalDiff(struct timeval *tvalold,struct timeval *tvalnew)
2097 return((tvalnew->tv_sec - tvalold->tv_sec)*1000 +
2098 ((int)tvalnew->tv_usec - (int)tvalold->tv_usec)/1000);
2101 /****************************************************************************
2102 send a keepalive packet (rfc1002)
2103 ****************************************************************************/
2104 BOOL send_keepalive(int client)
2106 unsigned char buf[4];
2109 buf[1] = buf[2] = buf[3] = 0;
2111 return(write_data(client,(char *)buf,4) == 4);
2116 /****************************************************************************
2117 read data from the client, reading exactly N bytes.
2118 ****************************************************************************/
2119 int read_data(int fd,char *buffer,int N)
2128 ret = read(fd,buffer + total,N - total);
2130 smb_read_error = READ_EOF;
2134 smb_read_error = READ_ERROR;
2143 /****************************************************************************
2145 ****************************************************************************/
2146 int write_data(int fd,char *buffer,int N)
2153 ret = write(fd,buffer + total,N - total);
2155 if (ret == -1) return -1;
2156 if (ret == 0) return total;
2164 /****************************************************************************
2165 transfer some data between two fd's
2166 ****************************************************************************/
2167 int transfer_file(int infd,int outfd,int n,char *header,int headlen,int align)
2169 static char *buf=NULL;
2174 DEBUG(4,("transfer_file %d (head=%d) called\n",n,headlen));
2177 size = lp_readsize();
2178 size = MAX(size,1024);
2181 while (!buf && size>0) {
2182 buf = (char *)Realloc(buf,size+8);
2183 if (!buf) size /= 2;
2187 DEBUG(0,("Can't allocate transfer buffer!\n"));
2191 abuf = buf + (align%8);
2198 int s = MIN(n,size);
2203 if (header && (headlen >= MIN(s,1024))) {
2213 if (header && headlen > 0)
2215 ret = MIN(headlen,size);
2216 memcpy(buf1,header,ret);
2219 if (headlen <= 0) header = NULL;
2223 ret += read(infd,buf1+ret,s-ret);
2227 ret2 = (outfd>=0?write_data(outfd,buf1,ret):ret);
2228 if (ret2 > 0) total += ret2;
2229 /* if we can't write then dump excess data */
2231 transfer_file(infd,-1,n-(ret+headlen),NULL,0,0);
2233 if (ret <= 0 || ret2 != ret)
2241 /****************************************************************************
2242 read 4 bytes of a smb packet and return the smb length of the packet
2243 possibly store the result in the buffer
2244 ****************************************************************************/
2245 int read_smb_length(int fd,char *inbuf,int timeout)
2249 int len=0, msg_type;
2260 ok = (read_with_timeout(fd,buffer,4,4,timeout) == 4);
2262 ok = (read_data(fd,buffer,4) == 4);
2267 len = smb_len(buffer);
2268 msg_type = CVAL(buffer,0);
2270 if (msg_type == 0x85)
2271 DEBUG(5,("Got keepalive packet\n"));
2274 DEBUG(10,("got smb length of %d\n",len));
2281 /****************************************************************************
2282 read an smb from a fd. Note that the buffer *MUST* be of size
2283 BUFFER_SIZE+SAFETY_MARGIN.
2284 The timeout is in milli seconds
2285 ****************************************************************************/
2286 BOOL receive_smb(int fd,char *buffer, int timeout)
2292 bzero(buffer,smb_size + 100);
2294 len = read_smb_length(fd,buffer,timeout);
2298 if (len > BUFFER_SIZE) {
2299 DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
2300 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
2305 ret = read_data(fd,buffer+4,len);
2307 smb_read_error = READ_ERROR;
2314 /****************************************************************************
2315 read a message from a udp fd.
2316 The timeout is in milli seconds
2317 ****************************************************************************/
2318 BOOL receive_local_message(int fd, char *buffer, int buffer_len, int timeout)
2320 struct sockaddr_in from;
2321 int fromlen = sizeof(from);
2333 to.tv_sec = timeout / 1000;
2334 to.tv_usec = (timeout % 1000) * 1000;
2336 selrtn = sys_select(&fds,&to);
2338 /* Check if error */
2341 /* something is wrong. Maybe the socket is dead? */
2342 smb_read_error = READ_ERROR;
2346 /* Did we timeout ? */
2349 smb_read_error = READ_TIMEOUT;
2355 * Read a loopback udp message.
2357 msg_len = recvfrom(fd, &buffer[UDP_CMD_HEADER_LEN],
2358 buffer_len - UDP_CMD_HEADER_LEN, 0,
2359 (struct sockaddr *)&from, &fromlen);
2363 DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
2367 /* Validate message length. */
2368 if(msg_len > (buffer_len - UDP_CMD_HEADER_LEN))
2370 DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
2372 buffer_len - UDP_CMD_HEADER_LEN));
2376 /* Validate message from address (must be localhost). */
2377 if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK))
2379 DEBUG(0,("receive_local_message: invalid 'from' address \
2380 (was %x should be 127.0.0.1\n", from.sin_addr.s_addr));
2384 /* Setup the message header */
2385 SIVAL(buffer,UDP_CMD_LEN_OFFSET,msg_len);
2386 SSVAL(buffer,UDP_CMD_PORT_OFFSET,ntohs(from.sin_port));
2391 /****************************************************************************
2392 structure to hold a linked list of local udp messages.
2394 ****************************************************************************/
2396 typedef struct _udp_message_list {
2397 struct _udp_message_list *msg_next;
2402 static udp_message_list *udp_msg_head = NULL;
2404 /****************************************************************************
2405 Function to push a linked list of local udp messages ready
2407 ****************************************************************************/
2408 BOOL push_local_message(char *buf, int msg_len)
2410 udp_message_list *msg = (udp_message_list *)malloc(sizeof(udp_message_list));
2414 DEBUG(0,("push_local_message: malloc fail (1)\n"));
2418 msg->msg_buf = (char *)malloc(msg_len);
2419 if(msg->msg_buf == NULL)
2421 DEBUG(0,("push_local_message: malloc fail (2)\n"));
2426 memcpy(msg->msg_buf, buf, msg_len);
2427 msg->msg_len = msg_len;
2429 msg->msg_next = udp_msg_head;
2435 /****************************************************************************
2436 Do a select on an two fd's - with timeout.
2438 If a local udp message has been pushed onto the
2439 queue (this can only happen during oplock break
2440 processing) return this first.
2442 If the first smbfd is ready then read an smb from it.
2443 if the second (loopback UDP) fd is ready then read a message
2444 from it and setup the buffer header to identify the length
2446 Returns False on timeout or error.
2449 The timeout is in milli seconds
2450 ****************************************************************************/
2451 BOOL receive_message_or_smb(int smbfd, int oplock_fd,
2452 char *buffer, int buffer_len,
2453 int timeout, BOOL *got_smb)
2462 * Check to see if we already have a message on the udp queue.
2463 * If so - copy and return it.
2468 udp_message_list *msg = udp_msg_head;
2469 memcpy(buffer, msg->msg_buf, MIN(buffer_len, msg->msg_len));
2470 udp_msg_head = msg->msg_next;
2472 /* Free the message we just copied. */
2473 free((char *)msg->msg_buf);
2480 FD_SET(oplock_fd,&fds);
2482 to.tv_sec = timeout / 1000;
2483 to.tv_usec = (timeout % 1000) * 1000;
2485 selrtn = sys_select(&fds,timeout>0?&to:NULL);
2487 /* Check if error */
2489 /* something is wrong. Maybe the socket is dead? */
2490 smb_read_error = READ_ERROR;
2494 /* Did we timeout ? */
2496 smb_read_error = READ_TIMEOUT;
2500 if (FD_ISSET(smbfd,&fds))
2503 return receive_smb(smbfd, buffer, 0);
2507 return receive_local_message(oplock_fd, buffer, buffer_len, 0);
2511 /****************************************************************************
2513 ****************************************************************************/
2514 BOOL send_smb(int fd,char *buffer)
2518 len = smb_len(buffer) + 4;
2520 while (nwritten < len)
2522 ret = write_socket(fd,buffer+nwritten,len - nwritten);
2525 DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",len,ret));
2537 /****************************************************************************
2538 find a pointer to a netbios name
2539 ****************************************************************************/
2540 char *name_ptr(char *buf,int ofs)
2542 unsigned char c = *(unsigned char *)(buf+ofs);
2544 if ((c & 0xC0) == 0xC0)
2548 memcpy(p,buf+ofs,2);
2551 DEBUG(5,("name ptr to pos %d from %d is %s\n",l,ofs,buf+l));
2558 /****************************************************************************
2559 extract a netbios name from a buf
2560 ****************************************************************************/
2561 int name_extract(char *buf,int ofs,char *name)
2563 char *p = name_ptr(buf,ofs);
2564 int d = PTR_DIFF(p,buf+ofs);
2566 if (d < -50 || d > 50) return(0);
2567 return(name_interpret(p,name));
2570 /****************************************************************************
2571 return the total storage length of a mangled name
2572 ****************************************************************************/
2573 int name_len( char *s )
2577 /* If the two high bits of the byte are set, return 2. */
2578 if( 0xC0 == (*(unsigned char *)s & 0xC0) )
2581 /* Add up the length bytes. */
2582 for( len = 1; (*s); s += (*s) + 1 )
2590 /****************************************************************************
2591 send a single packet to a port on another machine
2592 ****************************************************************************/
2593 BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
2597 struct sockaddr_in sock_out;
2602 /* create a socket to write to */
2603 out_fd = socket(AF_INET, type, 0);
2606 DEBUG(0,("socket failed"));
2610 /* set the address and port */
2611 bzero((char *)&sock_out,sizeof(sock_out));
2612 putip((char *)&sock_out.sin_addr,(char *)&ip);
2613 sock_out.sin_port = htons( port );
2614 sock_out.sin_family = AF_INET;
2617 DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
2618 len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));
2621 ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);
2624 DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
2625 inet_ntoa(ip),port,strerror(errno)));
2631 /*******************************************************************
2632 sleep for a specified number of milliseconds
2633 ********************************************************************/
2637 struct timeval tval,t1,t2;
2644 tval.tv_sec = (t-tdiff)/1000;
2645 tval.tv_usec = 1000*((t-tdiff)%1000);
2649 sys_select(&fds,&tval);
2652 tdiff = TvalDiff(&t1,&t2);
2656 /****************************************************************************
2657 check if a string is part of a list
2658 ****************************************************************************/
2659 BOOL in_list(char *s,char *list,BOOL casesensitive)
2664 if (!list) return(False);
2666 while (next_token(&p,tok,LIST_SEP))
2668 if (casesensitive) {
2669 if (strcmp(tok,s) == 0)
2672 if (StrCaseCmp(tok,s) == 0)
2679 /* this is used to prevent lots of mallocs of size 1 */
2680 static char *null_string = NULL;
2682 /****************************************************************************
2683 set a string value, allocing the space for the string
2684 ****************************************************************************/
2685 BOOL string_init(char **dest,char *src)
2696 null_string = (char *)malloc(1);
2699 *dest = null_string;
2703 (*dest) = (char *)malloc(l+1);
2704 if ((*dest) == NULL) {
2705 DEBUG(0,("Out of memory in string_init\n"));
2714 /****************************************************************************
2716 ****************************************************************************/
2717 void string_free(char **s)
2719 if (!s || !(*s)) return;
2720 if (*s == null_string)
2726 /****************************************************************************
2727 set a string value, allocing the space for the string, and deallocating any
2729 ****************************************************************************/
2730 BOOL string_set(char **dest,char *src)
2734 return(string_init(dest,src));
2737 /****************************************************************************
2738 substitute a string for a pattern in another string. Make sure there is
2741 This routine looks for pattern in s and replaces it with
2742 insert. It may do multiple replacements.
2744 return True if a substitution was done.
2745 ****************************************************************************/
2746 BOOL string_sub(char *s,char *pattern,char *insert)
2752 if (!insert || !pattern || !s) return(False);
2755 lp = strlen(pattern);
2756 li = strlen(insert);
2758 if (!*pattern) return(False);
2760 while (lp <= ls && (p = strstr(s,pattern)))
2763 memmove(p+li,p+lp,ls + 1 - (PTR_DIFF(p,s) + lp));
2764 memcpy(p,insert,li);
2773 /*********************************************************
2774 * Recursive routine that is called by mask_match.
2775 * Does the actual matching.
2776 *********************************************************/
2777 BOOL do_match(char *str, char *regexp, int case_sig)
2781 for( p = regexp; *p && *str; ) {
2788 /* Look for a character matching
2789 the one after the '*' */
2792 return True; /* Automatic match */
2794 while(*str && (case_sig ? (*p != *str) : (toupper(*p)!=toupper(*str))))
2796 if(do_match(str,p,case_sig))
2810 if(toupper(*str) != toupper(*p))
2820 if (!*p && str[0] == '.' && str[1] == 0)
2823 if (!*str && *p == '?')
2825 while (*p == '?') p++;
2829 if(!*str && (*p == '*' && p[1] == '\0'))
2835 /*********************************************************
2836 * Routine to match a given string with a regexp - uses
2837 * simplified regexp that takes * and ? only. Case can be
2838 * significant or not.
2839 *********************************************************/
2840 BOOL mask_match(char *str, char *regexp, int case_sig,BOOL trans2)
2844 fstring ebase,eext,sbase,sext;
2848 /* Make local copies of str and regexp */
2849 StrnCpy(p1,regexp,sizeof(pstring)-1);
2850 StrnCpy(p2,str,sizeof(pstring)-1);
2852 if (!strchr(p2,'.')) {
2857 if (!strchr(p1,'.')) {
2865 string_sub(p1,"*.*","*");
2866 string_sub(p1,".*","*");
2870 /* Remove any *? and ** as they are meaningless */
2871 for(p = p1; *p; p++)
2872 while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
2873 (void)strcpy( &p[1], &p[2]);
2875 if (strequal(p1,"*")) return(True);
2877 DEBUG(8,("mask_match str=<%s> regexp=<%s>, case_sig = %d\n", p2, p1, case_sig));
2883 if ((p=strrchr(p1,'.'))) {
2892 if (!strequal(p2,".") && !strequal(p2,"..") && (p=strrchr(p2,'.'))) {
2902 matched = do_match(sbase,ebase,case_sig) &&
2903 (trans2 || do_match(sext,eext,case_sig));
2905 DEBUG(8,("mask_match returning %d\n", matched));
2912 /****************************************************************************
2913 become a daemon, discarding the controlling terminal
2914 ****************************************************************************/
2915 void become_daemon(void)
2917 #ifndef NO_FORK_DEBUG
2921 /* detach from the terminal */
2924 #else /* USE_SETSID */
2927 int i = open("/dev/tty", O_RDWR);
2930 ioctl(i, (int) TIOCNOTTY, (char *)0);
2934 #endif /* TIOCNOTTY */
2935 #endif /* USE_SETSID */
2936 /* Close fd's 0,1,2. Needed if started by rsh */
2938 #endif /* NO_FORK_DEBUG */
2942 /****************************************************************************
2943 put up a yes/no prompt
2944 ****************************************************************************/
2950 if (!fgets(ans,sizeof(ans)-1,stdin))
2953 if (*ans == 'y' || *ans == 'Y')
2959 /****************************************************************************
2960 read a line from a file with possible \ continuation chars.
2961 Blanks at the start or end of a line are stripped.
2962 The string will be allocated if s2 is NULL
2963 ****************************************************************************/
2964 char *fgets_slash(char *s2,int maxlen,FILE *f)
2969 BOOL start_of_line = True;
2976 maxlen = MIN(maxlen,8);
2977 s = (char *)Realloc(s,maxlen);
2980 if (!s || maxlen < 2) return(NULL);
2984 while (len < maxlen-1)
2992 while (len > 0 && s[len-1] == ' ')
2996 if (len > 0 && s[len-1] == '\\')
2999 start_of_line = True;
3004 if (len <= 0 && !s2)
3006 return(len>0?s:NULL);
3011 start_of_line = False;
3015 if (!s2 && len > maxlen-3)
3018 s = (char *)Realloc(s,maxlen);
3019 if (!s) return(NULL);
3027 /****************************************************************************
3028 set the length of a file from a filedescriptor.
3029 Returns 0 on success, -1 on failure.
3030 ****************************************************************************/
3031 int set_filelen(int fd, long len)
3033 /* According to W. R. Stevens advanced UNIX prog. Pure 4.3 BSD cannot
3034 extend a file with ftruncate. Provide alternate implementation
3037 #if FTRUNCATE_CAN_EXTEND
3038 return ftruncate(fd, len);
3042 long currpos = lseek(fd, 0L, SEEK_CUR);
3046 /* Do an fstat to see if the file is longer than
3047 the requested size (call ftruncate),
3048 or shorter, in which case seek to len - 1 and write 1
3050 if(fstat(fd, &st)<0)
3054 if (S_ISFIFO(st.st_mode)) return 0;
3057 if(st.st_size == len)
3059 if(st.st_size > len)
3060 return ftruncate(fd, len);
3062 if(lseek(fd, len-1, SEEK_SET) != len -1)
3064 if(write(fd, &c, 1)!=1)
3066 /* Seek to where we were */
3067 lseek(fd, currpos, SEEK_SET);
3073 /****************************************************************************
3074 return the byte checksum of some data
3075 ****************************************************************************/
3076 int byte_checksum(char *buf,int len)
3078 unsigned char *p = (unsigned char *)buf;
3088 /****************************************************************************
3089 this is a version of setbuffer() for those machines that only have setvbuf
3090 ****************************************************************************/
3091 void setbuffer(FILE *f,char *buf,int bufsize)
3093 setvbuf(f,buf,_IOFBF,bufsize);
3098 /****************************************************************************
3099 parse out a directory name from a path name. Assumes dos style filenames.
3100 ****************************************************************************/
3101 char *dirname_dos(char *path,char *buf)
3103 char *p = strrchr(path,'\\');
3118 /****************************************************************************
3119 parse out a filename from a path name. Assumes dos style filenames.
3120 ****************************************************************************/
3121 static char *filename_dos(char *path,char *buf)
3123 char *p = strrchr(path,'\\');
3135 /****************************************************************************
3136 expand a pointer to be a particular size
3137 ****************************************************************************/
3138 void *Realloc(void *p,int size)
3144 DEBUG(5,("Realloc asked for 0 bytes\n"));
3149 ret = (void *)malloc(size);
3151 ret = (void *)realloc(p,size);
3154 DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",size));
3160 /****************************************************************************
3162 ****************************************************************************/
3163 char *strdup(char *s)
3166 if (!s) return(NULL);
3167 ret = (char *)malloc(strlen(s)+1);
3168 if (!ret) return(NULL);
3175 /****************************************************************************
3176 Signal handler for SIGPIPE (write on a disconnected socket)
3177 ****************************************************************************/
3180 DEBUG(0,("Probably got SIGPIPE\nExiting\n"));
3184 /****************************************************************************
3185 get my own name and IP
3186 ****************************************************************************/
3187 BOOL get_myname(char *my_name,struct in_addr *ip)
3194 /* get my host name */
3195 if (gethostname(hostname, MAXHOSTNAMELEN) == -1)
3197 DEBUG(0,("gethostname failed\n"));
3202 if ((hp = Get_Hostbyname(hostname)) == 0)
3204 DEBUG(0,( "Get_Hostbyname: Unknown host %s.\n",hostname));
3210 /* split off any parts after an initial . */
3211 char *p = strchr(hostname,'.');
3214 fstrcpy(my_name,hostname);
3218 putip((char *)ip,(char *)hp->h_addr);
3224 /****************************************************************************
3225 true if two IP addresses are equal
3226 ****************************************************************************/
3227 BOOL ip_equal(struct in_addr ip1,struct in_addr ip2)
3230 a1 = ntohl(ip1.s_addr);
3231 a2 = ntohl(ip2.s_addr);
3236 /****************************************************************************
3237 open a socket of the specified type, port and address for incoming data
3238 ****************************************************************************/
3239 int open_socket_in(int type, int port, int dlevel,uint32 socket_addr)
3242 struct sockaddr_in sock;
3246 /* get my host name */
3247 if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
3248 { DEBUG(0,("gethostname failed\n")); return -1; }
3251 if ((hp = Get_Hostbyname(host_name)) == 0)
3253 DEBUG(0,( "Get_Hostbyname: Unknown host. %s\n",host_name));
3257 bzero((char *)&sock,sizeof(sock));
3258 memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
3259 #if defined(__FreeBSD__) || defined(NETBSD) /* XXX not the right ifdef */
3260 sock.sin_len = sizeof(sock);
3262 sock.sin_port = htons( port );
3263 sock.sin_family = hp->h_addrtype;
3264 sock.sin_addr.s_addr = socket_addr;
3265 res = socket(hp->h_addrtype, type, 0);
3267 { DEBUG(0,("socket failed\n")); return -1; }
3271 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
3274 /* now we've got a socket - we need to bind it */
3275 if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
3278 if (port == SMB_PORT || port == NMB_PORT)
3279 DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
3280 port,inet_ntoa(sock.sin_addr),strerror(errno)));
3283 if (dlevel > 0 && port < 1000)
3286 if (port >= 1000 && port < 9000)
3287 return(open_socket_in(type,port+1,dlevel,socket_addr));
3292 DEBUG(3,("bind succeeded on port %d\n",port));
3298 /****************************************************************************
3299 create an outgoing socket
3300 **************************************************************************/
3301 int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
3303 struct sockaddr_in sock_out;
3305 int connect_loop = 250; /* 250 milliseconds */
3306 int loops = (timeout * 1000) / connect_loop;
3308 /* create a socket to write to */
3309 res = socket(PF_INET, type, 0);
3311 { DEBUG(0,("socket error\n")); return -1; }
3313 if (type != SOCK_STREAM) return(res);
3315 bzero((char *)&sock_out,sizeof(sock_out));
3316 putip((char *)&sock_out.sin_addr,(char *)addr);
3318 sock_out.sin_port = htons( port );
3319 sock_out.sin_family = PF_INET;
3321 /* set it non-blocking */
3322 set_blocking(res,False);
3324 DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));
3326 /* and connect it to the destination */
3328 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
3330 /* Some systems return EAGAIN when they mean EINPROGRESS */
3331 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3332 errno == EAGAIN) && loops--) {
3333 msleep(connect_loop);
3337 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
3339 DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
3345 if (ret < 0 && errno == EISCONN) {
3352 DEBUG(1,("error connecting to %s:%d (%s)\n",
3353 inet_ntoa(*addr),port,strerror(errno)));
3357 /* set it blocking again */
3358 set_blocking(res,True);
3364 /****************************************************************************
3365 interpret a protocol description string, with a default
3366 ****************************************************************************/
3367 int interpret_protocol(char *str,int def)
3369 if (strequal(str,"NT1"))
3370 return(PROTOCOL_NT1);
3371 if (strequal(str,"LANMAN2"))
3372 return(PROTOCOL_LANMAN2);
3373 if (strequal(str,"LANMAN1"))
3374 return(PROTOCOL_LANMAN1);
3375 if (strequal(str,"CORE"))
3376 return(PROTOCOL_CORE);
3377 if (strequal(str,"COREPLUS"))
3378 return(PROTOCOL_COREPLUS);
3379 if (strequal(str,"CORE+"))
3380 return(PROTOCOL_COREPLUS);
3382 DEBUG(0,("Unrecognised protocol level %s\n",str));
3387 /****************************************************************************
3388 interpret a security level
3389 ****************************************************************************/
3390 int interpret_security(char *str,int def)
3392 if (strequal(str,"SERVER"))
3394 if (strequal(str,"USER"))
3396 if (strequal(str,"SHARE"))
3399 DEBUG(0,("Unrecognised security level %s\n",str));
3405 /****************************************************************************
3406 interpret an internet address or name into an IP address in 4 byte form
3407 ****************************************************************************/
3408 uint32 interpret_addr(char *str)
3413 BOOL pure_address = True;
3415 if (strcmp(str,"0.0.0.0") == 0) return(0);
3416 if (strcmp(str,"255.255.255.255") == 0) return(0xFFFFFFFF);
3418 for (i=0; pure_address && str[i]; i++)
3419 if (!(isdigit(str[i]) || str[i] == '.'))
3420 pure_address = False;
3422 /* if it's in the form of an IP address then get the lib to interpret it */
3424 res = inet_addr(str);
3426 /* otherwise assume it's a network name of some sort and use
3428 if ((hp = Get_Hostbyname(str)) == 0) {
3429 DEBUG(3,("Get_Hostbyname: Unknown host. %s\n",str));
3432 if(hp->h_addr == NULL) {
3433 DEBUG(3,("Get_Hostbyname: host address is invalid for host %s.\n",str));
3436 putip((char *)&res,(char *)hp->h_addr);
3439 if (res == (uint32)-1) return(0);
3444 /*******************************************************************
3445 a convenient addition to interpret_addr()
3446 ******************************************************************/
3447 struct in_addr *interpret_addr2(char *str)
3449 static struct in_addr ret;
3450 uint32 a = interpret_addr(str);
3455 /*******************************************************************
3456 check if an IP is the 0.0.0.0
3457 ******************************************************************/
3458 BOOL zero_ip(struct in_addr ip)
3461 putip((char *)&a,(char *)&ip);
3466 /*******************************************************************
3467 matchname - determine if host name matches IP address
3468 ******************************************************************/
3469 static BOOL matchname(char *remotehost,struct in_addr addr)
3474 if ((hp = Get_Hostbyname(remotehost)) == 0) {
3475 DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
3480 * Make sure that gethostbyname() returns the "correct" host name.
3481 * Unfortunately, gethostbyname("localhost") sometimes yields
3482 * "localhost.domain". Since the latter host name comes from the
3483 * local DNS, we just have to trust it (all bets are off if the local
3484 * DNS is perverted). We always check the address list, though.
3487 if (strcasecmp(remotehost, hp->h_name)
3488 && strcasecmp(remotehost, "localhost")) {
3489 DEBUG(0,("host name/name mismatch: %s != %s",
3490 remotehost, hp->h_name));
3494 /* Look up the host address in the address list we just got. */
3495 for (i = 0; hp->h_addr_list[i]; i++) {
3496 if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
3501 * The host name does not map to the original host address. Perhaps
3502 * someone has compromised a name server. More likely someone botched
3503 * it, but that could be dangerous, too.
3506 DEBUG(0,("host name/address mismatch: %s != %s",
3507 inet_ntoa(addr), hp->h_name));
3511 /*******************************************************************
3512 Reset the 'done' variables so after a client process is created
3513 from a fork call these calls will be re-done. This should be
3514 expanded if more variables need reseting.
3515 ******************************************************************/
3517 static BOOL global_client_name_done = False;
3518 static BOOL global_client_addr_done = False;
3520 void reset_globals_after_fork()
3522 global_client_name_done = False;
3523 global_client_addr_done = False;
3526 /*******************************************************************
3527 return the DNS name of the client
3528 ******************************************************************/
3529 char *client_name(void)
3533 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3534 int length = sizeof(sa);
3535 static pstring name_buf;
3538 if (global_client_name_done)
3541 strcpy(name_buf,"UNKNOWN");
3547 if (getpeername(Client, &sa, &length) < 0) {
3548 DEBUG(0,("getpeername failed\n"));
3552 /* Look up the remote host name. */
3553 if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
3554 sizeof(sockin->sin_addr),
3556 DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr()));
3557 StrnCpy(name_buf,client_addr(),sizeof(name_buf) - 1);
3559 StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
3560 if (!matchname(name_buf, sockin->sin_addr)) {
3561 DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr()));
3562 strcpy(name_buf,"UNKNOWN");
3565 global_client_name_done = True;
3569 /*******************************************************************
3570 return the IP addr of the client as a string
3571 ******************************************************************/
3572 char *client_addr(void)
3576 struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
3577 int length = sizeof(sa);
3578 static fstring addr_buf;
3580 if (global_client_addr_done)
3583 strcpy(addr_buf,"0.0.0.0");
3589 if (getpeername(Client, &sa, &length) < 0) {
3590 DEBUG(0,("getpeername failed\n"));
3594 fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
3596 global_client_addr_done = True;
3600 char *automount_server(char *user_name)
3602 static pstring server_name;
3604 #if (defined(NETGROUP) && defined (AUTOMOUNT))
3605 int nis_error; /* returned by yp all functions */
3606 char *nis_result; /* yp_match inits this */
3607 int nis_result_len; /* and set this */
3608 char *nis_domain; /* yp_get_default_domain inits this */
3609 char *nis_map = (char *)lp_nis_home_map_name();
3610 int home_server_len;
3612 /* set to default of local machine */
3613 pstrcpy(server_name, local_machine);
3615 if ((nis_error = yp_get_default_domain(&nis_domain)) != 0)
3617 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3620 DEBUG(5, ("NIS Domain: %s\n", nis_domain));
3622 if ((nis_error = yp_match(nis_domain, nis_map,
3623 user_name, strlen(user_name),
3624 &nis_result, &nis_result_len)) != 0)
3626 DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
3629 if (!nis_error && lp_nis_home_map())
3631 home_server_len = strcspn(nis_result,":");
3632 DEBUG(5, ("NIS lookup succeeded. Home server length: %d\n",home_server_len));
3633 if (home_server_len > sizeof(pstring))
3635 home_server_len = sizeof(pstring);
3637 strncpy(server_name, nis_result, home_server_len);
3640 /* use the local machine name instead of the auto-map server */
3641 pstrcpy(server_name, local_machine);
3644 DEBUG(4,("Home server: %s\n", server_name));
3649 /*******************************************************************
3650 sub strings with useful parameters
3651 Rewritten by Stefaan A Eeckels <Stefaan.Eeckels@ecc.lu> and
3652 Paul Rippin <pr3245@nopc.eurostat.cec.be>
3653 ********************************************************************/
3654 void standard_sub_basic(char *str)
3658 struct passwd *pass;
3659 char *username = sam_logon_in_ssb ? samlogon_user : sesssetup_user;
3661 for (s = str ; (p = strchr(s,'%')) != NULL ; s = p )
3667 if ((pass = Get_Pwnam(sesssetup_user,False))!=NULL)
3669 string_sub(p,"%G",gidtoname(pass->pw_gid));
3677 case 'N' : string_sub(p,"%N", automount_server(username)); break;
3678 case 'I' : string_sub(p,"%I", client_addr()); break;
3679 case 'L' : string_sub(p,"%L", local_machine); break;
3680 case 'M' : string_sub(p,"%M", client_name()); break;
3681 case 'R' : string_sub(p,"%R", remote_proto); break;
3682 case 'T' : string_sub(p,"%T", timestring()); break;
3683 case 'U' : string_sub(p,"%U", username); break;
3684 case 'a' : string_sub(p,"%a", remote_arch); break;
3687 sprintf(pidstr,"%d",(int)getpid());
3688 string_sub(p,"%d", pidstr);
3691 case 'h' : string_sub(p,"%h", myhostname); break;
3692 case 'm' : string_sub(p,"%m", remote_machine); break;
3693 case 'v' : string_sub(p,"%v", VERSION); break;
3694 case '\0': p++; break; /* don't run off end if last character is % */
3695 default : p+=2; break;
3701 /*******************************************************************
3702 are two IPs on the same subnet?
3703 ********************************************************************/
3704 BOOL same_net(struct in_addr ip1,struct in_addr ip2,struct in_addr mask)
3706 uint32 net1,net2,nmask;
3708 nmask = ntohl(mask.s_addr);
3709 net1 = ntohl(ip1.s_addr);
3710 net2 = ntohl(ip2.s_addr);
3712 return((net1 & nmask) == (net2 & nmask));
3716 /*******************************************************************
3717 write a string in unicoode format
3718 ********************************************************************/
3719 int PutUniCode(char *dst,char *src)
3723 dst[ret++] = src[0];
3732 /****************************************************************************
3733 a wrapper for gethostbyname() that tries with all lower and all upper case
3734 if the initial name fails
3735 ****************************************************************************/
3736 struct hostent *Get_Hostbyname(char *name)
3738 char *name2 = strdup(name);
3739 struct hostent *ret;
3743 DEBUG(0,("Memory allocation error in Get_Hostbyname! panic\n"));
3747 if (!isalnum(*name2))
3753 ret = sys_gethostbyname(name2);
3760 /* try with all lowercase */
3762 ret = sys_gethostbyname(name2);
3769 /* try with all uppercase */
3771 ret = sys_gethostbyname(name2);
3778 /* nothing works :-( */
3784 /****************************************************************************
3785 check if a process exists. Does this work on all unixes?
3786 ****************************************************************************/
3787 BOOL process_exists(int pid)
3789 return(kill(pid,0) == 0 || errno != ESRCH);
3793 /*******************************************************************
3794 turn a uid into a user name
3795 ********************************************************************/
3796 char *uidtoname(int uid)
3798 static char name[40];
3799 struct passwd *pass = getpwuid(uid);
3800 if (pass) return(pass->pw_name);
3801 sprintf(name,"%d",uid);
3805 /*******************************************************************
3806 turn a gid into a group name
3807 ********************************************************************/
3808 char *gidtoname(int gid)
3810 static char name[40];
3811 struct group *grp = getgrgid(gid);
3812 if (grp) return(grp->gr_name);
3813 sprintf(name,"%d",gid);
3817 /*******************************************************************
3819 ********************************************************************/
3820 void BlockSignals(BOOL block,int signum)
3823 int block_mask = sigmask(signum);
3824 static int oldmask = 0;
3826 oldmask = sigblock(block_mask);
3828 sigsetmask(oldmask);
3829 #elif defined(USE_SIGPROCMASK)
3832 sigaddset(&set,signum);
3833 sigprocmask(block?SIG_BLOCK:SIG_UNBLOCK,&set,NULL);
3838 /*******************************************************************
3839 my own panic function - not suitable for general use
3840 ********************************************************************/
3841 void ajt_panic(void)
3843 system("/usr/bin/X11/xedit -display solen:0 /tmp/ERROR_FAULT");
3848 #define DIRECT direct
3850 #define DIRECT dirent
3853 /*******************************************************************
3854 a readdir wrapper which just returns the file name
3855 also return the inode number if requested
3856 ********************************************************************/
3857 char *readdirname(void *p)
3862 if (!p) return(NULL);
3864 ptr = (struct DIRECT *)readdir(p);
3865 if (!ptr) return(NULL);
3867 dname = ptr->d_name;
3870 if (telldir(p) < 0) return(NULL);
3874 /* this handles a broken compiler setup, causing a mixture
3875 of BSD and SYSV headers and libraries */
3877 static BOOL broken_readdir = False;
3878 if (!broken_readdir && !(*(dname)) && strequal("..",dname-2))
3880 DEBUG(0,("Your readdir() is broken. You have somehow mixed SYSV and BSD headers and libraries\n"));
3881 broken_readdir = True;
3890 pstrcpy(buf, dname);
3891 unix_to_dos(buf, True);
3898 /*******************************************************************
3899 Utility function used to decide if the last component
3900 of a path matches a (possibly wildcarded) entry in a namelist.
3901 ********************************************************************/
3903 BOOL is_in_path(char *name, name_compare_entry *namelist)
3905 pstring last_component;
3908 DEBUG(8, ("is_in_path: %s\n", name));
3910 /* if we have no list it's obviously not in the path */
3911 if((namelist == NULL ) || ((namelist != NULL) && (namelist[0].name == NULL)))
3913 DEBUG(8,("is_in_path: no name list.\n"));
3917 /* Get the last component of the unix name. */
3918 p = strrchr(name, '/');
3919 strncpy(last_component, p ? p : name, sizeof(last_component)-1);
3920 last_component[sizeof(last_component)-1] = '\0';
3922 for(; namelist->name != NULL; namelist++)
3924 if(namelist->is_wild)
3926 /* look for a wildcard match. */
3927 if (mask_match(last_component, namelist->name, case_sensitive, False))
3929 DEBUG(8,("is_in_path: mask match succeeded\n"));
3935 if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
3936 (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0)))
3938 DEBUG(8,("is_in_path: match succeeded\n"));
3943 DEBUG(8,("is_in_path: match not found\n"));
3948 /*******************************************************************
3949 Strip a '/' separated list into an array of
3950 name_compare_enties structures suitable for
3951 passing to is_in_path(). We do this for
3952 speed so we can pre-parse all the names in the list
3953 and don't do it for each call to is_in_path().
3954 namelist is modified here and is assumed to be
3955 a copy owned by the caller.
3956 We also check if the entry contains a wildcard to
3957 remove a potentially expensive call to mask_match
3959 ********************************************************************/
3961 void set_namearray(name_compare_entry **ppname_array, char *namelist)
3964 char *nameptr = namelist;
3965 int num_entries = 0;
3968 (*ppname_array) = NULL;
3970 if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0')))
3973 /* We need to make two passes over the string. The
3974 first to count the number of elements, the second
3979 if ( *nameptr == '/' )
3981 /* cope with multiple (useless) /s) */
3985 /* find the next / */
3986 name_end = strchr(nameptr, '/');
3988 /* oops - the last check for a / didn't find one. */
3989 if (name_end == NULL)
3992 /* next segment please */
3993 nameptr = name_end + 1;
3997 if(num_entries == 0)
4000 if(( (*ppname_array) = (name_compare_entry *)malloc(
4001 (num_entries + 1) * sizeof(name_compare_entry))) == NULL)
4003 DEBUG(0,("set_namearray: malloc fail\n"));
4007 /* Now copy out the names */
4012 if ( *nameptr == '/' )
4014 /* cope with multiple (useless) /s) */
4018 /* find the next / */
4019 if ((name_end = strchr(nameptr, '/')) != NULL)
4024 /* oops - the last check for a / didn't find one. */
4025 if(name_end == NULL)
4028 (*ppname_array)[i].is_wild = ((strchr( nameptr, '?')!=NULL) ||
4029 (strchr( nameptr, '*')!=NULL));
4030 if(((*ppname_array)[i].name = strdup(nameptr)) == NULL)
4032 DEBUG(0,("set_namearray: malloc fail (1)\n"));
4036 /* next segment please */
4037 nameptr = name_end + 1;
4041 (*ppname_array)[i].name = NULL;
4046 /****************************************************************************
4047 routine to free a namearray.
4048 ****************************************************************************/
4050 void free_namearray(name_compare_entry *name_array)
4055 if(name_array->name != NULL)
4056 free(name_array->name);
4058 free((char *)name_array);
4061 /****************************************************************************
4062 routine to do file locking
4063 ****************************************************************************/
4064 BOOL fcntl_lock(int fd,int op,uint32 offset,uint32 count,int type)
4071 uint32 mask = 0xC0000000;
4073 /* make sure the count is reasonable, we might kill the lockd otherwise */
4076 /* the offset is often strange - remove 2 of its bits if either of
4077 the top two bits are set. Shift the top ones by two bits. This
4078 still allows OLE2 apps to operate, but should stop lockd from
4080 if ((offset & mask) != 0)
4081 offset = (offset & ~mask) | ((offset & mask) >> 2);
4083 uint32 mask = ((unsigned)1<<31);
4085 /* interpret negative counts as large numbers */
4089 /* no negative offsets */
4092 /* count + offset must be in range */
4093 while ((offset < 0 || (offset + count < 0)) && mask)
4101 DEBUG(8,("fcntl_lock %d %d %d %d %d\n",fd,op,(int)offset,(int)count,type));
4104 lock.l_whence = SEEK_SET;
4105 lock.l_start = (int)offset;
4106 lock.l_len = (int)count;
4111 ret = fcntl(fd,op,&lock);
4114 DEBUG(3,("fcntl lock gave errno %d (%s)\n",errno,strerror(errno)));
4120 (lock.l_type != F_UNLCK) &&
4121 (lock.l_pid != 0) &&
4122 (lock.l_pid != getpid()))
4124 DEBUG(3,("fd %d is locked by pid %d\n",fd,lock.l_pid));
4128 /* it must be not locked or locked by me */
4132 /* a lock set or unset */
4135 DEBUG(3,("lock failed at offset %d count %d op %d type %d (%s)\n",
4136 offset,count,op,type,strerror(errno)));
4138 /* perhaps it doesn't support this sort of locking?? */
4139 if (errno == EINVAL)
4141 DEBUG(3,("locking not supported? returning True\n"));
4148 /* everything went OK */
4149 DEBUG(8,("Lock call successful\n"));
4157 /*******************************************************************
4158 lock a file - returning a open file descriptor or -1 on failure
4159 The timeout is in seconds. 0 means no timeout
4160 ********************************************************************/
4161 int file_lock(char *name,int timeout)
4163 int fd = open(name,O_RDWR|O_CREAT,0666);
4165 if (fd < 0) return(-1);
4168 if (timeout) t = time(NULL);
4169 while (!timeout || (time(NULL)-t < timeout)) {
4170 if (fcntl_lock(fd,F_SETLK,0,1,F_WRLCK)) return(fd);
4171 msleep(LOCK_RETRY_TIMEOUT);
4179 /*******************************************************************
4180 unlock a file locked by file_lock
4181 ********************************************************************/
4182 void file_unlock(int fd)
4186 fcntl_lock(fd,F_SETLK,0,1,F_UNLCK);
4191 /*******************************************************************
4192 is the name specified one of my netbios names
4193 returns true is it is equal, false otherwise
4194 ********************************************************************/
4195 BOOL is_myname(char *s)
4200 for (n=0; my_netbios_names[n]; n++) {
4201 if (strequal(my_netbios_names[n], s))
4204 DEBUG(8, ("is_myname(\"%s\") returns %d\n", s, ret));
4208 /*******************************************************************
4209 set the horrid remote_arch string based on an enum.
4210 ********************************************************************/
4211 void set_remote_arch(enum remote_arch_types type)
4217 strcpy(remote_arch, "WfWg");
4220 strcpy(remote_arch, "OS2");
4223 strcpy(remote_arch, "Win95");
4226 strcpy(remote_arch, "WinNT");
4229 strcpy(remote_arch,"Samba");
4232 ra_type = RA_UNKNOWN;
4233 strcpy(remote_arch, "UNKNOWN");
4238 /*******************************************************************
4239 Get the remote_arch type.
4240 ********************************************************************/
4241 enum remote_arch_types get_remote_arch()
4247 /*******************************************************************
4248 skip past some unicode strings in a buffer
4249 ********************************************************************/
4250 char *skip_unicode_string(char *buf,int n)
4261 /*******************************************************************
4262 Return a ascii version of a unicode string
4263 Hack alert: uses fixed buffer(s) and only handles ascii strings
4264 ********************************************************************/
4266 char *unistrn2(uint16 *buf, int len)
4268 static char lbufs[8][MAXUNI];
4270 char *lbuf = lbufs[nexti];
4273 nexti = (nexti+1)%8;
4275 DEBUG(10, ("unistrn2: "));
4277 for (p = lbuf; *buf && p-lbuf < MAXUNI-2 && len > 0; len--, p++, buf++)
4279 DEBUG(10, ("%4x ", *buf));
4289 /*******************************************************************
4290 Return a ascii version of a unicode string
4291 Hack alert: uses fixed buffer(s) and only handles ascii strings
4292 ********************************************************************/
4294 char *unistr2(uint16 *buf)
4296 static char lbufs[8][MAXUNI];
4298 char *lbuf = lbufs[nexti];
4301 nexti = (nexti+1)%8;
4303 DEBUG(10, ("unistr2: "));
4305 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf++)
4307 DEBUG(10, ("%4x ", *buf));
4317 /*******************************************************************
4318 create a null-terminated unicode string from a null-terminated ascii string.
4319 return number of unicode chars copied, excluding the null character.
4321 only handles ascii strings
4322 ********************************************************************/
4324 int struni2(uint16 *p, char *buf)
4328 if (p == NULL) return 0;
4330 DEBUG(10, ("struni2: "));
4334 for (; *buf && len < MAXUNI-2; len++, p++, buf++)
4336 DEBUG(10, ("%2x ", *buf));
4348 /*******************************************************************
4349 Return a ascii version of a unicode string
4350 Hack alert: uses fixed buffer(s) and only handles ascii strings
4351 ********************************************************************/
4353 char *unistr(char *buf)
4355 static char lbufs[8][MAXUNI];
4357 char *lbuf = lbufs[nexti];
4360 nexti = (nexti+1)%8;
4362 for (p = lbuf; *buf && p-lbuf < MAXUNI-2; p++, buf += 2)
4370 /*******************************************************************
4371 strncpy for unicode strings
4372 ********************************************************************/
4373 int unistrncpy(char *dst, char *src, int len)
4377 while (*src && len > 0)
4391 /*******************************************************************
4392 strcpy for unicode strings. returns length (in num of wide chars)
4393 ********************************************************************/
4394 int unistrcpy(char *dst, char *src)
4411 /*******************************************************************
4412 safe string copy into a fstring
4413 ********************************************************************/
4414 void fstrcpy(char *dest, char *src)
4416 int maxlength = sizeof(fstring) - 1;
4418 DEBUG(0,("ERROR: NULL dest in fstrcpy\n"));
4427 while (maxlength-- && *src)
4431 DEBUG(0,("ERROR: string overflow by %d in fstrcpy\n",
4436 /*******************************************************************
4437 safe string copy into a pstring
4438 ********************************************************************/
4439 void pstrcpy(char *dest, char *src)
4441 int maxlength = sizeof(pstring) - 1;
4443 DEBUG(0,("ERROR: NULL dest in pstrcpy\n"));
4452 while (maxlength-- && *src)
4456 DEBUG(0,("ERROR: string overflow by %d in pstrcpy\n",
4462 /*******************************************************************
4463 align a pointer to a multiple of 4 bytes
4464 ********************************************************************/
4465 char *align4(char *q, char *base)
4469 q += 4 - ((q - base) & 3);
4474 /*******************************************************************
4475 align a pointer to a multiple of 2 bytes
4476 ********************************************************************/
4477 char *align2(char *q, char *base)
4486 /*******************************************************************
4487 align a pointer to a multiple of align_offset bytes. looks like it
4488 will work for offsets of 0, 2 and 4...
4489 ********************************************************************/
4490 char *align_offset(char *q, char *base, int align_offset_len)
4492 int mod = ((q - base) & (align_offset_len-1));
4493 if (align_offset_len != 0 && mod != 0)
4495 q += align_offset_len - mod;
4500 void print_asc(int level, unsigned char *buf,int len)
4504 DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
4507 void dump_data(int level,char *buf1,int len)
4509 unsigned char *buf = (unsigned char *)buf1;
4513 DEBUG(level,("[%03X] ",i));
4515 DEBUG(level,("%02X ",(int)buf[i]));
4517 if (i%8 == 0) DEBUG(level,(" "));
4519 print_asc(level,&buf[i-16],8); DEBUG(level,(" "));
4520 print_asc(level,&buf[i-8],8); DEBUG(level,("\n"));
4521 if (i<len) DEBUG(level,("[%03X] ",i));
4529 if (n>8) DEBUG(level,(" "));
4530 while (n--) DEBUG(level,(" "));
4533 print_asc(level,&buf[i-(i%16)],n); DEBUG(level,(" "));
4535 if (n>0) print_asc(level,&buf[i-n],n);
4536 DEBUG(level,("\n"));
4540 char *tab_depth(int depth)
4542 static pstring spaces;
4543 memset(spaces, ' ', depth * 4);
4544 spaces[depth * 4] = 0;