/* Unix SMB/Netbios implementation. Version 1.9. Main SMB reply routines Copyright (C) Andrew Tridgell 1992-1997 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* This file handles most of the reply_ calls that the server makes to handle specific protocols */ #include "includes.h" #include "trans2.h" #include "nterr.h" /* look in server.c for some explanation of these variables */ extern int Protocol; extern int DEBUGLEVEL; extern int max_send; extern int max_recv; extern int chain_fnum; extern char magic_char; extern connection_struct Connections[]; extern files_struct Files[]; extern BOOL case_sensitive; extern BOOL case_preserve; extern BOOL short_case_preserve; extern pstring sesssetup_user; extern fstring myworkgroup; extern int Client; extern int global_oplock_break; /* this macro should always be used to extract an fnum (smb_fid) from a packet to ensure chaining works correctly */ #define GETFNUM(buf,where) (chain_fnum!= -1?chain_fnum:SVAL(buf,where)) /**************************************************************************** report a possible attack via the password buffer overflow bug ****************************************************************************/ static void overflow_attack(int len) { DEBUG(0,("ERROR: Invalid password length %d\n", len)); DEBUG(0,("your machine may be under attack by a user exploiting an old bug\n")); DEBUG(0,("Attack was from IP=%s\n", client_addr())); exit_server("possible attack"); } /**************************************************************************** reply to an special message ****************************************************************************/ int reply_special(char *inbuf,char *outbuf) { int outsize = 4; int msg_type = CVAL(inbuf,0); int msg_flags = CVAL(inbuf,1); pstring name1,name2; extern fstring remote_machine; extern fstring local_machine; char *p; *name1 = *name2 = 0; smb_setlen(outbuf,0); switch (msg_type) { case 0x81: /* session request */ CVAL(outbuf,0) = 0x82; CVAL(outbuf,3) = 0; if (name_len(inbuf+4) > 50 || name_len(inbuf+4 + name_len(inbuf + 4)) > 50) { DEBUG(0,("Invalid name length in session request\n")); return(0); } name_extract(inbuf,4,name1); name_extract(inbuf,4 + name_len(inbuf + 4),name2); DEBUG(2,("netbios connect: name1=%s name2=%s\n", name1,name2)); fstrcpy(remote_machine,name2); trim_string(remote_machine," "," "); p = strchr(remote_machine,' '); strlower(remote_machine); if (p) *p = 0; fstrcpy(local_machine,name1); trim_string(local_machine," "," "); p = strchr(local_machine,' '); strlower(local_machine); if (p) *p = 0; add_session_user(remote_machine); reload_services(True); reopen_logs(); break; case 0x89: /* session keepalive request (some old clients produce this?) */ CVAL(outbuf,0) = 0x85; CVAL(outbuf,3) = 0; break; case 0x82: /* positive session response */ case 0x83: /* negative session response */ case 0x84: /* retarget session response */ DEBUG(0,("Unexpected session response\n")); break; case 0x85: /* session keepalive */ default: return(0); } DEBUG(5,("%s init msg_type=0x%x msg_flags=0x%x\n", timestring(),msg_type,msg_flags)); return(outsize); } /******************************************************************* work out what error to give to a failed connection ********************************************************************/ static int connection_error(char *inbuf,char *outbuf,int connection_num) { switch (connection_num) { case -8: return(ERROR(ERRSRV,ERRnoresource)); case -7: return(ERROR(ERRSRV,ERRbaduid)); case -6: return(ERROR(ERRSRV,ERRinvdevice)); case -5: return(ERROR(ERRSRV,ERRinvnetname)); case -4: return(ERROR(ERRSRV,ERRaccess)); case -3: return(ERROR(ERRDOS,ERRnoipc)); case -2: return(ERROR(ERRSRV,ERRinvnetname)); } return(ERROR(ERRSRV,ERRbadpw)); } /**************************************************************************** parse a share descriptor string ****************************************************************************/ static void parse_connect(char *p,char *service,char *user, char *password,int *pwlen,char *dev) { char *p2; DEBUG(4,("parsing connect string %s\n",p)); p2 = strrchr(p,'\\'); if (p2 == NULL) fstrcpy(service,p); else fstrcpy(service,p2+1); p += strlen(p) + 2; fstrcpy(password,p); *pwlen = strlen(password); p += strlen(p) + 2; fstrcpy(dev,p); *user = 0; p = strchr(service,'%'); if (p != NULL) { *p = 0; fstrcpy(user,p+1); } } /**************************************************************************** reply to a tcon ****************************************************************************/ int reply_tcon(char *inbuf,char *outbuf) { pstring service; pstring user; pstring password; pstring dev; int connection_num; int outsize = 0; uint16 vuid = SVAL(inbuf,smb_uid); int pwlen=0; *service = *user = *password = *dev = 0; parse_connect(smb_buf(inbuf)+1,service,user,password,&pwlen,dev); connection_num = make_connection(service,user,password,pwlen,dev,vuid); if (connection_num < 0) return(connection_error(inbuf,outbuf,connection_num)); outsize = set_message(outbuf,2,0,True); SSVAL(outbuf,smb_vwv0,max_recv); SSVAL(outbuf,smb_vwv1,connection_num); SSVAL(outbuf,smb_tid,connection_num); DEBUG(3,("%s tcon service=%s user=%s cnum=%d\n",timestring(),service,user,connection_num)); return(outsize); } /**************************************************************************** reply to a tcon and X ****************************************************************************/ int reply_tcon_and_X(char *inbuf,char *outbuf,int length,int bufsize) { pstring service; pstring user; pstring password; pstring devicename; int connection_num; uint16 vuid = SVAL(inbuf,smb_uid); int passlen = SVAL(inbuf,smb_vwv3); BOOL doencrypt = SMBENCRYPT(); *service = *user = *password = *devicename = 0; /* we might have to close an old one */ if ((SVAL(inbuf,smb_vwv2) & 0x1) != 0) close_cnum(SVAL(inbuf,smb_tid),vuid); if (passlen > MAX_PASS_LEN) { overflow_attack(passlen); } { char *path; char *p; memcpy(password,smb_buf(inbuf),passlen); password[passlen]=0; path = smb_buf(inbuf) + passlen; if (!doencrypt || passlen != 24) { if (strequal(password," ")) *password = 0; passlen = strlen(password); } fstrcpy(service,path+2); p = strchr(service,'\\'); if (!p) return(ERROR(ERRSRV,ERRinvnetname)); *p = 0; fstrcpy(service,p+1); p = strchr(service,'%'); if (p) { *p++ = 0; fstrcpy(user,p); } StrnCpy(devicename,path + strlen(path) + 1,6); DEBUG(4,("Got device type %s\n",devicename)); } connection_num = make_connection(service,user,password,passlen,devicename,vuid); if (connection_num < 0) return(connection_error(inbuf,outbuf,connection_num)); if (Protocol < PROTOCOL_NT1) { set_message(outbuf,2,strlen(devicename)+1,True); strcpy(smb_buf(outbuf),devicename); } else { char *fsname = "SAMBA"; char *p; set_message(outbuf,3,3,True); p = smb_buf(outbuf); strcpy(p,devicename); p = skip_string(p,1); /* device name */ strcpy(p,fsname); p = skip_string(p,1); /* filesystem type e.g NTFS */ set_message(outbuf,3,PTR_DIFF(p,smb_buf(outbuf)),False); SSVAL(outbuf, smb_vwv2, 0x0); /* optional support */ } DEBUG(3,("%s tconX service=%s user=%s cnum=%d\n",timestring(),service,user,connection_num)); /* set the incoming and outgoing tid to the just created one */ SSVAL(inbuf,smb_tid,connection_num); SSVAL(outbuf,smb_tid,connection_num); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to an unknown type ****************************************************************************/ int reply_unknown(char *inbuf,char *outbuf) { int cnum; int type; cnum = SVAL(inbuf,smb_tid); type = CVAL(inbuf,smb_com); DEBUG(0,("%s unknown command type (%s): cnum=%d type=%d (0x%X)\n", timestring(), smb_fn_name(type), cnum,type,type)); return(ERROR(ERRSRV,ERRunknownsmb)); } /**************************************************************************** reply to an ioctl ****************************************************************************/ int reply_ioctl(char *inbuf,char *outbuf) { DEBUG(3,("ignoring ioctl\n")); #if 0 /* we just say it succeeds and hope its all OK. some day it would be nice to interpret them individually */ return set_message(outbuf,1,0,True); #else return(ERROR(ERRSRV,ERRnosupport)); #endif } /**************************************************************************** reply to a session setup command ****************************************************************************/ int reply_sesssetup_and_X(char *inbuf,char *outbuf,int length,int bufsize) { uint16 sess_vuid; int gid; int uid; int smb_bufsize; int smb_mpxmax; int smb_vc_num; uint32 smb_sesskey; int smb_apasslen = 0; pstring smb_apasswd; int smb_ntpasslen = 0; pstring smb_ntpasswd; BOOL valid_nt_password = False; pstring user; BOOL guest=False; BOOL computer_id=False; static BOOL done_sesssetup = False; BOOL doencrypt = SMBENCRYPT(); *smb_apasswd = 0; smb_bufsize = SVAL(inbuf,smb_vwv2); smb_mpxmax = SVAL(inbuf,smb_vwv3); smb_vc_num = SVAL(inbuf,smb_vwv4); smb_sesskey = IVAL(inbuf,smb_vwv5); if (Protocol < PROTOCOL_NT1) { smb_apasslen = SVAL(inbuf,smb_vwv7); if (smb_apasslen > MAX_PASS_LEN) { overflow_attack(smb_apasslen); } memcpy(smb_apasswd,smb_buf(inbuf),smb_apasslen); pstrcpy(user,smb_buf(inbuf)+smb_apasslen); if (lp_security() != SEC_SERVER && !doencrypt) { smb_apasslen = strlen(smb_apasswd); } } else { uint16 passlen1 = SVAL(inbuf,smb_vwv7); uint16 passlen2 = SVAL(inbuf,smb_vwv8); uint32 client_caps = IVAL(inbuf,smb_vwv11); enum remote_arch_types ra_type = get_remote_arch(); char *p = smb_buf(inbuf); /* client_caps is used as final determination if client is NT or Win95. This is needed to return the correct error codes in some circumstances. */ if(ra_type == RA_WINNT || ra_type == RA_WIN95) { if(client_caps & (CAP_NT_SMBS | CAP_STATUS32)) set_remote_arch( RA_WINNT); else set_remote_arch( RA_WIN95); } if (passlen1 != 24 && passlen2 != 24) doencrypt = False; if (passlen1 > MAX_PASS_LEN) { overflow_attack(passlen1); } passlen1 = MIN(passlen1, MAX_PASS_LEN); passlen2 = MIN(passlen2, MAX_PASS_LEN); if(doencrypt) { /* Save the lanman2 password and the NT md4 password. */ smb_apasslen = passlen1; memcpy(smb_apasswd,p,smb_apasslen); smb_ntpasslen = passlen2; memcpy(smb_ntpasswd,p+passlen1,smb_ntpasslen); } else { /* both Win95 and WinNT stuff up the password lengths for non-encrypting systems. Uggh. if passlen1==24 its a win95 system, and its setting the password length incorrectly. Luckily it still works with the default code because Win95 will null terminate the password anyway if passlen1>0 and passlen2>0 then maybe its a NT box and its setting passlen2 to some random value which really stuffs things up. we need to fix that one. */ if (passlen1 > 0 && passlen2 > 0 && passlen2 != 24 && passlen2 != 1) { passlen2 = 0; } /* we use the first password that they gave */ smb_apasslen = passlen1; StrnCpy(smb_apasswd,p,smb_apasslen); /* trim the password */ smb_apasslen = strlen(smb_apasswd); /* wfwg sometimes uses a space instead of a null */ if (strequal(smb_apasswd," ")) { smb_apasslen = 0; *smb_apasswd = 0; } } p += passlen1 + passlen2; fstrcpy(user,p); p = skip_string(p,1); DEBUG(3,("Domain=[%s] NativeOS=[%s] NativeLanMan=[%s]\n", p,skip_string(p,1),skip_string(p,2))); } DEBUG(3,("sesssetupX:name=[%s]\n",user)); /* If name ends in $ then I think it's asking about whether a */ /* computer with that name (minus the $) has access. For now */ /* say yes to everything ending in $. */ if (user[strlen(user) - 1] == '$') { #ifdef NTDOMAIN struct smb_passwd *smb_pass; /* To check if machine account exists */ /* PAXX: Ack. We don't want to do this. The workstation trust account with a $ on the end should exist in the local password database or be mapped to something generic, but not modified. For NT domain support we must reject this used in certain circumstances with a code to indicate to the client that it is an invalid use of a workstation trust account. NTWKS needs this error to join a domain. This may be the source of future bugs if we cannot be sure whether to reject this or not. */ smb_pass = get_smbpwnam(user); if(smb_pass) { /* PAXX: This is the NO LOGON workstation trust account stuff */ DEBUG(4,("Rejecting workstation trust account %s",user)); SSVAL(outbuf, smb_flg2, 0xc003); /* PAXX: Someone please unhack this */ CVAL(outbuf, smb_reh) = 1; /* PAXX: Someone please unhack this */ return(ERROR(NT_STATUS_ALLOTTED_SPACE_EXCEEDED, 0xc000)); /* 0x99 NT error, 0xc00 */ } computer_id = True; #else /* not NTDOMAIN, leave this in. PAXX: Someone get rid of this */ user[strlen(user) - 1] = '\0'; #endif } /* If no username is sent use the guest account */ if (!*user) { strcpy(user,lp_guestaccount(-1)); /* If no user and no password then set guest flag. */ if( *smb_apasswd == 0) guest = True; } strlower(user); strcpy(sesssetup_user,user); reload_services(True); add_session_user(user); /* Check if the given username was the guest user with no password. We need to do this check after add_session_user() as that call can potentially change the username (via map_user). */ if(!guest && strequal(user,lp_guestaccount(-1)) && (*smb_apasswd == 0)) guest = True; if (!guest && !(lp_security() == SEC_SERVER && server_validate(inbuf)) && !check_hosts_equiv(user)) { /* now check if it's a valid username/password */ /* If an NT password was supplied try and validate with that first. This is superior as the passwords are mixed case 128 length unicode */ if(smb_ntpasslen) { if(!password_ok(user,smb_ntpasswd,smb_ntpasslen,NULL)) DEBUG(0,("NT Password did not match ! Defaulting to Lanman\n")); else valid_nt_password = True; } if (!valid_nt_password && !password_ok(user,smb_apasswd,smb_apasslen,NULL)) { if (!computer_id && lp_security() >= SEC_USER) { #if (GUEST_SESSSETUP == 0) return(ERROR(ERRSRV,ERRbadpw)); #endif #if (GUEST_SESSSETUP == 1) if (Get_Pwnam(user,True)) return(ERROR(ERRSRV,ERRbadpw)); #endif } if (*smb_apasswd || !Get_Pwnam(user,True)) strcpy(user,lp_guestaccount(-1)); DEBUG(3,("Registered username %s for guest access\n",user)); guest = True; } } if (!Get_Pwnam(user,True)) { DEBUG(3,("No such user %s - using guest account\n",user)); strcpy(user,lp_guestaccount(-1)); guest = True; } if (!strequal(user,lp_guestaccount(-1)) && lp_servicenumber(user) < 0) { int homes = lp_servicenumber(HOMES_NAME); char *home = get_home_dir(user); if (homes >= 0 && home) lp_add_home(user,homes,home); } /* it's ok - setup a reply */ if (Protocol < PROTOCOL_NT1) { set_message(outbuf,3,0,True); } else { char *p; set_message(outbuf,3,3,True); p = smb_buf(outbuf); strcpy(p,"Unix"); p = skip_string(p,1); strcpy(p,"Samba "); strcat(p,VERSION); p = skip_string(p,1); strcpy(p,myworkgroup); p = skip_string(p,1); set_message(outbuf,3,PTR_DIFF(p,smb_buf(outbuf)),False); /* perhaps grab OS version here?? */ } /* Set the correct uid in the outgoing and incoming packets We will use this on future requests to determine which user we should become. */ { struct passwd *pw = Get_Pwnam(user,False); if (!pw) { DEBUG(1,("Username %s is invalid on this system\n",user)); return(ERROR(ERRSRV,ERRbadpw)); } gid = pw->pw_gid; uid = pw->pw_uid; } if (guest && !computer_id) SSVAL(outbuf,smb_vwv2,1); /* register the name and uid as being validated, so further connections to a uid can get through without a password, on the same VC */ sess_vuid = register_vuid(uid,gid,user,guest); SSVAL(outbuf,smb_uid,sess_vuid); SSVAL(inbuf,smb_uid,sess_vuid); if (!done_sesssetup) max_send = MIN(max_send,smb_bufsize); DEBUG(6,("Client requested max send size of %d\n", max_send)); done_sesssetup = True; return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a chkpth ****************************************************************************/ int reply_chkpth(char *inbuf,char *outbuf) { int outsize = 0; int cnum,mode; pstring name; BOOL ok = False; BOOL bad_path = False; cnum = SVAL(inbuf,smb_tid); pstrcpy(name,smb_buf(inbuf) + 1); unix_convert(name,cnum,0,&bad_path); mode = SVAL(inbuf,smb_vwv0); if (check_name(name,cnum)) ok = directory_exist(name,NULL); if (!ok) { /* We special case this - as when a Windows machine is parsing a path is steps through the components one at a time - if a component fails it expects ERRbadpath, not ERRbadfile. */ if(errno == ENOENT) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } #if 0 /* Ugly - NT specific hack - maybe not needed ? (JRA) */ if((errno == ENOTDIR) && (Protocol >= PROTOCOL_NT1) && (get_remote_arch() == RA_WINNT)) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbaddirectory; } #endif return(UNIXERROR(ERRDOS,ERRbadpath)); } outsize = set_message(outbuf,0,0,True); DEBUG(3,("%s chkpth %s cnum=%d mode=%d\n",timestring(),name,cnum,mode)); return(outsize); } /**************************************************************************** reply to a getatr ****************************************************************************/ int reply_getatr(char *inbuf,char *outbuf) { pstring fname; int cnum; int outsize = 0; struct stat sbuf; BOOL ok = False; int mode=0; uint32 size=0; time_t mtime=0; BOOL bad_path = False; cnum = SVAL(inbuf,smb_tid); pstrcpy(fname,smb_buf(inbuf) + 1); unix_convert(fname,cnum,0,&bad_path); /* dos smetimes asks for a stat of "" - it returns a "hidden directory" under WfWg - weird! */ if (! (*fname)) { mode = aHIDDEN | aDIR; if (!CAN_WRITE(cnum)) mode |= aRONLY; size = 0; mtime = 0; ok = True; } else if (check_name(fname,cnum)) { if (sys_stat(fname,&sbuf) == 0) { mode = dos_mode(cnum,fname,&sbuf); size = sbuf.st_size; mtime = sbuf.st_mtime; if (mode & aDIR) size = 0; ok = True; } else DEBUG(3,("stat of %s failed (%s)\n",fname,strerror(errno))); } if (!ok) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRbadfile)); } outsize = set_message(outbuf,10,0,True); SSVAL(outbuf,smb_vwv0,mode); put_dos_date3(outbuf,smb_vwv1,mtime); SIVAL(outbuf,smb_vwv3,size); if (Protocol >= PROTOCOL_NT1) { char *p = strrchr(fname,'/'); uint16 flg2 = SVAL(outbuf,smb_flg2); if (!p) p = fname; if (!is_8_3(fname, True)) SSVAL(outbuf,smb_flg2,flg2 | 0x40); /* IS_LONG_NAME */ } DEBUG(3,("%s getatr name=%s mode=%d size=%d\n",timestring(),fname,mode,size)); return(outsize); } /**************************************************************************** reply to a setatr ****************************************************************************/ int reply_setatr(char *inbuf,char *outbuf) { pstring fname; int cnum; int outsize = 0; BOOL ok=False; int mode; time_t mtime; BOOL bad_path = False; cnum = SVAL(inbuf,smb_tid); pstrcpy(fname,smb_buf(inbuf) + 1); unix_convert(fname,cnum,0,&bad_path); mode = SVAL(inbuf,smb_vwv0); mtime = make_unix_date3(inbuf+smb_vwv1); if (directory_exist(fname,NULL)) mode |= aDIR; if (check_name(fname,cnum)) ok = (dos_chmod(cnum,fname,mode,NULL) == 0); if (ok) ok = set_filetime(fname,mtime); if (!ok) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,0,0,True); DEBUG(3,("%s setatr name=%s mode=%d\n",timestring(),fname,mode)); return(outsize); } /**************************************************************************** reply to a dskattr ****************************************************************************/ int reply_dskattr(char *inbuf,char *outbuf) { int cnum; int outsize = 0; int dfree,dsize,bsize; cnum = SVAL(inbuf,smb_tid); sys_disk_free(".",&bsize,&dfree,&dsize); outsize = set_message(outbuf,5,0,True); SSVAL(outbuf,smb_vwv0,dsize); SSVAL(outbuf,smb_vwv1,bsize/512); SSVAL(outbuf,smb_vwv2,512); SSVAL(outbuf,smb_vwv3,dfree); DEBUG(3,("%s dskattr cnum=%d dfree=%d\n",timestring(),cnum,dfree)); return(outsize); } /**************************************************************************** reply to a search Can be called from SMBsearch, SMBffirst or SMBfunique. ****************************************************************************/ int reply_search(char *inbuf,char *outbuf) { pstring mask; pstring directory; pstring fname; int size,mode; time_t date; int dirtype; int cnum; int outsize = 0; int numentries = 0; BOOL finished = False; int maxentries; int i; char *p; BOOL ok = False; int status_len; char *path; char status[21]; int dptr_num= -1; BOOL check_descend = False; BOOL expect_close = False; BOOL can_open = True; BOOL bad_path = False; *mask = *directory = *fname = 0; /* If we were called as SMBffirst then we must expect close. */ if(CVAL(inbuf,smb_com) == SMBffirst) expect_close = True; cnum = SVAL(inbuf,smb_tid); outsize = set_message(outbuf,1,3,True); maxentries = SVAL(inbuf,smb_vwv0); dirtype = SVAL(inbuf,smb_vwv1); path = smb_buf(inbuf) + 1; status_len = SVAL(smb_buf(inbuf),3 + strlen(path)); /* dirtype &= ~aDIR; */ DEBUG(5,("path=%s status_len=%d\n",path,status_len)); if (status_len == 0) { pstring dir2; pstrcpy(directory,smb_buf(inbuf)+1); pstrcpy(dir2,smb_buf(inbuf)+1); unix_convert(directory,cnum,0,&bad_path); unix_format(dir2); if (!check_name(directory,cnum)) can_open = False; p = strrchr(dir2,'/'); if (p == NULL) { strcpy(mask,dir2); *dir2 = 0; } else { *p = 0; pstrcpy(mask,p+1); } p = strrchr(directory,'/'); if (!p) *directory = 0; else *p = 0; if (strlen(directory) == 0) strcpy(directory,"./"); bzero(status,21); CVAL(status,0) = dirtype; } else { memcpy(status,smb_buf(inbuf) + 1 + strlen(path) + 4,21); memcpy(mask,status+1,11); mask[11] = 0; dirtype = CVAL(status,0) & 0x1F; Connections[cnum].dirptr = dptr_fetch(status+12,&dptr_num); if (!Connections[cnum].dirptr) goto SearchEmpty; string_set(&Connections[cnum].dirpath,dptr_path(dptr_num)); if (!case_sensitive) strnorm(mask); } /* turn strings of spaces into a . */ { trim_string(mask,NULL," "); if ((p = strrchr(mask,' '))) { fstring ext; fstrcpy(ext,p+1); *p = 0; trim_string(mask,NULL," "); strcat(mask,"."); strcat(mask,ext); } } { for (p=mask; *p; p++) { if (*p != '?' && *p != '*' && !isdoschar(*p)) { DEBUG(5,("Invalid char [%c] in search mask?\n",*p)); *p = '?'; } } } if (!strchr(mask,'.') && strlen(mask)>8) { fstring tmp; fstrcpy(tmp,&mask[8]); mask[8] = '.'; mask[9] = 0; strcat(mask,tmp); } DEBUG(5,("mask=%s directory=%s\n",mask,directory)); if (can_open) { p = smb_buf(outbuf) + 3; ok = True; if (status_len == 0) { dptr_num = dptr_create(cnum,directory,expect_close,SVAL(inbuf,smb_pid)); if (dptr_num < 0) { if(dptr_num == -2) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return (UNIXERROR(ERRDOS,ERRnofids)); } return(ERROR(ERRDOS,ERRnofids)); } } DEBUG(4,("dptr_num is %d\n",dptr_num)); if (ok) { if ((dirtype&0x1F) == aVOLID) { memcpy(p,status,21); make_dir_struct(p,"???????????",volume_label(SNUM(cnum)),0,aVOLID,0); dptr_fill(p+12,dptr_num); if (dptr_zero(p+12) && (status_len==0)) numentries = 1; else numentries = 0; p += DIR_STRUCT_SIZE; } else { DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",Connections[cnum].dirpath,lp_dontdescend(SNUM(cnum)))); if (in_list(Connections[cnum].dirpath, lp_dontdescend(SNUM(cnum)),True)) check_descend = True; for (i=numentries;(i= 0 && CVAL(inbuf,smb_com) == SMBfunique) dptr_close(dptr_num); SSVAL(outbuf,smb_vwv0,numentries); SSVAL(outbuf,smb_vwv1,3 + numentries * DIR_STRUCT_SIZE); CVAL(smb_buf(outbuf),0) = 5; SSVAL(smb_buf(outbuf),1,numentries*DIR_STRUCT_SIZE); if (Protocol >= PROTOCOL_NT1) { uint16 flg2 = SVAL(outbuf,smb_flg2); SSVAL(outbuf,smb_flg2,flg2 | 0x40); /* IS_LONG_NAME */ } outsize += DIR_STRUCT_SIZE*numentries; smb_setlen(outbuf,outsize - 4); if ((! *directory) && dptr_path(dptr_num)) sprintf(directory,"(%s)",dptr_path(dptr_num)); DEBUG(4,("%s %s mask=%s path=%s cnum=%d dtype=%d nument=%d of %d\n", timestring(), smb_fn_name(CVAL(inbuf,smb_com)), mask,directory,cnum,dirtype,numentries,maxentries)); return(outsize); } /**************************************************************************** reply to a fclose (stop directory search) ****************************************************************************/ int reply_fclose(char *inbuf,char *outbuf) { int cnum; int outsize = 0; int status_len; char *path; char status[21]; int dptr_num= -1; cnum = SVAL(inbuf,smb_tid); outsize = set_message(outbuf,1,0,True); path = smb_buf(inbuf) + 1; status_len = SVAL(smb_buf(inbuf),3 + strlen(path)); if (status_len == 0) return(ERROR(ERRSRV,ERRsrverror)); memcpy(status,smb_buf(inbuf) + 1 + strlen(path) + 4,21); if(dptr_fetch(status+12,&dptr_num)) { /* Close the dptr - we know it's gone */ dptr_close(dptr_num); } SSVAL(outbuf,smb_vwv0,0); DEBUG(3,("%s search close cnum=%d\n",timestring(),cnum)); return(outsize); } /**************************************************************************** reply to an open ****************************************************************************/ int reply_open(char *inbuf,char *outbuf) { pstring fname; int cnum; int fnum = -1; int outsize = 0; int fmode=0; int share_mode; int size = 0; time_t mtime=0; int unixmode; int rmode=0; struct stat sbuf; BOOL bad_path = False; files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); cnum = SVAL(inbuf,smb_tid); share_mode = SVAL(inbuf,smb_vwv0); pstrcpy(fname,smb_buf(inbuf)+1); unix_convert(fname,cnum,0,&bad_path); fnum = find_free_file(); if (fnum < 0) return(ERROR(ERRSRV,ERRnofids)); if (!check_name(fname,cnum)) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } unixmode = unix_mode(cnum,aARCH); open_file_shared(fnum,cnum,fname,share_mode,3,unixmode, oplock_request,&rmode,NULL); fsp = &Files[fnum]; if (!fsp->open) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } if (fstat(fsp->fd_ptr->fd,&sbuf) != 0) { close_file(fnum,False); return(ERROR(ERRDOS,ERRnoaccess)); } size = sbuf.st_size; fmode = dos_mode(cnum,fname,&sbuf); mtime = sbuf.st_mtime; if (fmode & aDIR) { DEBUG(3,("attempt to open a directory %s\n",fname)); close_file(fnum,False); return(ERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,7,0,True); SSVAL(outbuf,smb_vwv0,fnum); SSVAL(outbuf,smb_vwv1,fmode); put_dos_date3(outbuf,smb_vwv2,mtime); SIVAL(outbuf,smb_vwv4,size); SSVAL(outbuf,smb_vwv6,rmode); if (oplock_request && lp_fake_oplocks(SNUM(cnum))) { CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; } if(fsp->granted_oplock) CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; return(outsize); } /**************************************************************************** reply to an open and X ****************************************************************************/ int reply_open_and_X(char *inbuf,char *outbuf,int length,int bufsize) { pstring fname; int cnum = SVAL(inbuf,smb_tid); int fnum = -1; int smb_mode = SVAL(inbuf,smb_vwv3); int smb_attr = SVAL(inbuf,smb_vwv5); BOOL oplock_request = EXTENDED_OPLOCK_REQUEST(inbuf); #if 0 int open_flags = SVAL(inbuf,smb_vwv2); int smb_sattr = SVAL(inbuf,smb_vwv4); uint32 smb_time = make_unix_date3(inbuf+smb_vwv6); #endif int smb_ofun = SVAL(inbuf,smb_vwv8); int unixmode; int size=0,fmode=0,mtime=0,rmode=0; struct stat sbuf; int smb_action = 0; BOOL bad_path = False; files_struct *fsp; /* If it's an IPC, pass off the pipe handler. */ if (IS_IPC(cnum)) return reply_open_pipe_and_X(inbuf,outbuf,length,bufsize); /* XXXX we need to handle passed times, sattr and flags */ pstrcpy(fname,smb_buf(inbuf)); unix_convert(fname,cnum,0,&bad_path); fnum = find_free_file(); if (fnum < 0) return(ERROR(ERRSRV,ERRnofids)); if (!check_name(fname,cnum)) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } unixmode = unix_mode(cnum,smb_attr | aARCH); open_file_shared(fnum,cnum,fname,smb_mode,smb_ofun,unixmode, oplock_request, &rmode,&smb_action); fsp = &Files[fnum]; if (!fsp->open) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } if (fstat(fsp->fd_ptr->fd,&sbuf) != 0) { close_file(fnum,False); return(ERROR(ERRDOS,ERRnoaccess)); } size = sbuf.st_size; fmode = dos_mode(cnum,fname,&sbuf); mtime = sbuf.st_mtime; if (fmode & aDIR) { close_file(fnum,False); return(ERROR(ERRDOS,ERRnoaccess)); } if (oplock_request && lp_fake_oplocks(SNUM(cnum))) { smb_action |= EXTENDED_OPLOCK_GRANTED; CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; } if(fsp->granted_oplock) { smb_action |= EXTENDED_OPLOCK_GRANTED; CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; } set_message(outbuf,15,0,True); SSVAL(outbuf,smb_vwv2,fnum); SSVAL(outbuf,smb_vwv3,fmode); put_dos_date3(outbuf,smb_vwv4,mtime); SIVAL(outbuf,smb_vwv6,size); SSVAL(outbuf,smb_vwv8,rmode); SSVAL(outbuf,smb_vwv11,smb_action); chain_fnum = fnum; return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a SMBulogoffX ****************************************************************************/ int reply_ulogoffX(char *inbuf,char *outbuf,int length,int bufsize) { uint16 vuid = SVAL(inbuf,smb_uid); user_struct *vuser = get_valid_user_struct(vuid); if(vuser == 0) { DEBUG(3,("ulogoff, vuser id %d does not map to user.\n", vuid)); } /* in user level security we are supposed to close any files open by this user */ if ((vuser != 0) && (lp_security() != SEC_SHARE)) { int i; for (i=0;iuid && Files[i].open) { close_file(i,False); } } invalidate_vuid(vuid); set_message(outbuf,2,0,True); DEBUG(3,("%s ulogoffX vuid=%d\n",timestring(),vuid)); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a mknew or a create ****************************************************************************/ int reply_mknew(char *inbuf,char *outbuf) { pstring fname; int cnum,com; int fnum = -1; int outsize = 0; int createmode; mode_t unixmode; int ofun = 0; BOOL bad_path = False; files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); com = SVAL(inbuf,smb_com); cnum = SVAL(inbuf,smb_tid); createmode = SVAL(inbuf,smb_vwv0); pstrcpy(fname,smb_buf(inbuf)+1); unix_convert(fname,cnum,0,&bad_path); if (createmode & aVOLID) { DEBUG(0,("Attempt to create file (%s) with volid set - please report this\n",fname)); } unixmode = unix_mode(cnum,createmode); fnum = find_free_file(); if (fnum < 0) return(ERROR(ERRSRV,ERRnofids)); if (!check_name(fname,cnum)) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } if(com == SMBmknew) { /* We should fail if file exists. */ ofun = 0x10; } else { /* SMBcreate - Create if file doesn't exist, truncate if it does. */ ofun = 0x12; } /* Open file in dos compatibility share mode. */ open_file_shared(fnum,cnum,fname,(DENY_FCB<<4)|0xF, ofun, unixmode, oplock_request, NULL, NULL); fsp = &Files[fnum]; if (!fsp->open) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,fnum); if (oplock_request && lp_fake_oplocks(SNUM(cnum))) { CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; } if(fsp->granted_oplock) CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; DEBUG(2,("new file %s\n",fname)); DEBUG(3,("%s mknew %s fd=%d fnum=%d cnum=%d dmode=%d umode=%o\n",timestring(),fname,Files[fnum].fd_ptr->fd,fnum,cnum,createmode,unixmode)); return(outsize); } /**************************************************************************** reply to a create temporary file ****************************************************************************/ int reply_ctemp(char *inbuf,char *outbuf) { pstring fname; pstring fname2; int cnum; int fnum = -1; int outsize = 0; int createmode; mode_t unixmode; BOOL bad_path = False; files_struct *fsp; int oplock_request = CORE_OPLOCK_REQUEST(inbuf); cnum = SVAL(inbuf,smb_tid); createmode = SVAL(inbuf,smb_vwv0); pstrcpy(fname,smb_buf(inbuf)+1); strcat(fname,"/TMXXXXXX"); unix_convert(fname,cnum,0,&bad_path); unixmode = unix_mode(cnum,createmode); fnum = find_free_file(); if (fnum < 0) return(ERROR(ERRSRV,ERRnofids)); if (!check_name(fname,cnum)) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } strcpy(fname2,(char *)mktemp(fname)); /* Open file in dos compatibility share mode. */ /* We should fail if file exists. */ open_file_shared(fnum,cnum,fname2,(DENY_FCB<<4)|0xF, 0x10, unixmode, oplock_request, NULL, NULL); fsp = &Files[fnum]; if (!fsp->open) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,1,2 + strlen(fname2),True); SSVAL(outbuf,smb_vwv0,fnum); CVAL(smb_buf(outbuf),0) = 4; strcpy(smb_buf(outbuf) + 1,fname2); if (oplock_request && lp_fake_oplocks(SNUM(cnum))) { CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; } if(fsp->granted_oplock) CVAL(outbuf,smb_flg) |= CORE_OPLOCK_GRANTED; DEBUG(2,("created temp file %s\n",fname2)); DEBUG(3,("%s ctemp %s fd=%d fnum=%d cnum=%d dmode=%d umode=%o\n",timestring(),fname2,Files[fnum].fd_ptr->fd,fnum,cnum,createmode,unixmode)); return(outsize); } /******************************************************************* check if a user is allowed to delete a file ********************************************************************/ static BOOL can_delete(char *fname,int cnum,int dirtype) { struct stat sbuf; int fmode; if (!CAN_WRITE(cnum)) return(False); if (sys_lstat(fname,&sbuf) != 0) return(False); fmode = dos_mode(cnum,fname,&sbuf); if (fmode & aDIR) return(False); if (!lp_delete_readonly(SNUM(cnum))) { if (fmode & aRONLY) return(False); } if ((fmode & ~dirtype) & (aHIDDEN | aSYSTEM)) return(False); if (!check_file_sharing(cnum,fname)) return(False); return(True); } /**************************************************************************** reply to a unlink ****************************************************************************/ int reply_unlink(char *inbuf,char *outbuf) { int outsize = 0; pstring name; int cnum; int dirtype; pstring directory; pstring mask; char *p; int count=0; int error = ERRnoaccess; BOOL has_wild; BOOL exists=False; BOOL bad_path = False; *directory = *mask = 0; cnum = SVAL(inbuf,smb_tid); dirtype = SVAL(inbuf,smb_vwv0); pstrcpy(name,smb_buf(inbuf) + 1); DEBUG(3,("reply_unlink : %s\n",name)); unix_convert(name,cnum,0,&bad_path); p = strrchr(name,'/'); if (!p) { strcpy(directory,"./"); strcpy(mask,name); } else { *p = 0; strcpy(directory,name); strcpy(mask,p+1); } if (is_mangled(mask)) check_mangled_stack(mask); has_wild = strchr(mask,'*') || strchr(mask,'?'); if (!has_wild) { strcat(directory,"/"); strcat(directory,mask); if (can_delete(directory,cnum,dirtype) && !sys_unlink(directory)) count++; if (!count) exists = file_exist(directory,NULL); } else { void *dirptr = NULL; char *dname; if (check_name(directory,cnum)) dirptr = OpenDir(cnum, directory, True); /* XXXX the CIFS spec says that if bit0 of the flags2 field is set then the pattern matches against the long name, otherwise the short name We don't implement this yet XXXX */ if (dirptr) { error = ERRbadfile; if (strequal(mask,"????????.???")) strcpy(mask,"*"); while ((dname = ReadDirName(dirptr))) { pstring fname; pstrcpy(fname,dname); if(!mask_match(fname, mask, case_sensitive, False)) continue; error = ERRnoaccess; sprintf(fname,"%s/%s",directory,dname); if (!can_delete(fname,cnum,dirtype)) continue; if (!sys_unlink(fname)) count++; DEBUG(3,("reply_unlink : doing unlink on %s\n",fname)); } CloseDir(dirptr); } } if (count == 0) { if (exists) return(ERROR(ERRDOS,error)); else { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,error)); } } outsize = set_message(outbuf,0,0,True); return(outsize); } /**************************************************************************** reply to a readbraw (core+ protocol) ****************************************************************************/ int reply_readbraw(char *inbuf, char *outbuf) { int cnum,maxcount,mincount,fnum; int nread = 0; uint32 startpos; char *header = outbuf; int ret=0; int fd; char *fname; /* * Special check if an oplock break has been issued * and the readraw request croses on the wire, we must * return a zero length response here. */ if(global_oplock_break) { _smb_setlen(header,0); transfer_file(0,Client,0,header,4,0); DEBUG(5,("readbraw - oplock break finished\n")); return -1; } cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); startpos = IVAL(inbuf,smb_vwv1); maxcount = SVAL(inbuf,smb_vwv3); mincount = SVAL(inbuf,smb_vwv4); /* ensure we don't overrun the packet size */ maxcount = MIN(65535,maxcount); maxcount = MAX(mincount,maxcount); if (!FNUM_OK(fnum,cnum) || !Files[fnum].can_read) { DEBUG(3,("fnum %d not open in readbraw - cache prime?\n",fnum)); _smb_setlen(header,0); transfer_file(0,Client,0,header,4,0); return(-1); } else { fd = Files[fnum].fd_ptr->fd; fname = Files[fnum].name; } if (!is_locked(fnum,cnum,maxcount,startpos)) { int size = Files[fnum].size; int sizeneeded = startpos + maxcount; if (size < sizeneeded) { struct stat st; if (fstat(Files[fnum].fd_ptr->fd,&st) == 0) size = st.st_size; if (!Files[fnum].can_write) Files[fnum].size = size; } nread = MIN(maxcount,(int)(size - startpos)); } if (nread < mincount) nread = 0; DEBUG(3,("%s readbraw fnum=%d cnum=%d start=%d max=%d min=%d nread=%d\n", timestring(), fnum,cnum,startpos, maxcount,mincount,nread)); #if UNSAFE_READRAW { int predict=0; _smb_setlen(header,nread); if (!Files[fnum].can_write) predict = read_predict(fd,startpos,header+4,NULL,nread); if ((nread-predict) > 0) seek_file(fnum,startpos + predict); ret = transfer_file(fd,Client,nread-predict,header,4+predict, startpos+predict); } if (ret != nread+4) DEBUG(0,("ERROR: file read failure on %s at %d for %d bytes (%d)\n", fname,startpos,nread,ret)); #else ret = read_file(fnum,header+4,startpos,nread); if (ret < mincount) ret = 0; _smb_setlen(header,ret); transfer_file(0,Client,0,header,4+ret,0); #endif DEBUG(5,("readbraw finished\n")); return -1; } /**************************************************************************** reply to a lockread (core+ protocol) ****************************************************************************/ int reply_lockread(char *inbuf,char *outbuf) { int cnum,fnum; int nread = -1; char *data; int outsize = 0; uint32 startpos, numtoread; int eclass; uint32 ecode; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_READ(fnum); CHECK_ERROR(fnum); numtoread = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); outsize = set_message(outbuf,5,3,True); numtoread = MIN(BUFFER_SIZE-outsize,numtoread); data = smb_buf(outbuf) + 3; if(!do_lock( fnum, cnum, numtoread, startpos, &eclass, &ecode)) return (ERROR(eclass,ecode)); nread = read_file(fnum,data,startpos,numtoread); if (nread < 0) return(UNIXERROR(ERRDOS,ERRnoaccess)); outsize += nread; SSVAL(outbuf,smb_vwv0,nread); SSVAL(outbuf,smb_vwv5,nread+3); SSVAL(smb_buf(outbuf),1,nread); DEBUG(3,("%s lockread fnum=%d cnum=%d num=%d nread=%d\n",timestring(),fnum,cnum,numtoread,nread)); return(outsize); } /**************************************************************************** reply to a read ****************************************************************************/ int reply_read(char *inbuf,char *outbuf) { int cnum,numtoread,fnum; int nread = 0; char *data; uint32 startpos; int outsize = 0; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_READ(fnum); CHECK_ERROR(fnum); numtoread = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); outsize = set_message(outbuf,5,3,True); numtoread = MIN(BUFFER_SIZE-outsize,numtoread); data = smb_buf(outbuf) + 3; if (is_locked(fnum,cnum,numtoread,startpos)) return(ERROR(ERRDOS,ERRlock)); if (numtoread > 0) nread = read_file(fnum,data,startpos,numtoread); if (nread < 0) return(UNIXERROR(ERRDOS,ERRnoaccess)); outsize += nread; SSVAL(outbuf,smb_vwv0,nread); SSVAL(outbuf,smb_vwv5,nread+3); CVAL(smb_buf(outbuf),0) = 1; SSVAL(smb_buf(outbuf),1,nread); DEBUG(3,("%s read fnum=%d cnum=%d num=%d nread=%d\n",timestring(),fnum,cnum,numtoread,nread)); return(outsize); } /**************************************************************************** reply to a read and X ****************************************************************************/ int reply_read_and_X(char *inbuf,char *outbuf,int length,int bufsize) { int fnum = GETFNUM(inbuf,smb_vwv2); uint32 smb_offs = IVAL(inbuf,smb_vwv3); int smb_maxcnt = SVAL(inbuf,smb_vwv5); int smb_mincnt = SVAL(inbuf,smb_vwv6); int cnum; int nread = -1; char *data; BOOL ok = False; cnum = SVAL(inbuf,smb_tid); CHECK_FNUM(fnum,cnum); CHECK_READ(fnum); CHECK_ERROR(fnum); set_message(outbuf,12,0,True); data = smb_buf(outbuf); if (is_locked(fnum,cnum,smb_maxcnt,smb_offs)) return(ERROR(ERRDOS,ERRlock)); nread = read_file(fnum,data,smb_offs,smb_maxcnt); ok = True; if (nread < 0) return(UNIXERROR(ERRDOS,ERRnoaccess)); SSVAL(outbuf,smb_vwv5,nread); SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf)); SSVAL(smb_buf(outbuf),-2,nread); DEBUG(3,("%s readX fnum=%d cnum=%d min=%d max=%d nread=%d\n", timestring(),fnum,cnum, smb_mincnt,smb_maxcnt,nread)); chain_fnum = fnum; return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a writebraw (core+ or LANMAN1.0 protocol) ****************************************************************************/ int reply_writebraw(char *inbuf,char *outbuf) { int nwritten=0; int total_written=0; int numtowrite=0; int cnum,fnum; int outsize = 0; long startpos; char *data=NULL; BOOL write_through; int tcount; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); tcount = IVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv3); write_through = BITSETW(inbuf+smb_vwv7,0); /* We have to deal with slightly different formats depending on whether we are using the core+ or lanman1.0 protocol */ if(Protocol <= PROTOCOL_COREPLUS) { numtowrite = SVAL(smb_buf(inbuf),-2); data = smb_buf(inbuf); } else { numtowrite = SVAL(inbuf,smb_vwv10); data = smb_base(inbuf) + SVAL(inbuf, smb_vwv11); } /* force the error type */ CVAL(inbuf,smb_com) = SMBwritec; CVAL(outbuf,smb_com) = SMBwritec; if (is_locked(fnum,cnum,tcount,startpos)) return(ERROR(ERRDOS,ERRlock)); if (seek_file(fnum,startpos) != startpos) DEBUG(0,("couldn't seek to %d in writebraw\n",startpos)); if (numtowrite>0) nwritten = write_file(fnum,data,numtowrite); DEBUG(3,("%s writebraw1 fnum=%d cnum=%d start=%d num=%d wrote=%d sync=%d\n", timestring(),fnum,cnum,startpos,numtowrite,nwritten,write_through)); if (nwritten < numtowrite) return(UNIXERROR(ERRHRD,ERRdiskfull)); total_written = nwritten; /* Return a message to the redirector to tell it to send more bytes */ CVAL(outbuf,smb_com) = SMBwritebraw; SSVALS(outbuf,smb_vwv0,-1); outsize = set_message(outbuf,Protocol>PROTOCOL_COREPLUS?1:0,0,True); send_smb(Client,outbuf); /* Now read the raw data into the buffer and write it */ if (read_smb_length(Client,inbuf,SMB_SECONDARY_WAIT) == -1) { exit_server("secondary writebraw failed"); } /* Even though this is not an smb message, smb_len returns the generic length of an smb message */ numtowrite = smb_len(inbuf); if (tcount > nwritten+numtowrite) { DEBUG(3,("Client overestimated the write %d %d %d\n", tcount,nwritten,numtowrite)); } nwritten = transfer_file(Client,Files[fnum].fd_ptr->fd,numtowrite,NULL,0, startpos+nwritten); total_written += nwritten; /* Set up outbuf to return the correct return */ outsize = set_message(outbuf,1,0,True); CVAL(outbuf,smb_com) = SMBwritec; SSVAL(outbuf,smb_vwv0,total_written); if (nwritten < numtowrite) { CVAL(outbuf,smb_rcls) = ERRHRD; SSVAL(outbuf,smb_err,ERRdiskfull); } if (lp_syncalways(SNUM(cnum)) || write_through) sync_file(fnum); DEBUG(3,("%s writebraw2 fnum=%d cnum=%d start=%d num=%d wrote=%d\n", timestring(),fnum,cnum,startpos,numtowrite,total_written)); /* we won't return a status if write through is not selected - this follows what WfWg does */ if (!write_through && total_written==tcount) return(-1); return(outsize); } /**************************************************************************** reply to a writeunlock (core+) ****************************************************************************/ int reply_writeunlock(char *inbuf,char *outbuf) { int cnum,fnum; int nwritten = -1; int outsize = 0; char *data; uint32 numtowrite,startpos; int eclass; uint32 ecode; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); data = smb_buf(inbuf) + 3; if (is_locked(fnum,cnum,numtowrite,startpos)) return(ERROR(ERRDOS,ERRlock)); seek_file(fnum,startpos); /* The special X/Open SMB protocol handling of zero length writes is *NOT* done for this call */ if(numtowrite == 0) nwritten = 0; else nwritten = write_file(fnum,data,numtowrite); if (lp_syncalways(SNUM(cnum))) sync_file(fnum); if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) return(UNIXERROR(ERRDOS,ERRnoaccess)); if(!do_unlock(fnum, cnum, numtowrite, startpos, &eclass, &ecode)) return(ERROR(eclass,ecode)); outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); DEBUG(3,("%s writeunlock fnum=%d cnum=%d num=%d wrote=%d\n", timestring(),fnum,cnum,numtowrite,nwritten)); return(outsize); } /**************************************************************************** reply to a write ****************************************************************************/ int reply_write(char *inbuf,char *outbuf,int dum1,int dum2) { int cnum,numtowrite,fnum; int nwritten = -1; int outsize = 0; int startpos; char *data; dum1 = dum2 = 0; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); data = smb_buf(inbuf) + 3; if (is_locked(fnum,cnum,numtowrite,startpos)) return(ERROR(ERRDOS,ERRlock)); seek_file(fnum,startpos); /* X/Open SMB protocol says that if smb_vwv1 is zero then the file size should be extended or truncated to the size given in smb_vwv[2-3] */ if(numtowrite == 0) nwritten = set_filelen(Files[fnum].fd_ptr->fd, startpos); else nwritten = write_file(fnum,data,numtowrite); if (lp_syncalways(SNUM(cnum))) sync_file(fnum); if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) return(UNIXERROR(ERRDOS,ERRnoaccess)); outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); if (nwritten < numtowrite) { CVAL(outbuf,smb_rcls) = ERRHRD; SSVAL(outbuf,smb_err,ERRdiskfull); } DEBUG(3,("%s write fnum=%d cnum=%d num=%d wrote=%d\n",timestring(),fnum,cnum,numtowrite,nwritten)); return(outsize); } /**************************************************************************** reply to a write and X ****************************************************************************/ int reply_write_and_X(char *inbuf,char *outbuf,int length,int bufsize) { int fnum = GETFNUM(inbuf,smb_vwv2); uint32 smb_offs = IVAL(inbuf,smb_vwv3); int smb_dsize = SVAL(inbuf,smb_vwv10); int smb_doff = SVAL(inbuf,smb_vwv11); BOOL write_through = BITSETW(inbuf+smb_vwv7,0); int cnum; int nwritten = -1; char *data; cnum = SVAL(inbuf,smb_tid); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); data = smb_base(inbuf) + smb_doff; if (is_locked(fnum,cnum,smb_dsize,smb_offs)) return(ERROR(ERRDOS,ERRlock)); seek_file(fnum,smb_offs); /* X/Open SMB protocol says that, unlike SMBwrite if the length is zero then NO truncation is done, just a write of zero. To truncate a file, use SMBwrite. */ if(smb_dsize == 0) nwritten = 0; else nwritten = write_file(fnum,data,smb_dsize); if(((nwritten == 0) && (smb_dsize != 0))||(nwritten < 0)) return(UNIXERROR(ERRDOS,ERRnoaccess)); set_message(outbuf,6,0,True); SSVAL(outbuf,smb_vwv2,nwritten); if (nwritten < smb_dsize) { CVAL(outbuf,smb_rcls) = ERRHRD; SSVAL(outbuf,smb_err,ERRdiskfull); } DEBUG(3,("%s writeX fnum=%d cnum=%d num=%d wrote=%d\n",timestring(),fnum,cnum,smb_dsize,nwritten)); chain_fnum = fnum; if (lp_syncalways(SNUM(cnum)) || write_through) sync_file(fnum); return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a lseek ****************************************************************************/ int reply_lseek(char *inbuf,char *outbuf) { int cnum,fnum; uint32 startpos; int32 res= -1; int mode,umode; int outsize = 0; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); mode = SVAL(inbuf,smb_vwv1) & 3; startpos = IVAL(inbuf,smb_vwv2); switch (mode & 3) { case 0: umode = SEEK_SET; break; case 1: umode = SEEK_CUR; break; case 2: umode = SEEK_END; break; default: umode = SEEK_SET; break; } res = lseek(Files[fnum].fd_ptr->fd,startpos,umode); Files[fnum].pos = res; outsize = set_message(outbuf,2,0,True); SIVALS(outbuf,smb_vwv0,res); DEBUG(3,("%s lseek fnum=%d cnum=%d ofs=%d mode=%d\n",timestring(),fnum,cnum,startpos,mode)); return(outsize); } /**************************************************************************** reply to a flush ****************************************************************************/ int reply_flush(char *inbuf,char *outbuf) { int cnum, fnum; int outsize = set_message(outbuf,0,0,True); cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); if (fnum != 0xFFFF) { CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); } if (fnum == 0xFFFF) { int i; for (i=0;iwr_errclass; err = Files[fnum].wbmpx_ptr->wr_error; } mtime = make_unix_date3(inbuf+smb_vwv1); /* try and set the date */ set_filetime(Files[fnum].name,mtime); close_file(fnum,True); /* We have a cached error */ if(eclass || err) return(ERROR(eclass,err)); DEBUG(3,("%s close fd=%d fnum=%d cnum=%d (numopen=%d)\n", timestring(),Files[fnum].fd_ptr->fd,fnum,cnum, Connections[cnum].num_files_open)); return(outsize); } /**************************************************************************** reply to a writeclose (Core+ protocol) ****************************************************************************/ int reply_writeclose(char *inbuf,char *outbuf) { int cnum,numtowrite,fnum; int nwritten = -1; int outsize = 0; int startpos; char *data; time_t mtime; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); numtowrite = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); mtime = make_unix_date3(inbuf+smb_vwv4); data = smb_buf(inbuf) + 1; if (is_locked(fnum,cnum,numtowrite,startpos)) return(ERROR(ERRDOS,ERRlock)); seek_file(fnum,startpos); nwritten = write_file(fnum,data,numtowrite); set_filetime(Files[fnum].name,mtime); close_file(fnum,True); DEBUG(3,("%s writeclose fnum=%d cnum=%d num=%d wrote=%d (numopen=%d)\n", timestring(),fnum,cnum,numtowrite,nwritten, Connections[cnum].num_files_open)); if (nwritten <= 0) return(UNIXERROR(ERRDOS,ERRnoaccess)); outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,nwritten); return(outsize); } /**************************************************************************** reply to a lock ****************************************************************************/ int reply_lock(char *inbuf,char *outbuf) { int fnum,cnum; int outsize = set_message(outbuf,0,0,True); uint32 count,offset; int eclass; uint32 ecode; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); count = IVAL(inbuf,smb_vwv1); offset = IVAL(inbuf,smb_vwv3); DEBUG(3,("%s lock fd=%d fnum=%d cnum=%d ofs=%d cnt=%d\n",timestring(),Files[fnum].fd_ptr->fd,fnum,cnum,offset,count)); if(!do_lock( fnum, cnum, count, offset, &eclass, &ecode)) return (ERROR(eclass,ecode)); return(outsize); } /**************************************************************************** reply to a unlock ****************************************************************************/ int reply_unlock(char *inbuf,char *outbuf) { int fnum,cnum; int outsize = set_message(outbuf,0,0,True); uint32 count,offset; int eclass; uint32 ecode; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); count = IVAL(inbuf,smb_vwv1); offset = IVAL(inbuf,smb_vwv3); if(!do_unlock(fnum, cnum, count, offset, &eclass, &ecode)) return (ERROR(eclass,ecode)); DEBUG(3,("%s unlock fd=%d fnum=%d cnum=%d ofs=%d cnt=%d\n",timestring(),Files[fnum].fd_ptr->fd,fnum,cnum,offset,count)); return(outsize); } /**************************************************************************** reply to a tdis ****************************************************************************/ int reply_tdis(char *inbuf,char *outbuf) { int cnum; int outsize = set_message(outbuf,0,0,True); uint16 vuid; cnum = SVAL(inbuf,smb_tid); vuid = SVAL(inbuf,smb_uid); if (!OPEN_CNUM(cnum)) { DEBUG(4,("Invalid cnum in tdis (%d)\n",cnum)); return(ERROR(ERRSRV,ERRinvnid)); } Connections[cnum].used = False; close_cnum(cnum,vuid); DEBUG(3,("%s tdis cnum=%d\n",timestring(),cnum)); return outsize; } /**************************************************************************** reply to a echo ****************************************************************************/ int reply_echo(char *inbuf,char *outbuf) { int cnum; int smb_reverb = SVAL(inbuf,smb_vwv0); int seq_num; int data_len = smb_buflen(inbuf); int outsize = set_message(outbuf,1,data_len,True); cnum = SVAL(inbuf,smb_tid); /* According to the latest CIFS spec we shouldn't care what the TID is. */ #if 0 if (cnum != 0xFFFF && !OPEN_CNUM(cnum)) { DEBUG(4,("Invalid cnum in echo (%d)\n",cnum)); return(ERROR(ERRSRV,ERRinvnid)); } #endif /* copy any incoming data back out */ if (data_len > 0) memcpy(smb_buf(outbuf),smb_buf(inbuf),data_len); if (smb_reverb > 100) { DEBUG(0,("large reverb (%d)?? Setting to 100\n",smb_reverb)); smb_reverb = 100; } for (seq_num =1 ; seq_num <= smb_reverb ; seq_num++) { SSVAL(outbuf,smb_vwv0,seq_num); smb_setlen(outbuf,outsize - 4); send_smb(Client,outbuf); } DEBUG(3,("%s echo %d times cnum=%d\n",timestring(),smb_reverb,cnum)); return -1; } /**************************************************************************** reply to a printopen ****************************************************************************/ int reply_printopen(char *inbuf,char *outbuf) { pstring fname; pstring fname2; int cnum; int fnum = -1; int outsize = 0; *fname = *fname2 = 0; cnum = SVAL(inbuf,smb_tid); if (!CAN_PRINT(cnum)) return(ERROR(ERRDOS,ERRnoaccess)); { pstring s; char *p; pstrcpy(s,smb_buf(inbuf)+1); p = s; while (*p) { if (!(isalnum(*p) || strchr("._-",*p))) *p = 'X'; p++; } if (strlen(s) > 10) s[10] = 0; sprintf(fname,"%s.XXXXXX",s); } fnum = find_free_file(); if (fnum < 0) return(ERROR(ERRSRV,ERRnofids)); strcpy(fname2,(char *)mktemp(fname)); if (!check_name(fname2,cnum)) return(ERROR(ERRDOS,ERRnoaccess)); /* Open for exclusive use, write only. */ open_file_shared(fnum,cnum,fname2,(DENY_ALL<<4)|1, 0x12, unix_mode(cnum,0), 0, NULL, NULL); if (!Files[fnum].open) return(UNIXERROR(ERRDOS,ERRnoaccess)); /* force it to be a print file */ Files[fnum].print_file = True; outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,fnum); DEBUG(3,("%s openprint %s fd=%d fnum=%d cnum=%d\n",timestring(),fname2,Files[fnum].fd_ptr->fd,fnum,cnum)); return(outsize); } /**************************************************************************** reply to a printclose ****************************************************************************/ int reply_printclose(char *inbuf,char *outbuf) { int fnum,cnum; int outsize = set_message(outbuf,0,0,True); cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); if (!CAN_PRINT(cnum)) return(ERROR(ERRDOS,ERRnoaccess)); close_file(fnum,True); DEBUG(3,("%s printclose fd=%d fnum=%d cnum=%d\n",timestring(),Files[fnum].fd_ptr->fd,fnum,cnum)); return(outsize); } /**************************************************************************** reply to a printqueue ****************************************************************************/ int reply_printqueue(char *inbuf,char *outbuf) { int cnum; int outsize = set_message(outbuf,2,3,True); int max_count = SVAL(inbuf,smb_vwv0); int start_index = SVAL(inbuf,smb_vwv1); uint16 vuid; cnum = SVAL(inbuf,smb_tid); vuid = SVAL(inbuf,smb_uid); /* allow checking the queue for anyone */ #if 0 if (!CAN_PRINT(cnum)) return(ERROR(ERRDOS,ERRnoaccess)); #endif SSVAL(outbuf,smb_vwv0,0); SSVAL(outbuf,smb_vwv1,0); CVAL(smb_buf(outbuf),0) = 1; SSVAL(smb_buf(outbuf),1,0); DEBUG(3,("%s printqueue cnum=%d start_index=%d max_count=%d\n", timestring(),cnum,start_index,max_count)); if (!OPEN_CNUM(cnum) || !Connections[cnum].printer) { int i; cnum = -1; for (i=0;i0?start_index:start_index+max_count+1); int i; if (first >= count) num_to_get = 0; else num_to_get = MIN(num_to_get,count-first); for (i=first;i 0) { outsize = set_message(outbuf,2,28*count+3,False); SSVAL(outbuf,smb_vwv0,count); SSVAL(outbuf,smb_vwv1,(max_count>0?first+count:first-1)); CVAL(smb_buf(outbuf),0) = 1; SSVAL(smb_buf(outbuf),1,28*count); } if (queue) free(queue); DEBUG(3,("%d entries returned in queue\n",count)); } return(outsize); } /**************************************************************************** reply to a printwrite ****************************************************************************/ int reply_printwrite(char *inbuf,char *outbuf) { int cnum,numtowrite,fnum; int outsize = set_message(outbuf,0,0,True); char *data; cnum = SVAL(inbuf,smb_tid); if (!CAN_PRINT(cnum)) return(ERROR(ERRDOS,ERRnoaccess)); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); numtowrite = SVAL(smb_buf(inbuf),1); data = smb_buf(inbuf) + 3; if (write_file(fnum,data,numtowrite) != numtowrite) return(UNIXERROR(ERRDOS,ERRnoaccess)); DEBUG(3,("%s printwrite fnum=%d cnum=%d num=%d\n",timestring(),fnum,cnum,numtowrite)); return(outsize); } /**************************************************************************** reply to a mkdir ****************************************************************************/ int reply_mkdir(char *inbuf,char *outbuf) { pstring directory; int cnum; int outsize,ret= -1; BOOL bad_path = False; pstrcpy(directory,smb_buf(inbuf) + 1); cnum = SVAL(inbuf,smb_tid); unix_convert(directory,cnum,0,&bad_path); if (check_name(directory,cnum)) ret = sys_mkdir(directory,unix_mode(cnum,aDIR)); if (ret < 0) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRnoaccess)); } outsize = set_message(outbuf,0,0,True); DEBUG(3,("%s mkdir %s cnum=%d ret=%d\n",timestring(),directory,cnum,ret)); return(outsize); } /**************************************************************************** Static function used by reply_rmdir to delete an entire directory tree recursively. ****************************************************************************/ static BOOL recursive_rmdir(char *directory) { char *dname = NULL; BOOL ret = False; void *dirptr = OpenDir(-1, directory, False); if(dirptr == NULL) return True; while((dname = ReadDirName(dirptr))) { pstring fullname; struct stat st; if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; /* Construct the full name. */ if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) { errno = ENOMEM; ret = True; break; } strcpy(fullname, directory); strcat(fullname, "/"); strcat(fullname, dname); if(sys_lstat(fullname, &st) != 0) { ret = True; break; } if(st.st_mode & S_IFDIR) { if(recursive_rmdir(fullname)!=0) { ret = True; break; } if(sys_rmdir(fullname) != 0) { ret = True; break; } } else if(sys_unlink(fullname) != 0) { ret = True; break; } } CloseDir(dirptr); return ret; } /**************************************************************************** reply to a rmdir ****************************************************************************/ int reply_rmdir(char *inbuf,char *outbuf) { pstring directory; int cnum; int outsize = 0; BOOL ok = False; BOOL bad_path = False; cnum = SVAL(inbuf,smb_tid); pstrcpy(directory,smb_buf(inbuf) + 1); unix_convert(directory,cnum,0,&bad_path); if (check_name(directory,cnum)) { dptr_closepath(directory,SVAL(inbuf,smb_pid)); ok = (sys_rmdir(directory) == 0); if(!ok && (errno == ENOTEMPTY) && lp_veto_files(SNUM(cnum))) { /* Check to see if the only thing in this directory are vetoed files/directories. If so then delete them and retry. If we fail to delete any of them (and we *don't* do a recursive delete) then fail the rmdir. */ BOOL all_veto_files = True; char *dname; void *dirptr = OpenDir(cnum, directory, False); if(dirptr != NULL) { int dirpos = TellDir(dirptr); while ((dname = ReadDirName(dirptr))) { if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; if(!IS_VETO_PATH(cnum, dname)) { all_veto_files = False; break; } } if(all_veto_files) { SeekDir(dirptr,dirpos); while ((dname = ReadDirName(dirptr))) { pstring fullname; struct stat st; if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) continue; /* Construct the full name. */ if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) { errno = ENOMEM; break; } pstrcpy(fullname, directory); strcat(fullname, "/"); strcat(fullname, dname); if(sys_lstat(fullname, &st) != 0) break; if(st.st_mode & S_IFDIR) { if(lp_recursive_veto_delete(SNUM(cnum))) { if(recursive_rmdir(fullname) != 0) break; } if(sys_rmdir(fullname) != 0) break; } else if(sys_unlink(fullname) != 0) break; } CloseDir(dirptr); /* Retry the rmdir */ ok = (sys_rmdir(directory) == 0); } else CloseDir(dirptr); } else errno = ENOTEMPTY; } if (!ok) DEBUG(3,("couldn't remove directory %s : %s\n", directory,strerror(errno))); } if (!ok) { if((errno == ENOENT) && bad_path) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,ERRbadpath)); } outsize = set_message(outbuf,0,0,True); DEBUG(3,("%s rmdir %s\n",timestring(),directory)); return(outsize); } /******************************************************************* resolve wildcards in a filename rename ********************************************************************/ static BOOL resolve_wildcards(char *name1,char *name2) { fstring root1,root2; fstring ext1,ext2; char *p,*p2; name1 = strrchr(name1,'/'); name2 = strrchr(name2,'/'); if (!name1 || !name2) return(False); fstrcpy(root1,name1); fstrcpy(root2,name2); p = strrchr(root1,'.'); if (p) { *p = 0; fstrcpy(ext1,p+1); } else { fstrcpy(ext1,""); } p = strrchr(root2,'.'); if (p) { *p = 0; fstrcpy(ext2,p+1); } else { fstrcpy(ext2,""); } p = root1; p2 = root2; while (*p2) { if (*p2 == '?') { *p2 = *p; p2++; } else { p2++; } if (*p) p++; } p = ext1; p2 = ext2; while (*p2) { if (*p2 == '?') { *p2 = *p; p2++; } else { p2++; } if (*p) p++; } strcpy(name2,root2); if (ext2[0]) { strcat(name2,"."); strcat(name2,ext2); } return(True); } /******************************************************************* check if a user is allowed to rename a file ********************************************************************/ static BOOL can_rename(char *fname,int cnum) { struct stat sbuf; if (!CAN_WRITE(cnum)) return(False); if (sys_lstat(fname,&sbuf) != 0) return(False); if (!check_file_sharing(cnum,fname)) return(False); return(True); } /**************************************************************************** reply to a mv ****************************************************************************/ int reply_mv(char *inbuf,char *outbuf) { int outsize = 0; pstring name; int cnum; pstring directory; pstring mask,newname; pstring newname_last_component; char *p; int count=0; int error = ERRnoaccess; BOOL has_wild; BOOL exists=False; BOOL bad_path1 = False; BOOL bad_path2 = False; *directory = *mask = 0; cnum = SVAL(inbuf,smb_tid); pstrcpy(name,smb_buf(inbuf) + 1); pstrcpy(newname,smb_buf(inbuf) + 3 + strlen(name)); DEBUG(3,("reply_mv : %s -> %s\n",name,newname)); unix_convert(name,cnum,0,&bad_path1); unix_convert(newname,cnum,newname_last_component,&bad_path2); /* * Split the old name into directory and last component * strings. Note that unix_convert may have stripped off a * leading ./ from both name and newname if the rename is * at the root of the share. We need to make sure either both * name and newname contain a / character or neither of them do * as this is checked in resolve_wildcards(). */ p = strrchr(name,'/'); if (!p) { strcpy(directory,"."); strcpy(mask,name); } else { *p = 0; strcpy(directory,name); strcpy(mask,p+1); *p = '/'; /* Replace needed for exceptional test below. */ } if (is_mangled(mask)) check_mangled_stack(mask); has_wild = strchr(mask,'*') || strchr(mask,'?'); if (!has_wild) { BOOL is_short_name = is_8_3(name, True); /* Add a terminating '/' to the directory name. */ strcat(directory,"/"); strcat(directory,mask); /* Ensure newname contains a '/' also */ if(strrchr(newname,'/') == 0) { pstring tmpstr; strcpy(tmpstr, "./"); strcat(tmpstr, newname); strcpy(newname, tmpstr); } DEBUG(3,("reply_mv : case_sensitive = %d, case_preserve = %d, short case preserve = %d, directory = %s, newname = %s, newname_last_component = %s, is_8_3 = %d\n", case_sensitive, case_preserve, short_case_preserve, directory, newname, newname_last_component, is_short_name)); /* * Check for special case with case preserving and not * case sensitive, if directory and newname are identical, * and the old last component differs from the original * last component only by case, then we should allow * the rename (user is trying to change the case of the * filename). */ if((case_sensitive == False) && ( ((case_preserve == True) && (is_short_name == False)) || ((short_case_preserve == True) && (is_short_name == True))) && strcsequal(directory, newname)) { pstring newname_modified_last_component; /* * Get the last component of the modified name. * Note that we guarantee that newname contains a '/' * character above. */ p = strrchr(newname,'/'); strcpy(newname_modified_last_component,p+1); if(strcsequal(newname_modified_last_component, newname_last_component) == False) { /* * Replace the modified last component with * the original. */ strcpy(p+1, newname_last_component); } } if (resolve_wildcards(directory,newname) && can_rename(directory,cnum) && !file_exist(newname,NULL) && !sys_rename(directory,newname)) count++; DEBUG(3,("reply_mv : %s doing rename on %s -> %s\n",(count != 0) ? "succeeded" : "failed", directory,newname)); if (!count) exists = file_exist(directory,NULL); if (!count && exists && file_exist(newname,NULL)) { exists = True; error = 183; } } else { void *dirptr = NULL; char *dname; pstring destname; if (check_name(directory,cnum)) dirptr = OpenDir(cnum, directory, True); if (dirptr) { error = ERRbadfile; if (strequal(mask,"????????.???")) strcpy(mask,"*"); while ((dname = ReadDirName(dirptr))) { pstring fname; pstrcpy(fname,dname); if(!mask_match(fname, mask, case_sensitive, False)) continue; error = ERRnoaccess; sprintf(fname,"%s/%s",directory,dname); if (!can_rename(fname,cnum)) continue; pstrcpy(destname,newname); if (!resolve_wildcards(fname,destname)) continue; if (file_exist(destname,NULL)) { error = 183; continue; } if (!sys_rename(fname,destname)) count++; DEBUG(3,("reply_mv : doing rename on %s -> %s\n",fname,destname)); } CloseDir(dirptr); } } if (count == 0) { if (exists) return(ERROR(ERRDOS,error)); else { if((errno == ENOENT) && (bad_path1 || bad_path2)) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,error)); } } outsize = set_message(outbuf,0,0,True); return(outsize); } /******************************************************************* copy a file as part of a reply_copy ******************************************************************/ static BOOL copy_file(char *src,char *dest1,int cnum,int ofun, int count,BOOL target_is_directory) { int Access,action; struct stat st; int ret=0; int fnum1,fnum2; pstring dest; pstrcpy(dest,dest1); if (target_is_directory) { char *p = strrchr(src,'/'); if (p) p++; else p = src; strcat(dest,"/"); strcat(dest,p); } if (!file_exist(src,&st)) return(False); fnum1 = find_free_file(); if (fnum1<0) return(False); open_file_shared(fnum1,cnum,src,(DENY_NONE<<4), 1,0,0,&Access,&action); if (!Files[fnum1].open) return(False); if (!target_is_directory && count) ofun = 1; fnum2 = find_free_file(); if (fnum2<0) { close_file(fnum1,False); return(False); } open_file_shared(fnum2,cnum,dest,(DENY_NONE<<4)|1, ofun,st.st_mode,0,&Access,&action); if (!Files[fnum2].open) { close_file(fnum1,False); return(False); } if ((ofun&3) == 1) { lseek(Files[fnum2].fd_ptr->fd,0,SEEK_END); } if (st.st_size) ret = transfer_file(Files[fnum1].fd_ptr->fd,Files[fnum2].fd_ptr->fd,st.st_size,NULL,0,0); close_file(fnum1,False); close_file(fnum2,False); return(ret == st.st_size); } /**************************************************************************** reply to a file copy. ****************************************************************************/ int reply_copy(char *inbuf,char *outbuf) { int outsize = 0; pstring name; int cnum; pstring directory; pstring mask,newname; char *p; int count=0; int error = ERRnoaccess; BOOL has_wild; BOOL exists=False; int tid2 = SVAL(inbuf,smb_vwv0); int ofun = SVAL(inbuf,smb_vwv1); int flags = SVAL(inbuf,smb_vwv2); BOOL target_is_directory=False; BOOL bad_path1 = False; BOOL bad_path2 = False; *directory = *mask = 0; cnum = SVAL(inbuf,smb_tid); pstrcpy(name,smb_buf(inbuf)); pstrcpy(newname,smb_buf(inbuf) + 1 + strlen(name)); DEBUG(3,("reply_copy : %s -> %s\n",name,newname)); if (tid2 != cnum) { /* can't currently handle inter share copies XXXX */ DEBUG(3,("Rejecting inter-share copy\n")); return(ERROR(ERRSRV,ERRinvdevice)); } unix_convert(name,cnum,0,&bad_path1); unix_convert(newname,cnum,0,&bad_path2); target_is_directory = directory_exist(newname,NULL); if ((flags&1) && target_is_directory) { return(ERROR(ERRDOS,ERRbadfile)); } if ((flags&2) && !target_is_directory) { return(ERROR(ERRDOS,ERRbadpath)); } if ((flags&(1<<5)) && directory_exist(name,NULL)) { /* wants a tree copy! XXXX */ DEBUG(3,("Rejecting tree copy\n")); return(ERROR(ERRSRV,ERRerror)); } p = strrchr(name,'/'); if (!p) { strcpy(directory,"./"); strcpy(mask,name); } else { *p = 0; strcpy(directory,name); strcpy(mask,p+1); } if (is_mangled(mask)) check_mangled_stack(mask); has_wild = strchr(mask,'*') || strchr(mask,'?'); if (!has_wild) { strcat(directory,"/"); strcat(directory,mask); if (resolve_wildcards(directory,newname) && copy_file(directory,newname,cnum,ofun, count,target_is_directory)) count++; if (!count) exists = file_exist(directory,NULL); } else { void *dirptr = NULL; char *dname; pstring destname; if (check_name(directory,cnum)) dirptr = OpenDir(cnum, directory, True); if (dirptr) { error = ERRbadfile; if (strequal(mask,"????????.???")) strcpy(mask,"*"); while ((dname = ReadDirName(dirptr))) { pstring fname; pstrcpy(fname,dname); if(!mask_match(fname, mask, case_sensitive, False)) continue; error = ERRnoaccess; sprintf(fname,"%s/%s",directory,dname); strcpy(destname,newname); if (resolve_wildcards(fname,destname) && copy_file(directory,newname,cnum,ofun, count,target_is_directory)) count++; DEBUG(3,("reply_copy : doing copy on %s -> %s\n",fname,destname)); } CloseDir(dirptr); } } if (count == 0) { if (exists) return(ERROR(ERRDOS,error)); else { if((errno == ENOENT) && (bad_path1 || bad_path2)) { unix_ERR_class = ERRDOS; unix_ERR_code = ERRbadpath; } return(UNIXERROR(ERRDOS,error)); } } outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,count); return(outsize); } /**************************************************************************** reply to a setdir ****************************************************************************/ int reply_setdir(char *inbuf,char *outbuf) { int cnum,snum; int outsize = 0; BOOL ok = False; pstring newdir; cnum = SVAL(inbuf,smb_tid); snum = Connections[cnum].service; if (!CAN_SETDIR(snum)) return(ERROR(ERRDOS,ERRnoaccess)); pstrcpy(newdir,smb_buf(inbuf) + 1); strlower(newdir); if (strlen(newdir) == 0) ok = True; else { ok = directory_exist(newdir,NULL); if (ok) string_set(&Connections[cnum].connectpath,newdir); } if (!ok) return(ERROR(ERRDOS,ERRbadpath)); outsize = set_message(outbuf,0,0,True); CVAL(outbuf,smb_reh) = CVAL(inbuf,smb_reh); DEBUG(3,("%s setdir %s cnum=%d\n",timestring(),newdir,cnum)); return(outsize); } /**************************************************************************** reply to a lockingX request ****************************************************************************/ int reply_lockingX(char *inbuf,char *outbuf,int length,int bufsize) { int fnum = GETFNUM(inbuf,smb_vwv2); unsigned char locktype = CVAL(inbuf,smb_vwv3); #if 0 unsigned char oplocklevel = CVAL(inbuf,smb_vwv3+1); #endif uint16 num_ulocks = SVAL(inbuf,smb_vwv6); uint16 num_locks = SVAL(inbuf,smb_vwv7); uint32 count, offset; int cnum; int i; char *data; uint32 ecode=0, dummy2; int eclass=0, dummy1; cnum = SVAL(inbuf,smb_tid); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); data = smb_buf(inbuf); /* Check if this is an oplock break on a file we have granted an oplock on. */ if((locktype == LOCKING_ANDX_OPLOCK_RELEASE) && (num_ulocks == 0) && (num_locks == 0) && (CVAL(inbuf,smb_vwv0) == 0xFF)) { int token; files_struct *fsp = &Files[fnum]; uint32 dev = fsp->fd_ptr->dev; uint32 inode = fsp->fd_ptr->inode; DEBUG(5,("reply_lockingX: oplock break reply from client for fnum = %d\n", fnum)); /* * Make sure we have granted an oplock on this file. */ if(!fsp->granted_oplock) { DEBUG(0,("reply_lockingX: Error : oplock break from client for fnum = %d and \ no oplock granted on this file.\n", fnum)); return ERROR(ERRDOS,ERRlock); } /* Remove the oplock flag from the sharemode. */ lock_share_entry(fsp->cnum, dev, inode, &token); if(remove_share_oplock( fnum, token)==False) { DEBUG(0,("reply_lockingX: failed to remove share oplock for fnum %d, \ dev = %x, inode = %x\n", fnum, dev, inode)); unlock_share_entry(fsp->cnum, dev, inode, token); return -1; } unlock_share_entry(fsp->cnum, dev, inode, token); /* Clear the granted flag and return. */ fsp->granted_oplock = False; return -1; } /* Data now points at the beginning of the list of smb_unlkrng structs */ for(i = 0; i < (int)num_ulocks; i++) { count = IVAL(data,SMB_LKLEN_OFFSET(i)); offset = IVAL(data,SMB_LKOFF_OFFSET(i)); if(!do_unlock(fnum,cnum,count,offset,&eclass, &ecode)) return ERROR(eclass,ecode); } /* Now do any requested locks */ data += 10*num_ulocks; /* Data now points at the beginning of the list of smb_lkrng structs */ for(i = 0; i < (int)num_locks; i++) { count = IVAL(data,SMB_LKLEN_OFFSET(i)); offset = IVAL(data,SMB_LKOFF_OFFSET(i)); if(!do_lock(fnum,cnum,count,offset, &eclass, &ecode)) break; } /* If any of the above locks failed, then we must unlock all of the previous locks (X/Open spec). */ if(i != num_locks && num_locks != 0) { for(; i >= 0; i--) { count = IVAL(data,SMB_LKLEN_OFFSET(i)); offset = IVAL(data,SMB_LKOFF_OFFSET(i)); do_unlock(fnum,cnum,count,offset,&dummy1,&dummy2); } return ERROR(eclass,ecode); } set_message(outbuf,2,0,True); DEBUG(3,("%s lockingX fnum=%d cnum=%d type=%d num_locks=%d num_ulocks=%d\n", timestring(),fnum,cnum,(unsigned int)locktype,num_locks,num_ulocks)); chain_fnum = fnum; return chain_reply(inbuf,outbuf,length,bufsize); } /**************************************************************************** reply to a SMBreadbmpx (read block multiplex) request ****************************************************************************/ int reply_readbmpx(char *inbuf,char *outbuf,int length,int bufsize) { int cnum,fnum; int nread = -1; int total_read; char *data; uint32 startpos; int outsize, mincount, maxcount; int max_per_packet; int tcount; int pad; /* this function doesn't seem to work - disable by default */ if (!lp_readbmpx()) return(ERROR(ERRSRV,ERRuseSTD)); outsize = set_message(outbuf,8,0,True); cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_READ(fnum); CHECK_ERROR(fnum); startpos = IVAL(inbuf,smb_vwv1); maxcount = SVAL(inbuf,smb_vwv3); mincount = SVAL(inbuf,smb_vwv4); data = smb_buf(outbuf); pad = ((long)data)%4; if (pad) pad = 4 - pad; data += pad; max_per_packet = bufsize-(outsize+pad); tcount = maxcount; total_read = 0; if (is_locked(fnum,cnum,maxcount,startpos)) return(ERROR(ERRDOS,ERRlock)); do { int N = MIN(max_per_packet,tcount-total_read); nread = read_file(fnum,data,startpos,N); if (nread <= 0) nread = 0; if (nread < N) tcount = total_read + nread; set_message(outbuf,8,nread,False); SIVAL(outbuf,smb_vwv0,startpos); SSVAL(outbuf,smb_vwv2,tcount); SSVAL(outbuf,smb_vwv6,nread); SSVAL(outbuf,smb_vwv7,smb_offset(data,outbuf)); send_smb(Client,outbuf); total_read += nread; startpos += nread; } while (total_read < tcount); return(-1); } /**************************************************************************** reply to a SMBwritebmpx (write block multiplex primary) request ****************************************************************************/ int reply_writebmpx(char *inbuf,char *outbuf) { int cnum,numtowrite,fnum; int nwritten = -1; int outsize = 0; uint32 startpos; int tcount, write_through, smb_doff; char *data; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); CHECK_ERROR(fnum); tcount = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv3); write_through = BITSETW(inbuf+smb_vwv7,0); numtowrite = SVAL(inbuf,smb_vwv10); smb_doff = SVAL(inbuf,smb_vwv11); data = smb_base(inbuf) + smb_doff; /* If this fails we need to send an SMBwriteC response, not an SMBwritebmpx - set this up now so we don't forget */ CVAL(outbuf,smb_com) = SMBwritec; if (is_locked(fnum,cnum,tcount,startpos)) return(ERROR(ERRDOS,ERRlock)); seek_file(fnum,startpos); nwritten = write_file(fnum,data,numtowrite); if(lp_syncalways(SNUM(cnum)) || write_through) sync_file(fnum); if(nwritten < numtowrite) return(UNIXERROR(ERRHRD,ERRdiskfull)); /* If the maximum to be written to this file is greater than what we just wrote then set up a secondary struct to be attached to this fd, we will use this to cache error messages etc. */ if(tcount > nwritten) { write_bmpx_struct *wbms; if(Files[fnum].wbmpx_ptr != NULL) wbms = Files[fnum].wbmpx_ptr; /* Use an existing struct */ else wbms = (write_bmpx_struct *)malloc(sizeof(write_bmpx_struct)); if(!wbms) { DEBUG(0,("Out of memory in reply_readmpx\n")); return(ERROR(ERRSRV,ERRnoresource)); } wbms->wr_mode = write_through; wbms->wr_discard = False; /* No errors yet */ wbms->wr_total_written = nwritten; wbms->wr_errclass = 0; wbms->wr_error = 0; Files[fnum].wbmpx_ptr = wbms; } /* We are returning successfully, set the message type back to SMBwritebmpx */ CVAL(outbuf,smb_com) = SMBwriteBmpx; outsize = set_message(outbuf,1,0,True); SSVALS(outbuf,smb_vwv0,-1); /* We don't support smb_remaining */ DEBUG(3,("%s writebmpx fnum=%d cnum=%d num=%d wrote=%d\n", timestring(),fnum,cnum,numtowrite,nwritten)); if (write_through && tcount==nwritten) { /* we need to send both a primary and a secondary response */ smb_setlen(outbuf,outsize - 4); send_smb(Client,outbuf); /* now the secondary */ outsize = set_message(outbuf,1,0,True); CVAL(outbuf,smb_com) = SMBwritec; SSVAL(outbuf,smb_vwv0,nwritten); } return(outsize); } /**************************************************************************** reply to a SMBwritebs (write block multiplex secondary) request ****************************************************************************/ int reply_writebs(char *inbuf,char *outbuf) { int cnum,numtowrite,fnum; int nwritten = -1; int outsize = 0; int32 startpos; int tcount, write_through, smb_doff; char *data; write_bmpx_struct *wbms; BOOL send_response = False; cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_WRITE(fnum); tcount = SVAL(inbuf,smb_vwv1); startpos = IVAL(inbuf,smb_vwv2); numtowrite = SVAL(inbuf,smb_vwv6); smb_doff = SVAL(inbuf,smb_vwv7); data = smb_base(inbuf) + smb_doff; /* We need to send an SMBwriteC response, not an SMBwritebs */ CVAL(outbuf,smb_com) = SMBwritec; /* This fd should have an auxiliary struct attached, check that it does */ wbms = Files[fnum].wbmpx_ptr; if(!wbms) return(-1); /* If write through is set we can return errors, else we must cache them */ write_through = wbms->wr_mode; /* Check for an earlier error */ if(wbms->wr_discard) return -1; /* Just discard the packet */ seek_file(fnum,startpos); nwritten = write_file(fnum,data,numtowrite); if(lp_syncalways(SNUM(cnum)) || write_through) sync_file(fnum); if (nwritten < numtowrite) { if(write_through) { /* We are returning an error - we can delete the aux struct */ if (wbms) free((char *)wbms); Files[fnum].wbmpx_ptr = NULL; return(ERROR(ERRHRD,ERRdiskfull)); } return(CACHE_ERROR(wbms,ERRHRD,ERRdiskfull)); } /* Increment the total written, if this matches tcount we can discard the auxiliary struct (hurrah !) and return a writeC */ wbms->wr_total_written += nwritten; if(wbms->wr_total_written >= tcount) { if (write_through) { outsize = set_message(outbuf,1,0,True); SSVAL(outbuf,smb_vwv0,wbms->wr_total_written); send_response = True; } free((char *)wbms); Files[fnum].wbmpx_ptr = NULL; } if(send_response) return(outsize); return(-1); } /**************************************************************************** reply to a SMBsetattrE ****************************************************************************/ int reply_setattrE(char *inbuf,char *outbuf) { int cnum,fnum; struct utimbuf unix_times; int outsize = 0; outsize = set_message(outbuf,0,0,True); cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); /* Convert the DOS times into unix times. Ignore create time as UNIX can't set this. */ unix_times.actime = make_unix_date2(inbuf+smb_vwv3); unix_times.modtime = make_unix_date2(inbuf+smb_vwv5); /* * Patch from Ray Frush * Sometimes times are sent as zero - ignore them. */ if ((unix_times.actime == 0) && (unix_times.modtime == 0)) { /* Ignore request */ DEBUG(3,("%s reply_setattrE fnum=%d cnum=%d ignoring zero request - \ not setting timestamps of 0\n", timestring(), fnum,cnum,unix_times.actime,unix_times.modtime)); return(outsize); } else if ((unix_times.actime != 0) && (unix_times.modtime == 0)) { /* set modify time = to access time if modify time was 0 */ unix_times.modtime = unix_times.actime; } /* Set the date on this file */ if(sys_utime(Files[fnum].name, &unix_times)) return(ERROR(ERRDOS,ERRnoaccess)); DEBUG(3,("%s reply_setattrE fnum=%d cnum=%d actime=%d modtime=%d\n", timestring(), fnum,cnum,unix_times.actime,unix_times.modtime)); return(outsize); } /**************************************************************************** reply to a SMBgetattrE ****************************************************************************/ int reply_getattrE(char *inbuf,char *outbuf) { int cnum,fnum; struct stat sbuf; int outsize = 0; int mode; outsize = set_message(outbuf,11,0,True); cnum = SVAL(inbuf,smb_tid); fnum = GETFNUM(inbuf,smb_vwv0); CHECK_FNUM(fnum,cnum); CHECK_ERROR(fnum); /* Do an fstat on this file */ if(fstat(Files[fnum].fd_ptr->fd, &sbuf)) return(UNIXERROR(ERRDOS,ERRnoaccess)); mode = dos_mode(cnum,Files[fnum].name,&sbuf); /* Convert the times into dos times. Set create date to be last modify date as UNIX doesn't save this */ put_dos_date2(outbuf,smb_vwv0,sbuf.st_mtime); put_dos_date2(outbuf,smb_vwv2,sbuf.st_atime); put_dos_date2(outbuf,smb_vwv4,sbuf.st_mtime); if (mode & aDIR) { SIVAL(outbuf,smb_vwv6,0); SIVAL(outbuf,smb_vwv8,0); } else { SIVAL(outbuf,smb_vwv6,sbuf.st_size); SIVAL(outbuf,smb_vwv8,ROUNDUP(sbuf.st_size,1024)); } SSVAL(outbuf,smb_vwv10, mode); DEBUG(3,("%s reply_getattrE fnum=%d cnum=%d\n",timestring(),fnum,cnum)); return(outsize); } 9' href='#n2649'>2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398
/* 
   Unix SMB/Netbios implementation.
   SMB client library implementation
   Copyright (C) Andrew Tridgell 1998
   Copyright (C) Richard Sharpe 2000, 2002
   Copyright (C) John Terpstra 2000
   Copyright (C) Tom Jansen (Ninja ISD) 2002 
   Copyright (C) Derrell Lipman 2003, 2004
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"

#include "include/libsmb_internal.h"


/*
 * DOS Attribute values (used internally)
 */
typedef struct DOS_ATTR_DESC
{
    int mode;
    unsigned long long size;
    time_t a_time;
    time_t c_time;
    time_t m_time;
    unsigned long long inode;
} DOS_ATTR_DESC;


/*
 * Internal flags for extended attributes
 */

/* internal mode values */
#define SMBC_XATTR_MODE_ADD          1
#define SMBC_XATTR_MODE_REMOVE       2
#define SMBC_XATTR_MODE_REMOVE_ALL   3
#define SMBC_XATTR_MODE_SET          4
#define SMBC_XATTR_MODE_CHOWN        5
#define SMBC_XATTR_MODE_CHGRP        6

#define CREATE_ACCESS_READ      READ_CONTROL_ACCESS

/*We should test for this in configure ... */
#ifndef ENOTSUP
#define ENOTSUP EOPNOTSUPP
#endif

/*
 * Functions exported by libsmb_cache.c that we need here
 */
int smbc_default_cache_functions(SMBCCTX *context);

/* 
 * check if an element is part of the list. 
 * FIXME: Does not belong here !  
 * Can anyone put this in a macro in dlinklist.h ?
 * -- Tom
 */
static int DLIST_CONTAINS(SMBCFILE * list, SMBCFILE *p) {
	if (!p || !list) return False;
	do {
		if (p == list) return True;
		list = list->next;
	} while (list);
	return False;
}

static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file);
static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence);

extern BOOL in_client;

/*
 * Is the logging working / configfile read ? 
 */
static int smbc_initialized = 0;

static int 
hex2int( unsigned int _char )
{
    if ( _char >= 'A' && _char <='F')
	return _char - 'A' + 10;
    if ( _char >= 'a' && _char <='f')
	return _char - 'a' + 10;
    if ( _char >= '0' && _char <='9')
	return _char - '0';
    return -1;
}

/*
 * smbc_urldecode()
 *
 * Convert strings of %xx to their single character equivalent.  Each 'x' must
 * be a valid hexadecimal digit, or that % sequence is left undecoded.
 *
 * dest may, but need not be, the same pointer as src.
 *
 * Returns the number of % sequences which could not be converted due to lack
 * of two following hexadecimal digits.
 */
int
smbc_urldecode(char *dest, char * src, size_t max_dest_len)
{
        int old_length = strlen(src);
        int i = 0;
        int err_count = 0;
        pstring temp;
        char * p;

        if ( old_length == 0 ) {
                return 0;
        }

        p = temp;
        while ( i < old_length ) {
                unsigned char character = src[ i++ ];

                if (character == '%') {
                        int a = i+1 < old_length ? hex2int( src[i] ) : -1;
                        int b = i+1 < old_length ? hex2int( src[i+1] ) : -1;

                        /* Replace valid sequence */
                        if (a != -1 && b != -1) {

                                /* Replace valid %xx sequence with %dd */
                                character = (a * 16) + b;

                                if (character == '\0') {
                                        break; /* Stop at %00 */
                                }

                                i += 2;
                        } else {

                                err_count++;
                        }
                }

                *p++ = character;
        }

        *p = '\0';

        strncpy(dest, temp, max_dest_len);

        return err_count;
}

/*
 * smbc_urlencode()
 *
 * Convert any characters not specifically allowed in a URL into their %xx
 * equivalent.
 *
 * Returns the remaining buffer length.
 */
int
smbc_urlencode(char * dest, char * src, int max_dest_len)
{
        char hex[] = "0123456789ABCDEF";

        for (; *src != '\0' && max_dest_len >= 3; src++) {

                if ((*src < '0' &&
                     *src != '-' &&
                     *src != '.') ||
                    (*src > '9' &&
                     *src < 'A') ||
                    (*src > 'Z' &&
                     *src < 'a' &&
                     *src != '_') ||
                    (*src > 'z')) {
                        *dest++ = '%';
                        *dest++ = hex[(*src >> 4) & 0x0f];
                        *dest++ = hex[*src & 0x0f];
                        max_dest_len -= 3;
                } else {
                        *dest++ = *src;
                        max_dest_len--;
                }
        }

        *dest++ = '\0';
        max_dest_len--;
        
        return max_dest_len;
}

/*
 * Function to parse a path and turn it into components
 *
 * The general format of an SMB URI is explain in Christopher Hertel's CIFS
 * book, at http://ubiqx.org/cifs/Appendix-D.html.  We accept a subset of the
 * general format ("smb:" only; we do not look for "cifs:").
 *
 *
 * We accept:
 *  smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]][?options]
 *
 * Meaning of URLs:
 *
 * smb://           Show all workgroups.
 *
 *                  The method of locating the list of workgroups varies
 *                  depending upon the setting of the context variable
 *                  context->options.browse_max_lmb_count.  This value
 *                  determine the maximum number of local master browsers to
 *                  query for the list of workgroups.  In order to ensure that
 *                  a complete list of workgroups is obtained, all master
 *                  browsers must be queried, but if there are many
 *                  workgroups, the time spent querying can begin to add up.
 *                  For small networks (not many workgroups), it is suggested
 *                  that this variable be set to 0, indicating query all local
 *                  master browsers.  When the network has many workgroups, a
 *                  reasonable setting for this variable might be around 3.
 *
 * smb://name/      if name<1D> or name<1B> exists, list servers in
 *                  workgroup, else, if name<20> exists, list all shares
 *                  for server ...
 *
 * If "options" are provided, this function returns the entire option list as a
 * string, for later parsing by the caller.  Note that currently, no options
 * are supported.
 */

static const char *smbc_prefix = "smb:";

static int
smbc_parse_path(SMBCCTX *context,
                const char *fname,
                char *server, int server_len,
                char *share, int share_len,
                char *path, int path_len,
		char *user, int user_len,
                char *password, int password_len,
                char *options, int options_len)
{
	static pstring s;
	pstring userinfo;
	const char *p;
	char *q, *r;
	int len;

	server[0] = share[0] = path[0] = user[0] = password[0] = (char)0;
        if (options != NULL && options_len > 0) {
                options[0] = (char)0;
        }
	pstrcpy(s, fname);

	/* see if it has the right prefix */
	len = strlen(smbc_prefix);
	if (strncmp(s,smbc_prefix,len) || (s[len] != '/' && s[len] != 0)) {
                return -1; /* What about no smb: ? */
        }

	p = s + len;

	/* Watch the test below, we are testing to see if we should exit */

	if (strncmp(p, "//", 2) && strncmp(p, "\\\\", 2)) {

                DEBUG(1, ("Invalid path (does not begin with smb://"));
		return -1;

	}

	p += 2;  /* Skip the double slash */

        /* See if any options were specified */
        if ((q = strrchr(p, '?')) != NULL ) {
                /* There are options.  Null terminate here and point to them */
                *q++ = '\0';
                
                DEBUG(4, ("Found options '%s'", q));

                /* Copy the options */
                if (options != NULL && options_len > 0) {
                        safe_strcpy(options, q, options_len - 1);
                }
        }

	if (*p == (char)0)
	    goto decoding;

	if (*p == '/') {

		strncpy(server, context->workgroup, 
			(strlen(context->workgroup) < 16)?strlen(context->workgroup):16);
		return 0;
		
	}

	/*
	 * ok, its for us. Now parse out the server, share etc. 
	 *
	 * However, we want to parse out [[domain;]user[:password]@] if it
	 * exists ...
	 */

	/* check that '@' occurs before '/', if '/' exists at all */
	q = strchr_m(p, '@');
	r = strchr_m(p, '/');
	if (q && (!r || q < r)) {
		pstring username, passwd, domain;
		const char *u = userinfo;

		next_token(&p, userinfo, "@", sizeof(fstring));

		username[0] = passwd[0] = domain[0] = 0;

		if (strchr_m(u, ';')) {
      
			next_token(&u, domain, ";", sizeof(fstring));

		}

		if (strchr_m(u, ':')) {

			next_token(&u, username, ":", sizeof(fstring));

			pstrcpy(passwd, u);

		}
		else {

			pstrcpy(username, u);

		}

		if (username[0])
			strncpy(user, username, user_len);  /* FIXME, domain */

		if (passwd[0])
			strncpy(password, passwd, password_len);

	}

	if (!next_token(&p, server, "/", sizeof(fstring))) {

		return -1;

	}

	if (*p == (char)0) goto decoding;  /* That's it ... */
  
	if (!next_token(&p, share, "/", sizeof(fstring))) {

		return -1;

	}

        safe_strcpy(path, p, path_len - 1);

	all_string_sub(path, "/", "\\", 0);

 decoding:
	(void) smbc_urldecode(path, path, path_len);
	(void) smbc_urldecode(server, server, server_len);
	(void) smbc_urldecode(share, share, share_len);
	(void) smbc_urldecode(user, user, user_len);
	(void) smbc_urldecode(password, password, password_len);

	return 0;
}

/*
 * Verify that the options specified in a URL are valid
 */
static int smbc_check_options(char *server, char *share, char *path, char *options)
{
        DEBUG(4, ("smbc_check_options(): server='%s' share='%s' path='%s' options='%s'\n", server, share, path, options));

        /* No options at all is always ok */
        if (! *options) return 0;

        /* Currently, we don't support any options. */
        return -1;
}

/*
 * Convert an SMB error into a UNIX error ...
 */
static int smbc_errno(SMBCCTX *context, struct cli_state *c)
{
	int ret = cli_errno(c);
	
        if (cli_is_dos_error(c)) {
                uint8 eclass;
                uint32 ecode;

                cli_dos_error(c, &eclass, &ecode);
                
                DEBUG(3,("smbc_error %d %d (0x%x) -> %d\n", 
                         (int)eclass, (int)ecode, (int)ecode, ret));
        } else {
                NTSTATUS status;

                status = cli_nt_error(c);

                DEBUG(3,("smbc errno %s -> %d\n",
                         nt_errstr(status), ret));
        }

	return ret;
}

/* 
 * Check a server for being alive and well.
 * returns 0 if the server is in shape. Returns 1 on error 
 * 
 * Also useable outside libsmbclient to enable external cache
 * to do some checks too.
 */
int smbc_check_server(SMBCCTX * context, SMBCSRV * server) 
{
	if ( send_keepalive(server->cli.fd) == False )
		return 1;

	/* connection is ok */
	return 0;
}

/* 
 * Remove a server from the cached server list it's unused.
 * On success, 0 is returned. 1 is returned if the server could not be removed.
 * 
 * Also useable outside libsmbclient
 */
int smbc_remove_unused_server(SMBCCTX * context, SMBCSRV * srv)
{
	SMBCFILE * file;

	/* are we being fooled ? */
	if (!context || !context->internal ||
	    !context->internal->_initialized || !srv) return 1;

	
	/* Check all open files/directories for a relation with this server */
	for (file = context->internal->_files; file; file=file->next) {
		if (file->srv == srv) {
			/* Still used */
			DEBUG(3, ("smbc_remove_usused_server: %p still used by %p.\n", 
				  srv, file));
			return 1;
		}
	}

	DLIST_REMOVE(context->internal->_servers, srv);

	cli_shutdown(&srv->cli);

	DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));

	context->callbacks.remove_cached_srv_fn(context, srv);
	
	return 0;
}

SMBCSRV *find_server(SMBCCTX *context,
                     const char *server,
                     const char *share,
                     fstring workgroup,
                     fstring username,
                     fstring password)
{
        SMBCSRV *srv;
        int auth_called = 0;
        
 check_server_cache:

	srv = context->callbacks.get_cached_srv_fn(context, server, share, 
						   workgroup, username);

	if (!auth_called && !srv && (!username[0] || !password[0])) {
		context->callbacks.auth_fn(server, share,
                                           workgroup, sizeof(fstring),
                                           username, sizeof(fstring),
                                           password, sizeof(fstring));
		/*
                 * However, smbc_auth_fn may have picked up info relating to
                 * an existing connection, so try for an existing connection
                 * again ...
                 */
		auth_called = 1;
		goto check_server_cache;
		
	}
	
	if (srv) {
		if (context->callbacks.check_server_fn(context, srv)) {
			/*
                         * This server is no good anymore 
                         * Try to remove it and check for more possible
                         * servers in the cache
                         */
			if (context->callbacks.remove_unused_server_fn(context,
                                                                       srv)) { 
                                /*
                                 * We could not remove the server completely,
                                 * remove it from the cache so we will not get
                                 * it again. It will be removed when the last
                                 * file/dir is closed.
                                 */
				context->callbacks.remove_cached_srv_fn(context,
                                                                        srv);
			}
			
			/*
                         * Maybe there are more cached connections to this
                         * server
                         */
			goto check_server_cache; 
		}

		return srv;
 	}

        return NULL;
}

/*
 * Connect to a server, possibly on an existing connection
 *
 * Here, what we want to do is: If the server and username
 * match an existing connection, reuse that, otherwise, establish a 
 * new connection.
 *
 * If we have to create a new connection, call the auth_fn to get the
 * info we need, unless the username and password were passed in.
 */

SMBCSRV *smbc_server(SMBCCTX *context,
		     const char *server, const char *share, 
		     fstring workgroup, fstring username, 
		     fstring password)
{
	SMBCSRV *srv=NULL;
	struct cli_state c;
	struct nmb_name called, calling;
	const char *server_n = server;
	pstring ipenv;
	struct in_addr ip;
	int tried_reverse = 0;
        int port_try_first;
        int port_try_next;
        const char *username_used;
  
	zero_ip(&ip);
	ZERO_STRUCT(c);

	if (server[0] == 0) {
		errno = EPERM;
		return NULL;
	}

        srv = find_server(context, server, share,
                          workgroup, username, password);

        /*
         * If we found a connection and we're only allowed one share per
         * server...
         */
        if (srv && *share != '\0' && context->options.one_share_per_server) {

                /*
                 * ... then if there's no current connection to the share,
                 * connect to it.  find_server(), or rather the function
                 * pointed to by context->callbacks.get_cached_srv_fn which
                 * was called by find_server(), will have issued a tree
                 * disconnect if the requested share is not the same as the
                 * one that was already connected.
                 */
                if (srv->cli.cnum == (uint16) -1) {
                        /* Ensure we have accurate auth info */
                        context->callbacks.auth_fn(server, share,
                                                   workgroup, sizeof(fstring),
                                                   username, sizeof(fstring),
                                                   password, sizeof(fstring));

                        if (! cli_send_tconX(&srv->cli, share, "?????",
                                             password, strlen(password)+1)) {
                        
                                errno = smbc_errno(context, &srv->cli);
                                cli_shutdown(&srv->cli);
                                context->callbacks.remove_cached_srv_fn(context, srv);
                                srv = NULL;
                        }

                        /* Regenerate the dev value since it's based on both server and share */
                        if (srv) {
                                srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
                        }
                }
        }
        
        /* If we have a connection... */
        if (srv) {

                /* ... then we're done here.  Give 'em what they came for. */
                return srv;
        }

	make_nmb_name(&calling, context->netbios_name, 0x0);
	make_nmb_name(&called , server, 0x20);

	DEBUG(4,("smbc_server: server_n=[%s] server=[%s]\n", server_n, server));
  
	DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));

 again:
	slprintf(ipenv,sizeof(ipenv)-1,"HOST_%s", server_n);

	zero_ip(&ip);

	/* have to open a new connection */
	if (!cli_initialise(&c)) {
		errno = ENOMEM;
		return NULL;
	}

	if (context->flags & SMB_CTX_FLAG_USE_KERBEROS) {
		c.use_kerberos = True;
	}
	if (context->flags & SMB_CTX_FLAG_FALLBACK_AFTER_KERBEROS) {
		c.fallback_after_kerberos = True;
	}

	c.timeout = context->timeout;

        /*
         * Force use of port 139 for first try if share is $IPC, empty, or
         * null, so browse lists can work
         */
        if (share == NULL || *share == '\0' || strcmp(share, "IPC$") == 0) {
                port_try_first = 139;
                port_try_next = 445;
        } else {
                port_try_first = 445;
                port_try_next = 139;
        }

        c.port = port_try_first;

	if (!cli_connect(&c, server_n, &ip)) {

                /* First connection attempt failed.  Try alternate port. */
                c.port = port_try_next;

                if (!cli_connect(&c, server_n, &ip)) {
                        cli_shutdown(&c);
                        errno = ETIMEDOUT;
                        return NULL;
                }
 	}

	if (!cli_session_request(&c, &calling, &called)) {
		cli_shutdown(&c);
		if (strcmp(called.name, "*SMBSERVER")) {
			make_nmb_name(&called , "*SMBSERVER", 0x20);
			goto again;
		}
		else {  /* Try one more time, but ensure we don't loop */

		  /* Only try this if server is an IP address ... */

		  if (is_ipaddress(server) && !tried_reverse) {
		    fstring remote_name;
		    struct in_addr rem_ip;

		    if ((rem_ip.s_addr=inet_addr(server)) == INADDR_NONE) {
		      DEBUG(4, ("Could not convert IP address %s to struct in_addr\n", server));
		      errno = ETIMEDOUT;
		      return NULL;
		    }

		    tried_reverse++; /* Yuck */

		    if (name_status_find("*", 0, 0, rem_ip, remote_name)) {
		      make_nmb_name(&called, remote_name, 0x20);
		      goto again;
		    }


		  }
		}
		errno = ETIMEDOUT;
		return NULL;
	}
  
	DEBUG(4,(" session request ok\n"));
  
	if (!cli_negprot(&c)) {
		cli_shutdown(&c);
		errno = ETIMEDOUT;
		return NULL;
	}

        username_used = username;

	if (!cli_session_setup(&c, username_used, 
			       password, strlen(password),
			       password, strlen(password),
			       workgroup)) {
                
                /* Failed.  Try an anonymous login, if allowed by flags. */
                username_used = "";

                if ((context->flags & SMBCCTX_FLAG_NO_AUTO_ANONYMOUS_LOGON) ||
                     !cli_session_setup(&c, username_used,
                                        password, 1,
                                        password, 0,
                                        workgroup)) {

                        cli_shutdown(&c);
                        errno = EPERM;
                        return NULL;
                }
	}

	DEBUG(4,(" session setup ok\n"));

	if (!cli_send_tconX(&c, share, "?????",
			    password, strlen(password)+1)) {
		errno = smbc_errno(context, &c);
		cli_shutdown(&c);
		return NULL;
	}
  
	DEBUG(4,(" tconx ok\n"));
  
	/*
	 * Ok, we have got a nice connection
	 * Let's allocate a server structure.
	 */

	srv = SMB_MALLOC_P(SMBCSRV);
	if (!srv) {
		errno = ENOMEM;
		goto failed;
	}

	ZERO_STRUCTP(srv);
	srv->cli = c;
	srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
        srv->no_pathinfo = False;
        srv->no_pathinfo2 = False;
        srv->no_nt_session = False;

	/* now add it to the cache (internal or external)  */
	/* Let the cache function set errno if it wants to */
	errno = 0;
	if (context->callbacks.add_cached_srv_fn(context, srv, server, share, workgroup, username_used)) {
		int saved_errno = errno;
		DEBUG(3, (" Failed to add server to cache\n"));
		errno = saved_errno;
		if (errno == 0) {
			errno = ENOMEM;
		}
		goto failed;
	}
	
	DEBUG(2, ("Server connect ok: //%s/%s: %p\n", 
		  server, share, srv));

	DLIST_ADD(context->internal->_servers, srv);
	return srv;

 failed:
	cli_shutdown(&c);
	if (!srv) return NULL;
  
	SAFE_FREE(srv);
	return NULL;
}

/*
 * Connect to a server for getting/setting attributes, possibly on an existing
 * connection.  This works similarly to smbc_server().
 */
SMBCSRV *smbc_attr_server(SMBCCTX *context,
                          const char *server, const char *share, 
                          fstring workgroup,
                          fstring username, fstring password,
                          POLICY_HND *pol)
{
        struct in_addr ip;
	struct cli_state *ipc_cli;
        NTSTATUS nt_status;
	SMBCSRV *ipc_srv=NULL;

        /*
         * See if we've already created this special connection.  Reference our
         * "special" share name '*IPC$', which is an impossible real share name
         * due to the leading asterisk.
         */
        ipc_srv = find_server(context, server, "*IPC$",
                              workgroup, username, password);
        if (!ipc_srv) {

                /* We didn't find a cached connection.  Get the password */
                if (*password == '\0') {
                        /* ... then retrieve it now. */
                        context->callbacks.auth_fn(server, share,
                                                   workgroup, sizeof(fstring),
                                                   username, sizeof(fstring),
                                                   password, sizeof(fstring));
                }
        
                zero_ip(&ip);
                nt_status = cli_full_connection(&ipc_cli,
                                                global_myname(), server, 
                                                &ip, 0, "IPC$", "?????",  
                                                username, workgroup,
                                                password, 0,
                                                Undefined, NULL);
                if (! NT_STATUS_IS_OK(nt_status)) {
                        DEBUG(1,("cli_full_connection failed! (%s)\n",
                                 nt_errstr(nt_status)));
                        errno = ENOTSUP;
                        return NULL;
                }

                if (!cli_nt_session_open(ipc_cli, PI_LSARPC)) {
                        DEBUG(1, ("cli_nt_session_open fail!\n"));
                        errno = ENOTSUP;
                        cli_shutdown(ipc_cli);
                        return NULL;
                }

                /* Some systems don't support SEC_RIGHTS_MAXIMUM_ALLOWED,
                   but NT sends 0x2000000 so we might as well do it too. */
        
                nt_status = cli_lsa_open_policy(ipc_cli,
                                                ipc_cli->mem_ctx,
                                                True, 
                                                GENERIC_EXECUTE_ACCESS,
                                                pol);
        
                if (!NT_STATUS_IS_OK(nt_status)) {
                        errno = smbc_errno(context, ipc_cli);
                        cli_shutdown(ipc_cli);
                        return NULL;
                }

                ipc_srv = SMB_MALLOC_P(SMBCSRV);
                if (!ipc_srv) {
                        errno = ENOMEM;
                        cli_shutdown(ipc_cli);
                        return NULL;
                }

                ZERO_STRUCTP(ipc_srv);
                ipc_srv->cli = *ipc_cli;

                free(ipc_cli);

                /* now add it to the cache (internal or external) */

                errno = 0;      /* let cache function set errno if it likes */
                if (context->callbacks.add_cached_srv_fn(context, ipc_srv,
                                                         server,
                                                         "*IPC$",
                                                         workgroup,
                                                         username)) {
                        DEBUG(3, (" Failed to add server to cache\n"));
                        if (errno == 0) {
                                errno = ENOMEM;
                        }
                        cli_shutdown(&ipc_srv->cli);
                        free(ipc_srv);
                        return NULL;
                }

                DLIST_ADD(context->internal->_servers, ipc_srv);
        }

        return ipc_srv;
}

/*
 * Routine to open() a file ...
 */

static SMBCFILE *smbc_open_ctx(SMBCCTX *context, const char *fname, int flags, mode_t mode)
{
	fstring server, share, user, password, workgroup;
	pstring path;
	SMBCSRV *srv   = NULL;
	SMBCFILE *file = NULL;
	int fd;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;  /* Best I can think of ... */
		return NULL;

	}

	if (!fname) {

		errno = EINVAL;
		return NULL;

	}

	if (smbc_parse_path(context, fname,
                            server, sizeof(server),
                            share, sizeof(share),
                            path, sizeof(path),
                            user, sizeof(user),
                            password, sizeof(password),
                            NULL, 0)) {
                errno = EINVAL;
                return NULL;
        }

	if (user[0] == (char)0) fstrcpy(user, context->user);

	fstrcpy(workgroup, context->workgroup);

	srv = smbc_server(context, server, share, workgroup, user, password);

	if (!srv) {

		if (errno == EPERM) errno = EACCES;
		return NULL;  /* smbc_server sets errno */
    
	}

	/* Hmmm, the test for a directory is suspect here ... FIXME */

	if (strlen(path) > 0 && path[strlen(path) - 1] == '\\') {
    
		fd = -1;

	}
	else {
	  
		file = SMB_MALLOC_P(SMBCFILE);

		if (!file) {

			errno = ENOMEM;
			return NULL;

		}

		ZERO_STRUCTP(file);

		if ((fd = cli_open(&srv->cli, path, flags, DENY_NONE)) < 0) {

			/* Handle the error ... */

			SAFE_FREE(file);
			errno = smbc_errno(context, &srv->cli);
			return NULL;

		}

		/* Fill in file struct */

		file->cli_fd  = fd;
		file->fname   = SMB_STRDUP(fname);
		file->srv     = srv;
		file->offset  = 0;
		file->file    = True;

		DLIST_ADD(context->internal->_files, file);

                /*
                 * If the file was opened in O_APPEND mode, all write
                 * operations should be appended to the file.  To do that,
                 * though, using this protocol, would require a getattrE()
                 * call for each and every write, to determine where the end
                 * of the file is. (There does not appear to be an append flag
                 * in the protocol.)  Rather than add all of that overhead of
                 * retrieving the current end-of-file offset prior to each
                 * write operation, we'll assume that most append operations
                 * will continuously write, so we'll just set the offset to
                 * the end of the file now and hope that's adequate.
                 *
                 * Note to self: If this proves inadequate, and O_APPEND
                 * should, in some cases, be forced for each write, add a
                 * field in the context options structure, for
                 * "strict_append_mode" which would select between the current
                 * behavior (if FALSE) or issuing a getattrE() prior to each
                 * write and forcing the write to the end of the file (if
                 * TRUE).  Adding that capability will likely require adding
                 * an "append" flag into the _SMBCFILE structure to track
                 * whether a file was opened in O_APPEND mode.  -- djl
                 */
                if (flags & O_APPEND) {
                        if (smbc_lseek_ctx(context, file, 0, SEEK_END) < 0) {
                                (void) smbc_close_ctx(context, file);
                                errno = ENXIO;
                                return NULL;
                        }
                }

		return file;

	}

	/* Check if opendir needed ... */

	if (fd == -1) {
		int eno = 0;

		eno = smbc_errno(context, &srv->cli);
		file = context->opendir(context, fname);
		if (!file) errno = eno;
		return file;

	}

	errno = EINVAL; /* FIXME, correct errno ? */
	return NULL;

}

/*
 * Routine to create a file 
 */

static int creat_bits = O_WRONLY | O_CREAT | O_TRUNC; /* FIXME: Do we need this */

static SMBCFILE *smbc_creat_ctx(SMBCCTX *context, const char *path, mode_t mode)
{

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return NULL;

	}

	return smbc_open_ctx(context, path, creat_bits, mode);
}

/*
 * Routine to read() a file ...
 */

static ssize_t smbc_read_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
{
	int ret;

        /*
         * offset:
         *
         * Compiler bug (possibly) -- gcc (GCC) 3.3.5 (Debian 1:3.3.5-2) --
         * appears to pass file->offset (which is type off_t) differently than
         * a local variable of type off_t.  Using local variable "offset" in
         * the call to cli_read() instead of file->offset fixes a problem
         * retrieving data at an offset greater than 4GB.
         */
        off_t offset = file->offset;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;

	}

	DEBUG(4, ("smbc_read(%p, %d)\n", file, (int)count));

	if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {

		errno = EBADF;
		return -1;

	}

	/* Check that the buffer exists ... */

	if (buf == NULL) {

		errno = EINVAL;
		return -1;

	}

	ret = cli_read(&file->srv->cli, file->cli_fd, buf, offset, count);

	if (ret < 0) {

		errno = smbc_errno(context, &file->srv->cli);
		return -1;

	}

	file->offset += ret;

	DEBUG(4, ("  --> %d\n", ret));

	return ret;  /* Success, ret bytes of data ... */

}

/*
 * Routine to write() a file ...
 */

static ssize_t smbc_write_ctx(SMBCCTX *context, SMBCFILE *file, void *buf, size_t count)
{
	int ret;
        off_t offset = file->offset; /* See "offset" comment in smbc_read_ctx() */

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;

	}

	if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {

		errno = EBADF;
		return -1;
    
	}

	/* Check that the buffer exists ... */

	if (buf == NULL) {

		errno = EINVAL;
		return -1;

	}

	ret = cli_write(&file->srv->cli, file->cli_fd, 0, buf, offset, count);

	if (ret <= 0) {

		errno = smbc_errno(context, &file->srv->cli);
		return -1;

	}

	file->offset += ret;

	return ret;  /* Success, 0 bytes of data ... */
}
 
/*
 * Routine to close() a file ...
 */

static int smbc_close_ctx(SMBCCTX *context, SMBCFILE *file)
{
        SMBCSRV *srv; 

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;

	}

	if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {
   
		errno = EBADF;
		return -1;

	}

	/* IS a dir ... */
	if (!file->file) {
		
		return context->closedir(context, file);

	}

	if (!cli_close(&file->srv->cli, file->cli_fd)) {

		DEBUG(3, ("cli_close failed on %s. purging server.\n", 
			  file->fname));
		/* Deallocate slot and remove the server 
		 * from the server cache if unused */
		errno = smbc_errno(context, &file->srv->cli);  
		srv = file->srv;
		DLIST_REMOVE(context->internal->_files, file);
		SAFE_FREE(file->fname);
		SAFE_FREE(file);
		context->callbacks.remove_unused_server_fn(context, srv);

		return -1;

	}

	DLIST_REMOVE(context->internal->_files, file);
	SAFE_FREE(file->fname);
	SAFE_FREE(file);

	return 0;
}

/*
 * Get info from an SMB server on a file. Use a qpathinfo call first
 * and if that fails, use getatr, as Win95 sometimes refuses qpathinfo
 */
static BOOL smbc_getatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
		 uint16 *mode, SMB_OFF_T *size, 
		 time_t *c_time, time_t *a_time, time_t *m_time,
		 SMB_INO_T *ino)
{

	if (!context || !context->internal ||
	    !context->internal->_initialized) {
 
		errno = EINVAL;
 		return -1;
 
 	}

	DEBUG(4,("smbc_getatr: sending qpathinfo\n"));
  
	if (!srv->no_pathinfo2 &&
	    cli_qpathinfo2(&srv->cli, path, c_time, a_time, m_time, NULL,
			   size, mode, ino)) return True;

	/* if this is NT then don't bother with the getatr */
	if (srv->cli.capabilities & CAP_NT_SMBS) {
                errno = EPERM;
                return False;
        }

	if (cli_getatr(&srv->cli, path, mode, size, m_time)) {
                if (m_time != NULL) {
                        if (a_time != NULL) *a_time = *m_time;
                        if (c_time != NULL) *c_time = *m_time;
                }
		srv->no_pathinfo2 = True;
		return True;
	}

        errno = EPERM;
	return False;

}

/*
 * Set file info on an SMB server.  Use setpathinfo call first.  If that
 * fails, use setattrE..
 *
 * Access and modification time parameters are always used and must be
 * provided.  Create time, if zero, will be determined from the actual create
 * time of the file.  If non-zero, the create time will be set as well.
 *
 * "mode" (attributes) parameter may be set to -1 if it is not to be set.
 */
static BOOL smbc_setatr(SMBCCTX * context, SMBCSRV *srv, char *path, 
                        time_t c_time, time_t a_time, time_t m_time,
                        uint16 mode)
{
        int fd;
        int ret;

        /*
         * Get the create time of the file (if not provided); we'll need it in
         * the set call.
         */
        if (! srv->no_pathinfo && c_time != 0) {
                if (! cli_qpathinfo(&srv->cli, path,
                                    &c_time, NULL, NULL, NULL, NULL)) {
                        /* qpathinfo not available */
                        srv->no_pathinfo = True;
                } else {
                        /*
                         * We got a creation time.  For sanity sake, since
                         * there is no POSIX function to set the create time
                         * of a file, if the existing create time is greater
                         * than either of access time or modification time,
                         * set create time to the smallest of those.  This
                         * ensure that the create time of a file is never
                         * greater than its last access or modification time.
                         */
                        if (c_time > a_time) c_time = a_time;
                        if (c_time > m_time) c_time = m_time;
                }
        }

        /*
         * First, try setpathinfo (if qpathinfo succeeded), for it is the
         * modern function for "new code" to be using, and it works given a
         * filename rather than requiring that the file be opened to have its
         * attributes manipulated.
         */
        if (srv->no_pathinfo ||
            ! cli_setpathinfo(&srv->cli, path, c_time, a_time, m_time, mode)) {

                /*
                 * setpathinfo is not supported; go to plan B. 
                 *
                 * cli_setatr() does not work on win98, and it also doesn't
                 * support setting the access time (only the modification
                 * time), so in all cases, we open the specified file and use
                 * cli_setattrE() which should work on all OS versions, and
                 * supports both times.
                 */

                /* Don't try {q,set}pathinfo() again, with this server */
                srv->no_pathinfo = True;

                /* Open the file */
                if ((fd = cli_open(&srv->cli, path, O_RDWR, DENY_NONE)) < 0) {

                        errno = smbc_errno(context, &srv->cli);
                        return -1;
                }

                /*
                 * Get the creat time of the file (if it wasn't provided).
                 * We'll need it in the set call
                 */
                if (c_time == 0) {
                        ret = cli_getattrE(&srv->cli, fd,
                                           NULL, NULL,
                                           &c_time, NULL, NULL);
                } else {
                        ret = True;
                }
                    
                /* If we got create time, set times */
                if (ret) {
                        /* Some OS versions don't support create time */
                        if (c_time == 0) {
                                c_time = time(NULL);
                        }

                        /*
                         * For sanity sake, since there is no POSIX function
                         * to set the create time of a file, if the existing
                         * create time is greater than either of access time
                         * or modification time, set create time to the
                         * smallest of those.  This ensure that the create
                         * time of a file is never greater than its last
                         * access or modification time.
                         */
                        if (c_time > a_time) c_time = a_time;
                        if (c_time > m_time) c_time = m_time;
                        
                        /* Set the new attributes */
                        ret = cli_setattrE(&srv->cli, fd,
                                           c_time, a_time, m_time);
                        cli_close(&srv->cli, fd);
                }

                /*
                 * Unfortunately, setattrE() doesn't have a provision for
                 * setting the access mode (attributes).  We'll have to try
                 * cli_setatr() for that, and with only this parameter, it
                 * seems to work on win98.
                 */
                if (ret && mode != (uint16) -1) {
                        ret = cli_setatr(&srv->cli, path, mode, 0);
                }

                if (! ret) {
                        errno = smbc_errno(context, &srv->cli);
                        return False;
                }
        }

        return True;
}

 /*
  * Routine to unlink() a file
  */

 static int smbc_unlink_ctx(SMBCCTX *context, const char *fname)
{
	fstring server, share, user, password, workgroup;
	pstring path;
	SMBCSRV *srv = NULL;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;  /* Best I can think of ... */
		return -1;

	}

	if (!fname) {

		errno = EINVAL;
		return -1;

	}

	if (smbc_parse_path(context, fname,
                            server, sizeof(server),
                            share, sizeof(share),
                            path, sizeof(path),
                            user, sizeof(user),
                            password, sizeof(password),
                            NULL, 0)) {
                errno = EINVAL;
                return -1;
        }

	if (user[0] == (char)0) fstrcpy(user, context->user);

	fstrcpy(workgroup, context->workgroup);

	srv = smbc_server(context, server, share, workgroup, user, password);

	if (!srv) {

		return -1;  /* smbc_server sets errno */

	}

	if (!cli_unlink(&srv->cli, path)) {

		errno = smbc_errno(context, &srv->cli);

		if (errno == EACCES) { /* Check if the file is a directory */

			int saverr = errno;
			SMB_OFF_T size = 0;
			uint16 mode = 0;
			time_t m_time = 0, a_time = 0, c_time = 0;
			SMB_INO_T ino = 0;

			if (!smbc_getatr(context, srv, path, &mode, &size,
					 &c_time, &a_time, &m_time, &ino)) {

				/* Hmmm, bad error ... What? */

				errno = smbc_errno(context, &srv->cli);
				return -1;

			}
			else {

				if (IS_DOS_DIR(mode))
					errno = EISDIR;
				else
					errno = saverr;  /* Restore this */

			}
		}

		return -1;

	}

	return 0;  /* Success ... */

}

/*
 * Routine to rename() a file
 */

static int smbc_rename_ctx(SMBCCTX *ocontext, const char *oname, 
			   SMBCCTX *ncontext, const char *nname)
{
	fstring server1, share1, server2, share2, user1, user2, password1, password2, workgroup;
	pstring path1, path2;
	SMBCSRV *srv = NULL;

	if (!ocontext || !ncontext || 
	    !ocontext->internal || !ncontext->internal ||
	    !ocontext->internal->_initialized || 
	    !ncontext->internal->_initialized) {

		errno = EINVAL;  /* Best I can think of ... */
		return -1;

	}
	
	if (!oname || !nname) {

		errno = EINVAL;
		return -1;

	}
	
	DEBUG(4, ("smbc_rename(%s,%s)\n", oname, nname));

	smbc_parse_path(ocontext, oname,
                        server1, sizeof(server1),
                        share1, sizeof(share1),
                        path1, sizeof(path1),
                        user1, sizeof(user1),
                        password1, sizeof(password1),
                        NULL, 0);

	if (user1[0] == (char)0) fstrcpy(user1, ocontext->user);

	smbc_parse_path(ncontext, nname,
                        server2, sizeof(server2),
                        share2, sizeof(share2),
                        path2, sizeof(path2),
                        user2, sizeof(user2),
                        password2, sizeof(password2),
                        NULL, 0);

	if (user2[0] == (char)0) fstrcpy(user2, ncontext->user);

	if (strcmp(server1, server2) || strcmp(share1, share2) ||
	    strcmp(user1, user2)) {

		/* Can't rename across file systems, or users?? */

		errno = EXDEV;
		return -1;

	}

	fstrcpy(workgroup, ocontext->workgroup);
	/* HELP !!! Which workgroup should I use ? Or are they always the same -- Tom */ 
	srv = smbc_server(ocontext, server1, share1, workgroup, user1, password1);
	if (!srv) {

		return -1;

	}

	if (!cli_rename(&srv->cli, path1, path2)) {
		int eno = smbc_errno(ocontext, &srv->cli);

		if (eno != EEXIST ||
		    !cli_unlink(&srv->cli, path2) ||
		    !cli_rename(&srv->cli, path1, path2)) {

			errno = eno;
			return -1;

		}
	}

	return 0; /* Success */

}

/*
 * A routine to lseek() a file
 */

static off_t smbc_lseek_ctx(SMBCCTX *context, SMBCFILE *file, off_t offset, int whence)
{
	SMB_OFF_T size;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;
		
	}

	if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {

		errno = EBADF;
		return -1;

	}

	if (!file->file) {

		errno = EINVAL;
		return -1;      /* Can't lseek a dir ... */

	}

	switch (whence) {
	case SEEK_SET:
		file->offset = offset;
		break;

	case SEEK_CUR:
		file->offset += offset;
		break;

	case SEEK_END:
		if (!cli_qfileinfo(&file->srv->cli, file->cli_fd, NULL, &size, NULL, NULL,
				   NULL, NULL, NULL)) 
		{
		    SMB_BIG_UINT b_size = size;
		    if (!cli_getattrE(&file->srv->cli, file->cli_fd, NULL, &b_size, NULL, NULL,
				      NULL)) 
		    {
			errno = EINVAL;
			return -1;
		    } else
			size = b_size;
		}
		file->offset = size + offset;
		break;

	default:
		errno = EINVAL;
		break;

	}

	return file->offset;

}

/* 
 * Generate an inode number from file name for those things that need it
 */

static
ino_t smbc_inode(SMBCCTX *context, const char *name)
{

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;

	}

	if (!*name) return 2; /* FIXME, why 2 ??? */
	return (ino_t)str_checksum(name);

}

/*
 * Routine to put basic stat info into a stat structure ... Used by stat and
 * fstat below.
 */

static
int smbc_setup_stat(SMBCCTX *context, struct stat *st, char *fname,
                    SMB_OFF_T size, int mode)
{
	
	st->st_mode = 0;

	if (IS_DOS_DIR(mode)) {
		st->st_mode = SMBC_DIR_MODE;
	} else {
		st->st_mode = SMBC_FILE_MODE;
	}

	if (IS_DOS_ARCHIVE(mode)) st->st_mode |= S_IXUSR;
	if (IS_DOS_SYSTEM(mode)) st->st_mode |= S_IXGRP;
	if (IS_DOS_HIDDEN(mode)) st->st_mode |= S_IXOTH;
	if (!IS_DOS_READONLY(mode)) st->st_mode |= S_IWUSR;

	st->st_size = size;
#ifdef HAVE_STAT_ST_BLKSIZE
	st->st_blksize = 512;
#endif
#ifdef HAVE_STAT_ST_BLOCKS
	st->st_blocks = (size+511)/512;
#endif
	st->st_uid = getuid();
	st->st_gid = getgid();

	if (IS_DOS_DIR(mode)) {
		st->st_nlink = 2;
	} else {
		st->st_nlink = 1;
	}

	if (st->st_ino == 0) {
		st->st_ino = smbc_inode(context, fname);
	}
	
	return True;  /* FIXME: Is this needed ? */

}

/*
 * Routine to stat a file given a name
 */

static int smbc_stat_ctx(SMBCCTX *context, const char *fname, struct stat *st)
{
	SMBCSRV *srv;
	fstring server, share, user, password, workgroup;
	pstring path;
	time_t m_time = 0, a_time = 0, c_time = 0;
	SMB_OFF_T size = 0;
	uint16 mode = 0;
	SMB_INO_T ino = 0;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;  /* Best I can think of ... */
		return -1;
    
	}

	if (!fname) {

		errno = EINVAL;
		return -1;

	}
  
	DEBUG(4, ("smbc_stat(%s)\n", fname));

	if (smbc_parse_path(context, fname,
                            server, sizeof(server),
                            share, sizeof(share),
                            path, sizeof(path),
                            user, sizeof(user),
                            password, sizeof(password),
                            NULL, 0)) {
                errno = EINVAL;
                return -1;
        }

	if (user[0] == (char)0) fstrcpy(user, context->user);

	fstrcpy(workgroup, context->workgroup);

	srv = smbc_server(context, server, share, workgroup, user, password);

	if (!srv) {
		return -1;  /* errno set by smbc_server */
	}

	if (!smbc_getatr(context, srv, path, &mode, &size, 
			 &c_time, &a_time, &m_time, &ino)) {

		errno = smbc_errno(context, &srv->cli);
		return -1;
		
	}

	st->st_ino = ino;

	smbc_setup_stat(context, st, path, size, mode);

	st->st_atime = a_time;
	st->st_ctime = c_time;
	st->st_mtime = m_time;
	st->st_dev   = srv->dev;

	return 0;

}

/*
 * Routine to stat a file given an fd
 */

static int smbc_fstat_ctx(SMBCCTX *context, SMBCFILE *file, struct stat *st)
{
	time_t c_time, a_time, m_time;
	SMB_OFF_T size;
	uint16 mode;
	SMB_INO_T ino = 0;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {

		errno = EINVAL;
		return -1;

	}

	if (!file || !DLIST_CONTAINS(context->internal->_files, file)) {

		errno = EBADF;
		return -1;

	}

	if (!file->file) {

		return context->fstatdir(context, file, st);

	}

	if (!cli_qfileinfo(&file->srv->cli, file->cli_fd,
			   &mode, &size, &c_time, &a_time, &m_time, NULL, &ino)) {
	    if (!cli_getattrE(&file->srv->cli, file->cli_fd,
			  &mode, &size, &c_time, &a_time, &m_time)) {

		errno = EINVAL;
		return -1;
	    }
	}

	st->st_ino = ino;

	smbc_setup_stat(context, st, file->fname, size, mode);

	st->st_atime = a_time;
	st->st_ctime = c_time;
	st->st_mtime = m_time;
	st->st_dev = file->srv->dev;

	return 0;

}

/*
 * Routine to open a directory
 * We accept the URL syntax explained in smbc_parse_path(), above.
 */

static void smbc_remove_dir(SMBCFILE *dir)
{
	struct smbc_dir_list *d,*f;

	d = dir->dir_list;
	while (d) {

		f = d; d = d->next;

		SAFE_FREE(f->dirent);
		SAFE_FREE(f);

	}

	dir->dir_list = dir->dir_end = dir->dir_next = NULL;

}

static int add_dirent(SMBCFILE *dir, const char *name, const char *comment, uint32 type)
{
	struct smbc_dirent *dirent;
	int size;
        int name_length = (name == NULL ? 0 : strlen(name));
        int comment_len = (comment == NULL ? 0 : strlen(comment));

	/*
	 * Allocate space for the dirent, which must be increased by the 
	 * size of the name and the comment and 1 each for the null terminator.
	 */

	size = sizeof(struct smbc_dirent) + name_length + comment_len + 2;
    
	dirent = SMB_MALLOC(size);

	if (!dirent) {

		dir->dir_error = ENOMEM;
		return -1;

	}

	ZERO_STRUCTP(dirent);

	if (dir->dir_list == NULL) {

		dir->dir_list = SMB_MALLOC_P(struct smbc_dir_list);
		if (!dir->dir_list) {

			SAFE_FREE(dirent);
			dir->dir_error = ENOMEM;
			return -1;

		}
		ZERO_STRUCTP(dir->dir_list);

		dir->dir_end = dir->dir_next = dir->dir_list;
	}
	else {

		dir->dir_end->next = SMB_MALLOC_P(struct smbc_dir_list);
		
		if (!dir->dir_end->next) {
			
			SAFE_FREE(dirent);
			dir->dir_error = ENOMEM;
			return -1;

		}
		ZERO_STRUCTP(dir->dir_end->next);

		dir->dir_end = dir->dir_end->next;
	}

	dir->dir_end->next = NULL;
	dir->dir_end->dirent = dirent;
	
	dirent->smbc_type = type;
	dirent->namelen = name_length;
	dirent->commentlen = comment_len;
	dirent->dirlen = size;
  
	strncpy(dirent->name, (name?name:""), dirent->namelen + 1);

	dirent->comment = (char *)(&dirent->name + dirent->namelen + 1);
	strncpy(dirent->comment, (comment?comment:""), dirent->commentlen + 1);
	
	return 0;

}

static void
list_unique_wg_fn(const char *name, uint32 type, const char *comment, void *state)
{
	SMBCFILE *dir = (SMBCFILE *)state;
        struct smbc_dir_list *dir_list;
        struct smbc_dirent *dirent;
	int dirent_type;
        int do_remove = 0;

	dirent_type = dir->dir_type;

	if (add_dirent(dir, name, comment, dirent_type) < 0) {

		/* An error occurred, what do we do? */
		/* FIXME: Add some code here */
	}

        /* Point to the one just added */
        dirent = dir->dir_end->dirent;

        /* See if this was a duplicate */
        for (dir_list = dir->dir_list;
             dir_list != dir->dir_end;
             dir_list = dir_list->next) {
                if (! do_remove &&
                    strcmp(dir_list->dirent->name, dirent->name) == 0) {
                        /* Duplicate.  End end of list need to be removed. */
                        do_remove = 1;
                }

                if (do_remove && dir_list->next == dir->dir_end) {
                        /* Found the end of the list.  Remove it. */
                        dir->dir_end = dir_list;
                        free(dir_list->next);
                        dir_list->next = NULL;
                        break;
                }
        }
}

static void
list_fn(const char *name, uint32 type, const char *comment, void *state)
{
	SMBCFILE *dir = (SMBCFILE *)state;
	int dirent_type;

	/* We need to process the type a little ... */

	if (dir->dir_type == SMBC_FILE_SHARE) {
		
		switch (type) {
		case 0: /* Directory tree */
			dirent_type = SMBC_FILE_SHARE;
			break;

		case 1:
			dirent_type = SMBC_PRINTER_SHARE;
			break;

		case 2:
			dirent_type = SMBC_COMMS_SHARE;
			break;

		case 3:
			dirent_type = SMBC_IPC_SHARE;
			break;

		default:
			dirent_type = SMBC_FILE_SHARE; /* FIXME, error? */
			break;
		}
	}
	else dirent_type = dir->dir_type;

	if (add_dirent(dir, name, comment, dirent_type) < 0) {

		/* An error occurred, what do we do? */
		/* FIXME: Add some code here */

	}
}

static void
dir_list_fn(const char *mnt, file_info *finfo, const char *mask, void *state)
{

	if (add_dirent((SMBCFILE *)state, finfo->name, "", 
		       (finfo->mode&aDIR?SMBC_DIR:SMBC_FILE)) < 0) {

		/* Handle an error ... */

		/* FIXME: Add some code ... */

	} 

}

static SMBCFILE *smbc_opendir_ctx(SMBCCTX *context, const char *fname)
{
	fstring server, share, user, password, options;
	pstring workgroup;
	pstring path;
        uint16 mode;
        char *p;
	SMBCSRV *srv  = NULL;
	SMBCFILE *dir = NULL;
	struct in_addr rem_ip;

	if (!context || !context->internal ||
	    !context->internal->_initialized) {
	        DEBUG(4, ("no valid context\n"));
		errno = EINVAL + 8192;
		return NULL;

	}

	if (!fname) {
		DEBUG(4, ("no valid fname\n"));
		errno = EINVAL + 8193;
		return NULL;
	}

	if (smbc_parse_path(context, fname,
                            server, sizeof(server),
                            share, sizeof(share),
                            path, sizeof(path),
                            user, sizeof(user),
                            password, sizeof(password),
                            options, sizeof(options))) {
	        DEBUG(4, ("no valid path\n"));
		errno = EINVAL + 8194;
		return NULL;
	}

	DEBUG(4, ("parsed path: fname='%s' server='%s' share='%s' path='%s' options='%s'\n", fname, server, share, path, options));

        /* Ensure the options are valid */
        if (smbc_check_options(server, share, path, options)) {
                DEBUG(4, ("unacceptable options (%s)\n", options));
                errno = EINVAL + 8195;
                return NULL;
        }

	if (user[0] == (char)0) fstrcpy(user, context->user);

	pstrcpy(workgroup, context->workgroup);

	dir = SMB_MALLOC_P(SMBCFILE);

	if (!dir) {

		errno = ENOMEM;
		return NULL;

	}

	ZERO_STRUCTP(dir);

	dir->cli_fd   = 0;
	dir->fname    = SMB_STRDUP(fname);
	dir->srv      = NULL;
	dir->offset   = 0;
	dir->file     = False;
	dir->dir_list = dir->dir_next = dir->dir_end = NULL;

	if (server[0] == (char)0) {

                int i;
                int count;
                int max_lmb_count;
                struct ip_service *ip_list;
                struct ip_service server_addr;
                struct user_auth_info u_info;
                struct cli_state *cli;

		if (share[0] != (char)0 || path[0] != (char)0) {

			errno = EINVAL + 8196;
			if (dir) {
				SAFE_FREE(dir->fname);
				SAFE_FREE(dir);
			}
			return NULL;
		}

                /* Determine how many local master browsers to query */
                max_lmb_count = (context->options.browse_max_lmb_count == 0
                                 ? INT_MAX
                                 : context->options.browse_max_lmb_count);

                pstrcpy(u_info.username, user);
                pstrcpy(u_info.password, password);

		/*
                 * We have server and share and path empty but options
                 * requesting that we scan all master browsers for their list
                 * of workgroups/domains.  This implies that we must first try
                 * broadcast queries to find all master browsers, and if that
                 * doesn't work, then try our other methods which return only
                 * a single master browser.
                 */

                if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
                        if (!find_master_ip(workgroup, &server_addr.ip)) {

                                errno = ENOENT;
                                return NULL;
                        }

                        ip_list = &server_addr;