FtpControlSocket.cpp 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236
  1. //---------------------------------------------------------------------------
  2. #include "FileZillaPCH.h"
  3. #include "FtpControlSocket.h"
  4. #include "MainThread.h"
  5. #include "transfersocket.h"
  6. #include "asyncproxysocketlayer.h"
  7. #include "AsyncSslSocketLayer.h"
  8. #ifndef MPEXT_NO_GSS
  9. #include "AsyncGssSocketLayer.h"
  10. #endif
  11. #include "filezillaapi.h"
  12. #include <WideStrUtils.hpp>
  13. class CFtpControlSocket::CFileTransferData : public CFtpControlSocket::t_operation::COpData
  14. {
  15. public:
  16. CFileTransferData()
  17. {
  18. pDirectoryListing=0;
  19. nGotTransferEndReply=0;
  20. nWaitNextOpState=0;
  21. nMKDOpState=-1;
  22. hasRemoteDate = false;
  23. pFileSize=0;
  24. bUseAbsolutePaths = FALSE;
  25. bTriedPortPasvOnce = FALSE;
  26. askOnResumeFail = false;
  27. };
  28. ~CFileTransferData()
  29. {
  30. if (pDirectoryListing)
  31. delete pDirectoryListing;
  32. pDirectoryListing=0;
  33. delete pFileSize;
  34. };
  35. CString rawpwd;
  36. t_transferfile transferfile;
  37. t_transferdata transferdata;
  38. CString host;
  39. int port;
  40. BOOL bPasv;
  41. int nGotTransferEndReply;
  42. t_directory *pDirectoryListing;
  43. int nWaitNextOpState;
  44. CServerPath MKDCurrent;
  45. std::list<CString> MKDSegments;
  46. int nMKDOpState;
  47. bool hasRemoteDate;
  48. t_directory::t_direntry::t_date remoteDate;
  49. //CTime *pFileTime; //Used when downloading and OPTION_PRESERVEDOWNLOADFILETIME is set or when LIST fails
  50. _int64 *pFileSize; //Used when LIST failes
  51. BOOL bUseAbsolutePaths;
  52. BOOL bTriedPortPasvOnce;
  53. bool askOnResumeFail;
  54. };
  55. class CFtpControlSocket::CLogonData:public CFtpControlSocket::t_operation::COpData
  56. {
  57. public:
  58. CLogonData()
  59. {
  60. waitForAsyncRequest = false;
  61. gotPassword = false;
  62. }
  63. virtual ~CLogonData()
  64. {
  65. }
  66. bool waitForAsyncRequest;
  67. bool gotPassword;
  68. };
  69. class CFtpControlSocket::CListData:public CFtpControlSocket::t_operation::COpData
  70. {
  71. public:
  72. CListData()
  73. {
  74. pDirectoryListing = 0;
  75. bTriedPortPasvOnce = FALSE;
  76. lastCmdSentCDUP = false;
  77. }
  78. virtual ~CListData()
  79. {
  80. if (pDirectoryListing)
  81. delete pDirectoryListing;
  82. }
  83. CString rawpwd;
  84. CServerPath path;
  85. CString fileName;
  86. CString subdir;
  87. BOOL bPasv;
  88. CString host;
  89. int port;
  90. int nFinish;
  91. t_directory *pDirectoryListing;
  92. BOOL bTriedPortPasvOnce;
  93. bool lastCmdSentCDUP;
  94. };
  95. class CFtpControlSocket::CListFileData:public CFtpControlSocket::t_operation::COpData
  96. {
  97. public:
  98. CListFileData()
  99. {
  100. direntry = NULL;
  101. }
  102. ~CListFileData()
  103. {
  104. delete [] direntry;
  105. }
  106. CString fileName;
  107. CString dir;
  108. CString path;
  109. CServerPath pwd;
  110. t_directory::t_direntry * direntry;
  111. };
  112. class CFtpControlSocket::CMakeDirData : public CFtpControlSocket::t_operation::COpData
  113. {
  114. public:
  115. CMakeDirData() {}
  116. virtual ~CMakeDirData() {}
  117. CServerPath path;
  118. CServerPath Current;
  119. std::list<CString> Segments;
  120. };
  121. #define MKD_INIT -1
  122. #define MKD_FINDPARENT 0
  123. #define MKD_MAKESUBDIRS 1
  124. #define MKD_CHANGETOSUBDIR 2
  125. /////////////////////////////////////////////////////////////////////////////
  126. // CFtpControlSocket
  127. std::list<CFtpControlSocket::t_ActiveList> CFtpControlSocket::m_InstanceList[2];
  128. CTime CFtpControlSocket::m_CurrentTransferTime[2] = { CTime::CreateForCurrentTime(), CTime::CreateForCurrentTime() };
  129. _int64 CFtpControlSocket::m_CurrentTransferLimit[2] = {0, 0};
  130. CCriticalSectionWrapper CFtpControlSocket::m_SpeedLimitSync;
  131. #define BUFSIZE 16384
  132. CFtpControlSocket::CFtpControlSocket(CMainThread *pMainThread, CFileZillaTools * pTools)
  133. {
  134. DebugAssert(pMainThread);
  135. m_pOwner=pMainThread;
  136. m_pTools=pTools;
  137. m_Operation.nOpMode=0;
  138. m_Operation.nOpState=-1;
  139. m_Operation.pData=0;
  140. m_pProxyLayer = NULL;
  141. m_pSslLayer = NULL;
  142. #ifndef MPEXT_NO_GSS
  143. m_pGssLayer = NULL;
  144. #endif
  145. m_pDirectoryListing=0;
  146. m_pTransferSocket=0;
  147. m_pDataFile=0;
  148. srand( (unsigned)time( NULL ) );
  149. m_bKeepAliveActive=FALSE;
  150. m_bCheckForTimeout=TRUE;
  151. m_bDidRejectCertificate = FALSE;
  152. m_bUTF8 = true;
  153. m_hasClntCmd = false;
  154. m_serverCapabilities.Clear();
  155. m_ListFile = "";
  156. m_awaitsReply = false;
  157. m_skipReply = false;
  158. m_sendBuffer = 0;
  159. m_sendBufferLen = 0;
  160. m_bProtP = false;
  161. m_mayBeMvsFilesystem = false;
  162. m_mayBeBS2000Filesystem = false;
  163. }
  164. CFtpControlSocket::~CFtpControlSocket()
  165. {
  166. DoClose();
  167. if (m_pTransferSocket)
  168. {
  169. m_pTransferSocket->Close();
  170. delete m_pTransferSocket;
  171. m_pTransferSocket=0;
  172. }
  173. if (m_pDataFile)
  174. {
  175. delete m_pDataFile;
  176. m_pDataFile=0;
  177. }
  178. Close();
  179. }
  180. void CFtpControlSocket::ShowStatus(UINT nID, int type) const
  181. {
  182. CString str;
  183. str.LoadString(nID);
  184. ShowStatus(str, type);
  185. }
  186. void CFtpControlSocket::ShowStatus(CString status, int type) const
  187. {
  188. if (!GetOptionVal(OPTION_MPEXT_LOG_SENSITIVE))
  189. {
  190. if ( status.Left(5)==L"PASS " )
  191. {
  192. int len=status.GetLength()-5;
  193. status=L"PASS ";
  194. for (int i=0;i<len;i++)
  195. status+=L"*";
  196. }
  197. else if ( status.Left(5)==L"ACCT " )
  198. {
  199. int len=status.GetLength()-5;
  200. status=L"ACCT ";
  201. for (int i=0;i<len;i++)
  202. status+=L"*";
  203. }
  204. }
  205. LogMessageRaw(type, (LPCTSTR)status);
  206. }
  207. void CFtpControlSocket::ShowTimeoutError(UINT nID) const
  208. {
  209. CString str1;
  210. str1.LoadString(IDS_ERRORMSG_TIMEOUT);
  211. CString str2;
  212. str2.LoadString(nID);
  213. CString message;
  214. message.Format(L"%s (%s)", (LPCTSTR)str1, (LPCTSTR)str2);
  215. ShowStatus(message, FZ_LOG_ERROR);
  216. }
  217. t_server CFtpControlSocket::GetCurrentServer()
  218. {
  219. return m_CurrentServer;
  220. }
  221. void CFtpControlSocket::Close()
  222. {
  223. if (m_pDirectoryListing)
  224. {
  225. delete m_pDirectoryListing;
  226. }
  227. m_pDirectoryListing=0;
  228. CAsyncSocketEx::Close();
  229. delete m_pProxyLayer;
  230. m_pProxyLayer = NULL;
  231. delete m_pSslLayer;
  232. m_pSslLayer = NULL;
  233. #ifndef MPEXT_NO_GSS
  234. delete m_pGssLayer;
  235. m_pGssLayer = NULL;
  236. #endif
  237. RemoveActiveTransfer();
  238. }
  239. BOOL CFtpControlSocket::Connect(CString hostAddress, UINT nHostPort)
  240. {
  241. hostAddress = ConvertDomainName(hostAddress);
  242. //Don't resolve host asynchronously when using proxies
  243. if (m_pProxyLayer)
  244. {
  245. return CAsyncSocketEx::Connect(hostAddress, nHostPort);
  246. }
  247. BOOL res = CAsyncSocketEx::Connect(hostAddress, nHostPort);
  248. int nLastError = WSAGetLastError();
  249. if (res || nLastError==WSAEWOULDBLOCK)
  250. {
  251. WSASetLastError(nLastError);
  252. }
  253. return res;
  254. }
  255. void CFtpControlSocket::SetDirectoryListing(t_directory *pDirectory, bool bSetWorkingDir /*=true*/)
  256. {
  257. if (m_pDirectoryListing)
  258. delete m_pDirectoryListing;
  259. m_CurrentServer=pDirectory->server;
  260. m_pDirectoryListing=new t_directory;
  261. *m_pDirectoryListing=*pDirectory;
  262. if (bSetWorkingDir)
  263. m_pOwner->SetWorkingDir(pDirectory);
  264. }
  265. /////////////////////////////////////////////////////////////////////////////
  266. // Member-Funktion CFtpControlSocket
  267. #define CONNECT_INIT -1
  268. #ifndef MPEXT_NO_GSS
  269. #define CONNECT_GSS_INIT -2
  270. #define CONNECT_GSS_AUTHDONE -3
  271. #define CONNECT_GSS_CWD -4
  272. #define CONNECT_GSS_FAILED -5
  273. #define CONNECT_GSS_NEEDPASS -6
  274. #define CONNECT_GSS_NEEDUSER -7
  275. #endif
  276. #define CONNECT_SSL_INIT -8
  277. #define CONNECT_SSL_NEGOTIATE -9
  278. #define CONNECT_TLS_NEGOTIATE -10
  279. #define CONNECT_SSL_WAITDONE -11
  280. #define CONNECT_SSL_PBSZ -12
  281. #define CONNECT_SSL_PROT -13
  282. #define CONNECT_FEAT -14
  283. #define CONNECT_SYST -15
  284. #define CONNECT_OPTSUTF8 -16
  285. #define CONNECT_CLNT -17
  286. #define CONNECT_OPTSMLST -18
  287. #define CONNECT_NEEDPASS -19
  288. #define CONNECT_HOST -20
  289. bool CFtpControlSocket::InitConnect()
  290. {
  291. USES_CONVERSION;
  292. // Reset detected capabilities
  293. m_bAnnouncesUTF8 = false;
  294. m_hasClntCmd = false;
  295. m_serverCapabilities.Clear();
  296. m_ListFile = "";
  297. m_isFileZilla = false;
  298. if (m_CurrentServer.nUTF8 == 2)
  299. m_bUTF8 = false;
  300. else
  301. m_bUTF8 = true;
  302. // Some sanity checks
  303. if (m_pOwner->IsConnected())
  304. {
  305. ShowStatus(L"Internal error: Connect called while still connected", FZ_LOG_ERROR);
  306. if (!m_Operation.nOpMode)
  307. m_Operation.nOpMode = CSMODE_CONNECT;
  308. DoClose(FZ_REPLY_CRITICALERROR);
  309. return false;
  310. }
  311. if (m_pSslLayer)
  312. {
  313. ShowStatus(L"Internal error: m_pSslLayer not zero in Connect", FZ_LOG_ERROR);
  314. DoClose(FZ_REPLY_CRITICALERROR);
  315. return false;
  316. }
  317. if (m_pProxyLayer)
  318. {
  319. ShowStatus(L"Internal error: m_pProxyLayer not zero in Connect", FZ_LOG_ERROR);
  320. DoClose(FZ_REPLY_CRITICALERROR);
  321. return false;
  322. }
  323. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT ||
  324. m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT ||
  325. m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_TLS_EXPLICIT)
  326. {
  327. m_pSslLayer = new CAsyncSslSocketLayer;
  328. AddLayer(m_pSslLayer);
  329. m_pSslLayer->SetClientCertificate(m_CurrentServer.Certificate, m_CurrentServer.PrivateKey);
  330. CString filename = GetOption(OPTION_MPEXT_CERT_STORAGE);
  331. m_pSslLayer->SetCertStorage(filename);
  332. }
  333. int nProxyType = GetOptionVal(OPTION_PROXYTYPE);
  334. if (nProxyType != PROXYTYPE_NOPROXY)
  335. {
  336. m_pProxyLayer = new CAsyncProxySocketLayer;
  337. m_pProxyLayer->SetProxy(
  338. nProxyType, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT),
  339. GetOptionVal(OPTION_PROXYUSELOGON), T2CA(GetOption(OPTION_PROXYUSER)), T2CA(GetOption(OPTION_PROXYPASS)));
  340. AddLayer(m_pProxyLayer);
  341. }
  342. #ifndef MPEXT_NO_GSS
  343. BOOL bUseGSS = FALSE;
  344. if (GetOptionVal(OPTION_USEGSS) && !m_pSslLayer)
  345. {
  346. CString GssServers=GetOption(OPTION_GSSSERVERS);
  347. LPCSTR lpszAscii=T2CA(m_CurrentServer.host);
  348. hostent *fullname=gethostbyname(lpszAscii);
  349. CString host;
  350. if (fullname)
  351. host=fullname->h_name;
  352. else
  353. host=m_CurrentServer.host;
  354. host.MakeLower();
  355. int i;
  356. while ((i=GssServers.Find(L";"))!=-1)
  357. {
  358. if ((L"."+GssServers.Left(i))==host.Right(GssServers.Left(i).GetLength()+1) || GssServers.Left(i)==host)
  359. {
  360. bUseGSS=TRUE;
  361. break;
  362. }
  363. GssServers=GssServers.Mid(i+1);
  364. }
  365. }
  366. if (bUseGSS)
  367. {
  368. m_pGssLayer = new CAsyncGssSocketLayer;
  369. AddLayer(m_pGssLayer);
  370. if (!m_pGssLayer->InitGSS())
  371. {
  372. ShowStatus(L"Unable to initialize GSS api", FZ_LOG_ERROR);
  373. DoClose(FZ_REPLY_CRITICALERROR);
  374. return false;
  375. }
  376. }
  377. #endif
  378. return true;
  379. }
  380. int CFtpControlSocket::InitConnectState()
  381. {
  382. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  383. return CONNECT_SSL_INIT;
  384. else
  385. #ifndef MPEXT_NO_GSS
  386. if (m_pGssLayer)
  387. return CONNECT_GSS_INIT;
  388. else
  389. #endif
  390. return CONNECT_INIT;
  391. }
  392. void CFtpControlSocket::Connect(t_server &server)
  393. {
  394. if (m_Operation.nOpMode)
  395. {
  396. ShowStatus(L"Internal error: m_Operation.nOpMode not zero in Connect", FZ_LOG_ERROR);
  397. m_Operation.nOpMode = CSMODE_CONNECT;
  398. DoClose(FZ_REPLY_CRITICALERROR);
  399. return;
  400. }
  401. m_Operation.nOpMode = CSMODE_CONNECT;
  402. m_CurrentServer = server;
  403. if (!InitConnect())
  404. return;
  405. if (!Create())
  406. {
  407. DoClose();
  408. return;
  409. }
  410. AsyncSelect();
  411. if (GetOptionVal(OPTION_MPEXT_HOST))
  412. {
  413. m_Operation.nOpState = CONNECT_HOST;
  414. }
  415. else
  416. {
  417. m_Operation.nOpState = InitConnectState();
  418. }
  419. if (server.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT)
  420. {
  421. if (!m_pSslLayer)
  422. {
  423. ShowStatus(L"Internal error: m_pSslLayer not initialized", FZ_LOG_ERROR);
  424. DoClose(FZ_REPLY_CRITICALERROR);
  425. return;
  426. }
  427. int res = m_pSslLayer->InitSSLConnection(true, NULL,
  428. GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE), server.host,
  429. m_pTools);
  430. if (res == SSL_FAILURE_INITSSL)
  431. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  432. if (res)
  433. {
  434. DoClose();
  435. return;
  436. }
  437. }
  438. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  439. int port;
  440. CString buf,temp;
  441. // are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0)
  442. CString fwhost;
  443. int fwport;
  444. if(!logontype)
  445. {
  446. temp=server.host;
  447. port=server.port;
  448. }
  449. else
  450. {
  451. fwhost=GetOption(OPTION_FWHOST);
  452. fwport=GetOptionVal(OPTION_FWPORT);
  453. temp=fwhost;
  454. port=fwport;
  455. if(fwport!=21)
  456. fwhost.Format( L"%s:%d", (LPCTSTR)fwhost, fwport); // add port to fwhost (only if port is not 21)
  457. }
  458. CString hostname = server.host;
  459. if(server.port!=21)
  460. hostname.Format( L"%s:%d", (LPCTSTR)hostname, server.port); // add port to hostname (only if port is not 21)
  461. CString str;
  462. str.Format(IDS_STATUSMSG_CONNECTING, (LPCTSTR)hostname);
  463. ShowStatus(str, FZ_LOG_STATUS);
  464. if (!Connect(temp, port))
  465. {
  466. if (WSAGetLastError() != WSAEWOULDBLOCK)
  467. {
  468. DoClose();
  469. return;
  470. }
  471. else
  472. {
  473. LogMessage(FZ_LOG_INFO, L"Connection pending");
  474. }
  475. }
  476. else
  477. {
  478. LogMessage(FZ_LOG_INFO, L"Connected");
  479. }
  480. m_ServerName = logontype?fwhost:hostname;
  481. m_LastRecvTime = m_LastSendTime = CTime::CreateForCurrentTime();
  482. m_Operation.pData = new CLogonData();
  483. }
  484. static CString NormalizePass(const CString & pass)
  485. {
  486. return CString(NormalizeString(UnicodeString(T2CW(pass))).c_str());
  487. }
  488. void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/)
  489. {
  490. int logontype =
  491. #ifndef MPEXT_NO_GSS
  492. m_pGssLayer ? 0 :
  493. #endif
  494. GetOptionVal(OPTION_LOGONTYPE);
  495. const int LO = -2, ER = -1;
  496. CString buf, temp;
  497. const int NUMLOGIN = 9; // currently supports 9 different login sequences
  498. int logonseq[NUMLOGIN][20] = {
  499. // this array stores all of the logon sequences for the various firewalls
  500. // in blocks of 3 nums. 1st num is command to send, 2nd num is next point in logon sequence array
  501. // if 200 series response is rec'd from server as the result of the command, 3rd num is next
  502. // point in logon sequence if 300 series rec'd
  503. {0,LO,3, 1,LO,6, 12,LO,ER}, // no firewall
  504. {3,6,3, 4,6,ER, 5,9,9, 0,LO,12, 1,LO,15, 12,LO,ER}, // SITE hostname
  505. {3,6,3, 4,6,ER, 6,LO,9, 1,LO,12, 12,LO,ER}, // USER after logon
  506. {7,3,3, 0,LO,6, 1,LO,9, 12,LO,ER}, //proxy OPEN
  507. {3,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, // Transparent
  508. {6,LO,3, 1,LO,6, 12,LO,ER}, // USER remoteID@remotehost
  509. {8,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, //USER fireID@remotehost
  510. {9,ER,3, 1,LO,6, 2,LO,ER}, //USER remoteID@remotehost fireID
  511. {10,LO,3,11,LO,6,2,LO,ER} // USER remoteID@fireID@remotehost
  512. };
  513. if (m_Operation.nOpState == CONNECT_SSL_INIT)
  514. {
  515. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT)
  516. {
  517. if (!SendAuthSsl())
  518. {
  519. return;
  520. }
  521. }
  522. else
  523. {
  524. if (!Send("AUTH TLS"))
  525. return;
  526. m_Operation.nOpState = CONNECT_TLS_NEGOTIATE;
  527. }
  528. return;
  529. }
  530. else if ((m_Operation.nOpState == CONNECT_SSL_NEGOTIATE) ||
  531. (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE))
  532. {
  533. int res = GetReplyCode();
  534. if (res!=2 && res!=3)
  535. {
  536. if (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE)
  537. {
  538. // Try to fall back to AUTH SSL
  539. if (!SendAuthSsl())
  540. {
  541. return;
  542. }
  543. }
  544. else
  545. {
  546. DoClose();
  547. }
  548. return;
  549. }
  550. else
  551. {
  552. if (!m_pSslLayer)
  553. {
  554. ShowStatus(L"Internal error: m_pSslLayer not initialized", FZ_LOG_ERROR);
  555. DoClose(FZ_REPLY_CRITICALERROR);
  556. return;
  557. }
  558. int res = m_pSslLayer->InitSSLConnection(true, NULL,
  559. GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE), m_CurrentServer.host,
  560. m_pTools);
  561. if (res == SSL_FAILURE_INITSSL)
  562. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  563. if (res)
  564. {
  565. DoClose();
  566. return;
  567. }
  568. }
  569. m_Operation.nOpState = CONNECT_SSL_WAITDONE;
  570. return;
  571. }
  572. else if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  573. {
  574. m_Operation.nOpState = CONNECT_INIT;
  575. }
  576. else if (m_Operation.nOpState == CONNECT_SSL_PBSZ)
  577. {
  578. if (!Send(L"PROT P"))
  579. return;
  580. m_Operation.nOpState = CONNECT_SSL_PROT;
  581. return;
  582. }
  583. else if (m_Operation.nOpState == CONNECT_SSL_PROT)
  584. {
  585. int code = GetReplyCode();
  586. if (code == 2 || code == 3)
  587. m_bProtP = true;
  588. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  589. m_pOwner->SetConnected(TRUE);
  590. ResetOperation(FZ_REPLY_OK);
  591. return;
  592. }
  593. #ifndef MPEXT_NO_GSS
  594. else
  595. if (m_Operation.nOpState==CONNECT_GSS_FAILED ||
  596. m_Operation.nOpState == CONNECT_GSS_NEEDPASS ||
  597. m_Operation.nOpState == CONNECT_GSS_NEEDUSER)
  598. {
  599. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  600. {
  601. //Incoming reply from server during async is not allowed
  602. DoClose();
  603. return;
  604. }
  605. }
  606. #endif
  607. else if (m_Operation.nOpState == CONNECT_HOST)
  608. {
  609. if (Send(L"HOST " + m_CurrentServer.host))
  610. {
  611. m_Operation.nOpState = InitConnectState();
  612. return;
  613. }
  614. }
  615. else if (m_Operation.nOpState == CONNECT_OPTSMLST)
  616. {
  617. int code = GetReplyCode();
  618. if (code != 2 && code != 3)
  619. m_serverCapabilities.SetCapability(mlsd_command, no);
  620. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  621. m_pOwner->SetConnected(TRUE);
  622. ResetOperation(FZ_REPLY_OK);
  623. return;
  624. }
  625. else if (m_Operation.nOpState == CONNECT_FEAT)
  626. {
  627. std::string facts;
  628. if (m_serverCapabilities.GetCapabilityString(mlsd_command, &facts) == yes)
  629. {
  630. ftp_capabilities_t cap = m_serverCapabilities.GetCapabilityString(opts_mlst_command);
  631. if (cap == unknown)
  632. {
  633. std::transform(facts.begin(), facts.end(), facts.begin(), ::towlower);
  634. bool had_unset = false;
  635. std::string opts_facts;
  636. // Create a list of all facts understood by both FZ and the server.
  637. // Check if there's any supported fact not enabled by default, should that
  638. // be the case we need to send OPTS MLST
  639. while (!facts.empty())
  640. {
  641. size_t delim = facts.find_first_of(';');
  642. if (delim == -1)
  643. break;
  644. if (!delim)
  645. {
  646. facts = facts.substr(1, std::string::npos);
  647. continue;
  648. }
  649. bool enabled = false;
  650. std::string fact;
  651. if (facts[delim - 1] == '*')
  652. {
  653. if (delim == 1)
  654. {
  655. facts = facts.substr(delim + 1, std::string::npos);
  656. continue;
  657. }
  658. enabled = true;
  659. fact = facts.substr(0, delim - 1);
  660. }
  661. else
  662. {
  663. enabled = false;
  664. fact = facts.substr(0, delim);
  665. }
  666. facts = facts.substr(delim + 1, std::string::npos);
  667. if (!strcmp(fact.c_str(), "type") ||
  668. !strcmp(fact.c_str(), "size") ||
  669. !strcmp(fact.c_str(), "modify") ||
  670. !strcmp(fact.c_str(), "create") ||
  671. !strcmp(fact.c_str(), "perm") ||
  672. !strcmp(fact.c_str(), "unix.mode") ||
  673. !strcmp(fact.c_str(), "unix.owner") ||
  674. !strcmp(fact.c_str(), "unix.user") ||
  675. !strcmp(fact.c_str(), "unix.group") ||
  676. !strcmp(fact.c_str(), "unix.uid") ||
  677. !strcmp(fact.c_str(), "unix.gid"))
  678. {
  679. had_unset |= !enabled;
  680. opts_facts += fact.c_str();
  681. opts_facts += ";";
  682. }
  683. }
  684. if (had_unset)
  685. {
  686. m_serverCapabilities.SetCapability(opts_mlst_command, yes, opts_facts);
  687. }
  688. else
  689. {
  690. m_serverCapabilities.SetCapability(opts_mlst_command, no);
  691. }
  692. }
  693. }
  694. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_CAPABILITIES, 0), (LPARAM)&m_serverCapabilities);
  695. if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8)
  696. m_bUTF8 = false;
  697. if (m_hasClntCmd)
  698. {
  699. // Some servers refuse to enable UTF8 if client does not send CLNT command
  700. // to fix compatibility with Internet Explorer, but in the process breaking
  701. // compatibility with other clients.
  702. // Rather than forcing MS to fix Internet Explorer, letting other clients
  703. // suffer is a questionable decision in my opinion.
  704. if (Send(CString(L"CLNT ") + m_pTools->GetClientString().c_str()))
  705. m_Operation.nOpState = CONNECT_CLNT;
  706. return;
  707. }
  708. if (m_bUTF8 && !m_isFileZilla)
  709. {
  710. // Handle servers that disobey RFC 2640 that have UTF8 in the FEAT
  711. // response but do not use UTF8 unless OPTS UTF8 ON gets send.
  712. // However these servers obey a conflicting ietf draft:
  713. // https://datatracker.ietf.org/doc/html/draft-ietf-ftpext-utf-8-option-00
  714. // servers are, amongst others, G6 FTP Server and RaidenFTPd.
  715. if (Send(L"OPTS UTF8 ON"))
  716. m_Operation.nOpState = CONNECT_OPTSUTF8;
  717. return;
  718. }
  719. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  720. {
  721. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  722. Send(L"PBSZ 0");
  723. return;
  724. }
  725. if (m_serverCapabilities.GetCapability(mlsd_command) == yes)
  726. {
  727. std::string args;
  728. // this is never true, see comment is DiscardLine
  729. if (m_serverCapabilities.GetCapabilityString(opts_mlst_command, &args) == yes &&
  730. !args.empty())
  731. {
  732. m_Operation.nOpState = CONNECT_OPTSMLST;
  733. Send("OPTS MLST " + CString(args.c_str()));
  734. return;
  735. }
  736. }
  737. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  738. m_pOwner->SetConnected(TRUE);
  739. ResetOperation(FZ_REPLY_OK);
  740. return;
  741. }
  742. else if (m_Operation.nOpState == CONNECT_CLNT)
  743. {
  744. // See above why we send this command
  745. if (Send(L"OPTS UTF8 ON"))
  746. m_Operation.nOpState = CONNECT_OPTSUTF8;
  747. return;
  748. }
  749. else if (m_Operation.nOpState == CONNECT_OPTSUTF8)
  750. {
  751. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  752. {
  753. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  754. Send(L"PBSZ 0");
  755. return;
  756. }
  757. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  758. m_pOwner->SetConnected(TRUE);
  759. ResetOperation(FZ_REPLY_OK);
  760. return;
  761. }
  762. else if (m_Operation.nOpState == CONNECT_SYST)
  763. {
  764. if (GetReplyCode() == 2)
  765. {
  766. const RawByteString reply = m_RecvBuffer.front();
  767. if (reply.Length() > 7 && reply.SubString(4, 4) == " MVS")
  768. m_mayBeMvsFilesystem = true;
  769. else if (reply.Length() >= 11 && reply.SubString(4, 8) == " BS-2000")
  770. m_mayBeBS2000Filesystem = true;
  771. // This is probably wrong
  772. if (reply.SubString(1, 4) == "VMS ")
  773. {
  774. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  775. }
  776. if (reply.Pos("FileZilla") > 0)
  777. m_isFileZilla = true;
  778. }
  779. if (Send(L"FEAT"))
  780. m_Operation.nOpState = CONNECT_FEAT;
  781. return;
  782. }
  783. else if (!bSkipReply)
  784. {
  785. int res = GetReplyCode();
  786. if (res != 2 && res != 3 && m_Operation.nOpState >= 0) // get initial connect msg off server
  787. {
  788. int nError = 0;
  789. if (m_bUTF8 && m_CurrentServer.nUTF8 != 1)
  790. {
  791. // Fall back to local charset for the case that the server might not
  792. // support UTF8 and the login data contains non-ascii characters.
  793. bool asciiOnly = true;
  794. for (int i = 0; i < m_CurrentServer.user.GetLength(); i++)
  795. if (m_CurrentServer.user.GetAt(i) > 127)
  796. asciiOnly = false;
  797. CString pass = NormalizePass(m_CurrentServer.pass);
  798. for (int i = 0; i < pass.GetLength(); i++)
  799. if (pass.GetAt(i) > 127)
  800. asciiOnly = false;
  801. for (int i = 0; i < m_CurrentServer.account.GetLength(); i++)
  802. if (m_CurrentServer.account.GetAt(i) > 127)
  803. asciiOnly = false;
  804. if (!asciiOnly)
  805. {
  806. ShowStatus(L"Login data contains non-ascii characters and server might not be UTF-8 aware. Trying local charset.", FZ_LOG_STATUS);
  807. m_bUTF8 = false;
  808. m_Operation.nOpState = CONNECT_INIT;
  809. }
  810. else
  811. nError = FZ_REPLY_ERROR;
  812. }
  813. else
  814. nError = FZ_REPLY_ERROR;
  815. if (nError)
  816. {
  817. if (res==5 && logonseq[logontype][m_Operation.nOpState]==1)
  818. nError|=FZ_REPLY_CRITICALERROR;
  819. DoClose(nError);
  820. return;
  821. }
  822. }
  823. }
  824. CString hostname = m_CurrentServer.host;
  825. if (m_CurrentServer.port != 21)
  826. hostname.Format(hostname+ L":%d", m_CurrentServer.port); // add port to hostname (only if port is not 21)
  827. #ifndef MPEXT_NO_GSS
  828. USES_CONVERSION;
  829. //**** GSS Authentication ****
  830. if (m_Operation.nOpState==CONNECT_GSS_INIT) //authenticate
  831. {
  832. int i = m_pGssLayer->GetClientAuth(T2CA(m_CurrentServer.host));
  833. if (i==-1)
  834. m_Operation.nOpState = CONNECT_GSS_AUTHDONE;
  835. else if (i != GSSAPI_AUTHENTICATION_SUCCEEDED)
  836. {
  837. m_Operation.nOpState = CONNECT_GSS_FAILED;
  838. CAsyncRequestData *pData=new CAsyncRequestData;
  839. pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  840. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  841. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  842. {
  843. delete pData;
  844. }
  845. else
  846. {
  847. m_bCheckForTimeout = FALSE;
  848. }
  849. }
  850. else
  851. {
  852. // we got authentication, we need to check whether we have forwardable tickets
  853. if (Send(L"CWD ."))
  854. m_Operation.nOpState = CONNECT_GSS_CWD;
  855. }
  856. return;
  857. }
  858. else if (m_Operation.nOpState == CONNECT_GSS_AUTHDONE)
  859. {
  860. if (!m_pGssLayer->AuthSuccessful())
  861. {
  862. m_Operation.nOpState = CONNECT_GSS_FAILED;
  863. CAsyncRequestData *pData=new CAsyncRequestData;
  864. pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  865. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  866. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  867. {
  868. delete pData;
  869. }
  870. else
  871. {
  872. m_bCheckForTimeout = FALSE;
  873. }
  874. return;
  875. }
  876. else
  877. {
  878. // we got authentication, we need to check whether we have forwardable tickets
  879. if (Send(L"CWD ."))
  880. m_Operation.nOpState = CONNECT_GSS_CWD;
  881. return;
  882. }
  883. }
  884. else if (m_Operation.nOpState == CONNECT_GSS_CWD)
  885. { // authentication succeeded, we're now get the response to the CWD command
  886. if (GetReplyCode() == 2) // we're logged on
  887. {
  888. if (Send(L"SYST"))
  889. m_Operation.nOpState = CONNECT_SYST;
  890. return;
  891. }
  892. else
  893. {
  894. //GSS authentication complete but we still have to go through the standard logon procedure
  895. m_Operation.nOpState = CONNECT_INIT;
  896. }
  897. }
  898. #endif
  899. if (m_Operation.nOpState==CONNECT_INIT)
  900. {
  901. if (logontype)
  902. {
  903. CString str;
  904. str.Format(IDS_STATUSMSG_FWCONNECT,(LPCTSTR)hostname);
  905. ShowStatus(str,FZ_LOG_STATUS);
  906. }
  907. m_Operation.nOpState++;
  908. }
  909. else if (m_Operation.nOpState >= 0 && !bSkipReply)
  910. {
  911. m_Operation.nOpState=logonseq[logontype][m_Operation.nOpState+GetReplyCode()-1]; //get next command from array
  912. switch(m_Operation.nOpState)
  913. {
  914. case ER: // ER means summat has gone wrong
  915. DoClose();
  916. return;
  917. case LO: //LO means we are logged on
  918. if (Send(L"SYST"))
  919. m_Operation.nOpState = CONNECT_SYST;
  920. return;
  921. }
  922. }
  923. // go through appropriate logon procedure
  924. #ifndef MPEXT_NO_GSS
  925. int i = logonseq[logontype][m_Operation.nOpState];
  926. if (m_pGssLayer)
  927. {
  928. if ((i == 0 || i == 6 || i == 9 || i == 10) &&
  929. (m_CurrentServer.user == L"anonymous" || m_CurrentServer.user == L""))
  930. {
  931. //Extract user from kerberos ticket
  932. char str[256];
  933. if (m_pGssLayer->GetUserFromKrbTicket(str))
  934. m_CurrentServer.user = str;
  935. if (m_CurrentServer.user == L"")
  936. {
  937. CGssNeedUserRequestData *pData = new CGssNeedUserRequestData;
  938. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  939. pData->nOldOpState = m_Operation.nOpState;
  940. m_Operation.nOpState = CONNECT_GSS_NEEDUSER;
  941. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData))
  942. {
  943. delete pData;
  944. }
  945. else
  946. {
  947. m_bCheckForTimeout = FALSE;
  948. }
  949. return;
  950. }
  951. }
  952. else if ((i == 1 || i == 11) && (m_CurrentServer.pass == GetOption(OPTION_ANONPWD) || m_CurrentServer.pass == ""))
  953. {
  954. CGssNeedPassRequestData *pData=new CGssNeedPassRequestData;
  955. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  956. pData->nOldOpState = m_Operation.nOpState;
  957. m_Operation.nOpState = CONNECT_GSS_NEEDPASS;
  958. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData))
  959. {
  960. delete pData;
  961. }
  962. else
  963. {
  964. m_bCheckForTimeout = FALSE;
  965. }
  966. return;
  967. }
  968. }
  969. #endif
  970. CLogonData *pData = static_cast<CLogonData *>(m_Operation.pData);
  971. bool needpass = (m_CurrentServer.pass == GetOption(OPTION_ANONPWD)) || (m_CurrentServer.pass == L"");
  972. switch(logonseq[logontype][m_Operation.nOpState])
  973. {
  974. case 0:
  975. temp=L"USER "+m_CurrentServer.user;
  976. break;
  977. case 1:
  978. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  979. {
  980. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  981. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  982. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  983. m_Operation.nOpState = CONNECT_NEEDPASS;
  984. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  985. {
  986. delete pNeedPassRequestData;
  987. ResetOperation(FZ_REPLY_ERROR);
  988. }
  989. else
  990. {
  991. m_bCheckForTimeout = FALSE;
  992. }
  993. pData->waitForAsyncRequest = true;
  994. return;
  995. }
  996. else if (!needpass || pData->gotPassword)
  997. {
  998. temp=L"PASS "+NormalizePass(m_CurrentServer.pass);
  999. }
  1000. else
  1001. {
  1002. return;
  1003. }
  1004. break;
  1005. case 2:
  1006. temp=L"ACCT "+GetOption(OPTION_FWPASS);
  1007. break;
  1008. case 3:
  1009. temp=L"USER "+GetOption(OPTION_FWUSER);
  1010. break;
  1011. case 4:
  1012. temp=L"PASS "+GetOption(OPTION_FWPASS);
  1013. break;
  1014. case 5:
  1015. temp=L"SITE "+hostname;
  1016. break;
  1017. case 6:
  1018. temp=L"USER "+m_CurrentServer.user+L"@"+hostname;
  1019. break;
  1020. case 7:
  1021. temp=L"OPEN "+hostname;
  1022. break;
  1023. case 8:
  1024. temp=L"USER "+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1025. break;
  1026. case 9:
  1027. temp=L"USER "+m_CurrentServer.user+L"@"+hostname+L" "+GetOption(OPTION_FWUSER);
  1028. break;
  1029. case 10:
  1030. temp=L"USER "+m_CurrentServer.user+L"@"+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1031. break;
  1032. case 11:
  1033. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  1034. {
  1035. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  1036. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  1037. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  1038. m_Operation.nOpState = CONNECT_NEEDPASS;
  1039. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  1040. {
  1041. delete pNeedPassRequestData;
  1042. ResetOperation(FZ_REPLY_ERROR);
  1043. }
  1044. else
  1045. {
  1046. m_bCheckForTimeout = FALSE;
  1047. }
  1048. pData->waitForAsyncRequest = true;
  1049. return;
  1050. }
  1051. else if (!needpass || pData->gotPassword)
  1052. {
  1053. temp=L"PASS "+NormalizePass(m_CurrentServer.pass)+L"@"+GetOption(OPTION_FWPASS);
  1054. }
  1055. else
  1056. {
  1057. return;
  1058. }
  1059. break;
  1060. case 12:
  1061. if (m_CurrentServer.account == L"")
  1062. temp = L"ACCT default";
  1063. else
  1064. temp = L"ACCT " + m_CurrentServer.account;
  1065. break;
  1066. }
  1067. // send command, get response
  1068. if(!Send(temp))
  1069. return;
  1070. }
  1071. BOOL CFtpControlSocket::SendAuthSsl()
  1072. {
  1073. if (!Send("AUTH SSL"))
  1074. return false;
  1075. m_Operation.nOpState = CONNECT_SSL_NEGOTIATE;
  1076. return true;
  1077. }
  1078. #define BUFFERSIZE 4096
  1079. void CFtpControlSocket::OnReceive(int nErrorCode)
  1080. {
  1081. m_LastRecvTime = CTime::CreateForCurrentTime();
  1082. if (!m_pOwner->IsConnected())
  1083. {
  1084. if (!m_Operation.nOpMode)
  1085. {
  1086. LogMessage(FZ_LOG_INFO, L"Socket has been closed, don't process receive" );
  1087. return;
  1088. }
  1089. m_MultiLine = "";
  1090. CString str;
  1091. str.Format(IDS_STATUSMSG_CONNECTEDWITH, (LPCTSTR)m_ServerName);
  1092. ShowStatus(str, FZ_LOG_PROGRESS);
  1093. m_pOwner->SetConnected(TRUE);
  1094. }
  1095. char *buffer = new char[BUFFERSIZE];
  1096. int numread = Receive(buffer, BUFFERSIZE);
  1097. if (numread == SOCKET_ERROR)
  1098. {
  1099. delete [] buffer;
  1100. buffer = NULL;
  1101. int Error = GetLastError();
  1102. if (Error != WSAEWOULDBLOCK)
  1103. {
  1104. LogError(Error);
  1105. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  1106. DoClose();
  1107. }
  1108. else
  1109. {
  1110. LogSocketMessageRaw(FZ_LOG_INFO, L"No data to read");
  1111. }
  1112. return;
  1113. }
  1114. if (!numread)
  1115. {
  1116. delete [] buffer;
  1117. buffer = NULL;
  1118. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  1119. DoClose();
  1120. }
  1121. if (LoggingMessageType(FZ_LOG_INFO))
  1122. {
  1123. CString str;
  1124. str.Format(L"Read %d bytes", numread);
  1125. LogSocketMessageRaw(FZ_LOG_INFO, str);
  1126. }
  1127. for (int i=0; i < numread; i++)
  1128. {
  1129. if ((buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == 0))
  1130. {
  1131. if (!m_RecvBuffer.empty() && m_RecvBuffer.back() != "")
  1132. {
  1133. USES_CONVERSION;
  1134. if (m_bUTF8)
  1135. {
  1136. // convert from UTF-8 to ANSI
  1137. LPCSTR utf8 = m_RecvBuffer.back().c_str();
  1138. if (DetectUTF8Encoding(RawByteString(utf8)) == etANSI)
  1139. {
  1140. if (m_CurrentServer.nUTF8 != 1)
  1141. {
  1142. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  1143. m_bUTF8 = false;
  1144. }
  1145. ShowStatus(A2CT(utf8), FZ_LOG_REPLY);
  1146. }
  1147. else
  1148. {
  1149. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  1150. if (!len)
  1151. m_RecvBuffer.back() = "";
  1152. else
  1153. {
  1154. LPWSTR p1 = new WCHAR[len + 1];
  1155. MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
  1156. ShowStatus(W2CT(p1), FZ_LOG_REPLY);
  1157. delete [] p1;
  1158. }
  1159. }
  1160. }
  1161. else
  1162. {
  1163. ShowStatus(A2CT(m_RecvBuffer.back().c_str()), FZ_LOG_REPLY);
  1164. }
  1165. // Check for multi-line responses
  1166. // Partially duplicated in TFTPFileSystem::HandleReplyStatus
  1167. if (m_RecvBuffer.back().Length() > 3)
  1168. {
  1169. if (m_MultiLine != "")
  1170. {
  1171. if (m_RecvBuffer.back().SubString(1, 4) != m_MultiLine)
  1172. {
  1173. RawByteString line = m_RecvBuffer.back();
  1174. if (line.SubString(1, 4) == m_MultiLine.SubString(1, 3) + '-')
  1175. {
  1176. line = line.SubString(5, line.Length() - 4);
  1177. }
  1178. DiscardLine(line);
  1179. m_RecvBuffer.pop_back();
  1180. }
  1181. else // end of multi-line found
  1182. {
  1183. m_MultiLine = "";
  1184. LPARAM lParam = 0;
  1185. #ifdef _DEBUG
  1186. lParam = GetTickCount();
  1187. #endif
  1188. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, lParam);
  1189. }
  1190. }
  1191. // start of new multi-line
  1192. else if (m_RecvBuffer.back()[4] == '-')
  1193. {
  1194. // DDD<SP> is the end of a multi-line response
  1195. m_MultiLine = m_RecvBuffer.back().SubString(1, 3) + ' ';
  1196. m_RecvBuffer.pop_back();
  1197. }
  1198. else
  1199. {
  1200. LPARAM lParam = 0;
  1201. #ifdef _DEBUG
  1202. lParam = GetTickCount();
  1203. #endif
  1204. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, lParam);
  1205. }
  1206. }
  1207. else
  1208. {
  1209. m_RecvBuffer.pop_back();
  1210. }
  1211. m_RecvBuffer.push_back("");
  1212. }
  1213. }
  1214. else
  1215. {
  1216. //The command may only be 2000 chars long. This ensures that a malicious user can't
  1217. //send extremely large commands to fill the memory of the server
  1218. if (m_RecvBuffer.empty())
  1219. m_RecvBuffer.push_back("");
  1220. if (m_RecvBuffer.back().Length() < 2000)
  1221. m_RecvBuffer.back() += buffer[i];
  1222. }
  1223. }
  1224. delete [] buffer;
  1225. }
  1226. void CFtpControlSocket::ProcessReply()
  1227. {
  1228. if (m_RecvBuffer.empty())
  1229. return;
  1230. if (m_awaitsReply)
  1231. {
  1232. if (m_sendBuffer)
  1233. TriggerEvent(FD_WRITE);
  1234. m_awaitsReply = false;
  1235. }
  1236. CString reply = GetReply();
  1237. if ( reply == L"" )
  1238. return;
  1239. // After Cancel, we might have to skip a reply
  1240. if (m_skipReply)
  1241. {
  1242. m_skipReply = false;
  1243. m_RecvBuffer.pop_front();
  1244. return;
  1245. }
  1246. if (m_bKeepAliveActive)
  1247. {
  1248. m_bKeepAliveActive = FALSE;
  1249. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID,FZAPI_THREADMSG_POSTKEEPALIVE,0);
  1250. }
  1251. else if (m_Operation.nOpMode&CSMODE_CONNECT)
  1252. LogOnToServer();
  1253. else if (m_Operation.nOpMode& (CSMODE_COMMAND|CSMODE_CHMOD) )
  1254. {
  1255. if (GetReplyCode()== 2 || GetReplyCode()== 3)
  1256. ResetOperation(FZ_REPLY_OK);
  1257. else
  1258. ResetOperation(FZ_REPLY_ERROR);
  1259. }
  1260. else if (m_Operation.nOpMode&CSMODE_TRANSFER)
  1261. {
  1262. FileTransfer(0);
  1263. }
  1264. else if (m_Operation.nOpMode&CSMODE_LIST)
  1265. List(FALSE);
  1266. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  1267. ListFile(L"", CServerPath());
  1268. else if (m_Operation.nOpMode&CSMODE_DELETE)
  1269. Delete( L"",CServerPath(), false);
  1270. else if (m_Operation.nOpMode&CSMODE_RMDIR)
  1271. RemoveDir( L"",CServerPath());
  1272. else if (m_Operation.nOpMode&CSMODE_MKDIR)
  1273. MakeDir(CServerPath());
  1274. else if (m_Operation.nOpMode&CSMODE_RENAME)
  1275. Rename(L"", L"", CServerPath(), CServerPath());
  1276. if (!m_RecvBuffer.empty())
  1277. m_RecvBuffer.pop_front();
  1278. }
  1279. void CFtpControlSocket::OnConnect(int nErrorCode)
  1280. {
  1281. if (!m_Operation.nOpMode)
  1282. {
  1283. if (!m_pOwner->IsConnected())
  1284. DoClose();
  1285. return;
  1286. }
  1287. if (!nErrorCode)
  1288. {
  1289. if (!m_pOwner->IsConnected())
  1290. {
  1291. m_MultiLine = "";
  1292. m_pOwner->SetConnected(TRUE);
  1293. CString str;
  1294. str.Format(
  1295. m_pSslLayer ? IDS_STATUSMSG_CONNECTEDWITHSSL : IDS_STATUSMSG_CONNECTEDWITH,
  1296. (LPCTSTR)m_ServerName);
  1297. ShowStatus(str,FZ_LOG_PROGRESS);
  1298. }
  1299. }
  1300. else
  1301. {
  1302. if (nErrorCode == WSAHOST_NOT_FOUND)
  1303. {
  1304. CString str;
  1305. str.Format(IDS_ERRORMSG_CANTRESOLVEHOST2, (LPCTSTR)m_ServerName);
  1306. ShowStatus(str, FZ_LOG_ERROR);
  1307. }
  1308. else
  1309. {
  1310. TCHAR Buffer[255];
  1311. int Len = FormatMessage(
  1312. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1313. NULL, nErrorCode, 0, Buffer, LENOF(Buffer), NULL);
  1314. while ((Len > 0) && ((Buffer[Len - 1] >= 0) && (Buffer[Len - 1] <= 32)))
  1315. {
  1316. --Len;
  1317. }
  1318. ShowStatus(CString(Buffer, Len), FZ_LOG_ERROR);
  1319. }
  1320. DoClose();
  1321. }
  1322. }
  1323. BOOL CFtpControlSocket::Send(CString str)
  1324. {
  1325. USES_CONVERSION;
  1326. ShowStatus(str, FZ_LOG_COMMAND);
  1327. str += L"\r\n";
  1328. int res = 0;
  1329. if (m_bUTF8)
  1330. {
  1331. LPCWSTR unicode = T2CW(str);
  1332. int len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, 0, 0, 0, 0);
  1333. if (!len)
  1334. {
  1335. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1336. DoClose();
  1337. return FALSE;
  1338. }
  1339. char* utf8 = new char[len + 1];
  1340. WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len + 1, 0, 0);
  1341. int sendLen = strlen(utf8);
  1342. if (!m_awaitsReply && !m_sendBuffer)
  1343. res = CAsyncSocketEx::Send(utf8, strlen(utf8));
  1344. else
  1345. res = -2;
  1346. if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
  1347. {
  1348. delete [] utf8;
  1349. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1350. DoClose();
  1351. return FALSE;
  1352. }
  1353. if (res != sendLen)
  1354. {
  1355. if (res < 0)
  1356. res = 0;
  1357. if (!m_sendBuffer)
  1358. {
  1359. m_sendBuffer = new char[sendLen - res];
  1360. memcpy(m_sendBuffer, utf8 + res, sendLen - res);
  1361. m_sendBufferLen = sendLen - res;
  1362. }
  1363. else
  1364. {
  1365. char* tmp = new char[m_sendBufferLen + sendLen - res];
  1366. memcpy(tmp, m_sendBuffer, m_sendBufferLen);
  1367. memcpy(tmp + m_sendBufferLen, utf8 + res, sendLen - res);
  1368. delete [] m_sendBuffer;
  1369. m_sendBuffer = tmp;
  1370. m_sendBufferLen += sendLen - res;
  1371. }
  1372. }
  1373. delete [] utf8;
  1374. }
  1375. else
  1376. {
  1377. LPCSTR lpszAsciiSend = T2CA(str);
  1378. int sendLen = strlen(lpszAsciiSend);
  1379. if (!m_awaitsReply && !m_sendBuffer)
  1380. res = CAsyncSocketEx::Send(lpszAsciiSend, strlen(lpszAsciiSend));
  1381. else
  1382. res = -2;
  1383. if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
  1384. {
  1385. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1386. DoClose();
  1387. return FALSE;
  1388. }
  1389. if (res != sendLen)
  1390. {
  1391. if (res < 0)
  1392. res = 0;
  1393. if (!m_sendBuffer)
  1394. {
  1395. m_sendBuffer = new char[sendLen - res];
  1396. memcpy(m_sendBuffer, lpszAsciiSend, sendLen - res);
  1397. m_sendBufferLen = sendLen - res;
  1398. }
  1399. else
  1400. {
  1401. char* tmp = new char[m_sendBufferLen + sendLen - res];
  1402. memcpy(tmp, m_sendBuffer, m_sendBufferLen);
  1403. memcpy(tmp + m_sendBufferLen, lpszAsciiSend + res, sendLen - res);
  1404. delete [] m_sendBuffer;
  1405. m_sendBuffer = tmp;
  1406. m_sendBufferLen += sendLen - res;
  1407. }
  1408. }
  1409. }
  1410. if (res > 0)
  1411. {
  1412. m_awaitsReply = true;
  1413. m_LastSendTime = CTime::CreateForCurrentTime();
  1414. // Count timeout since the last request, not only since the last received data
  1415. // otherwise we may happen to timeout immediately after sending request if
  1416. // CheckForTimeout occurs in between and we haven't received any data for a while
  1417. m_LastRecvTime = m_LastSendTime;
  1418. }
  1419. return TRUE;
  1420. }
  1421. int CFtpControlSocket::TryGetReplyCode()
  1422. {
  1423. if (m_RecvBuffer.empty())
  1424. return 0;
  1425. RawByteString str = m_RecvBuffer.front();
  1426. if (str == "")
  1427. {
  1428. return -1;
  1429. }
  1430. else if ((str[1] < '1') || (str[1] > '9'))
  1431. {
  1432. UnicodeString Error = FMTLOAD(FTP_MALFORMED_RESPONSE, (UnicodeString(str)));
  1433. LogMessageRaw(FZ_LOG_WARNING, Error.c_str());
  1434. return 0;
  1435. }
  1436. else
  1437. {
  1438. return str[1]-'0';
  1439. }
  1440. }
  1441. int CFtpControlSocket::GetReplyCode()
  1442. {
  1443. int Result = TryGetReplyCode();
  1444. if (Result < 0)
  1445. {
  1446. UnicodeString Error = FMTLOAD(FTP_MALFORMED_RESPONSE, (UnicodeString()));
  1447. LogMessageRaw(FZ_LOG_WARNING, Error.c_str());
  1448. Result = 0;
  1449. }
  1450. return Result;
  1451. }
  1452. void CFtpControlSocket::DoClose(int nError /*=0*/)
  1453. {
  1454. LogMessage(FZ_LOG_INFO, L"Connection closed");
  1455. m_bCheckForTimeout=TRUE;
  1456. m_pOwner->SetConnected(FALSE);
  1457. m_bKeepAliveActive=FALSE;
  1458. if (nError & FZ_REPLY_CRITICALERROR)
  1459. nError |= FZ_REPLY_ERROR;
  1460. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED|nError);
  1461. m_RecvBuffer.clear();
  1462. m_MultiLine = "";
  1463. m_bDidRejectCertificate = FALSE;
  1464. m_bUTF8 = false;
  1465. m_hasClntCmd = false;
  1466. m_serverCapabilities.Clear();
  1467. m_ListFile = "";
  1468. m_awaitsReply = false;
  1469. m_skipReply = false;
  1470. delete [] m_sendBuffer;
  1471. m_sendBuffer = 0;
  1472. m_sendBufferLen = 0;
  1473. m_bProtP = false;
  1474. m_mayBeMvsFilesystem = false;
  1475. m_mayBeBS2000Filesystem = false;
  1476. Close();
  1477. }
  1478. void CFtpControlSocket::Disconnect()
  1479. {
  1480. DebugAssert(!m_Operation.nOpMode);
  1481. m_Operation.nOpMode=CSMODE_DISCONNECT;
  1482. DoClose();
  1483. ShowStatus(IDS_STATUSMSG_DISCONNECTED,FZ_LOG_STATUS); //Send the disconnected message to the message log
  1484. }
  1485. void CFtpControlSocket::CheckForTimeout()
  1486. {
  1487. if (!m_Operation.nOpMode && !m_bKeepAliveActive)
  1488. return;
  1489. if (!m_bCheckForTimeout)
  1490. return;
  1491. int delay=GetOptionVal(OPTION_TIMEOUTLENGTH);
  1492. if (m_pTransferSocket)
  1493. {
  1494. int res = m_pTransferSocket->CheckForTimeout(delay);
  1495. if (res != 0)
  1496. {
  1497. if (res == 1)
  1498. {
  1499. // avoid trying to set keepalive command right after the transfer finishes
  1500. m_LastSendTime = CTime::CreateForCurrentTime();
  1501. }
  1502. return;
  1503. }
  1504. }
  1505. CTimeSpan span=CTime::CreateForCurrentTime()-m_LastRecvTime;
  1506. if (span.GetTotalSeconds()>=delay)
  1507. {
  1508. ShowTimeoutError(IDS_CONTROL_CONNECTION);
  1509. DoClose();
  1510. }
  1511. }
  1512. void CFtpControlSocket::FtpCommand(LPCTSTR pCommand)
  1513. {
  1514. m_Operation.nOpMode=CSMODE_COMMAND;
  1515. Send(pCommand);
  1516. }
  1517. bool CFtpControlSocket::UsingMlsd()
  1518. {
  1519. return
  1520. // 0 = on, 1 = off, 2 = auto
  1521. (m_CurrentServer.iUseMlsd == 0) ||
  1522. ((m_CurrentServer.iUseMlsd != 1) &&
  1523. (m_serverCapabilities.GetCapability(mlsd_command) == yes));
  1524. }
  1525. bool CFtpControlSocket::UsingUtf8()
  1526. {
  1527. return m_bUTF8;
  1528. }
  1529. std::string CFtpControlSocket::GetTlsVersionStr()
  1530. {
  1531. if (m_pSslLayer != NULL)
  1532. {
  1533. return m_pSslLayer->GetTlsVersionStr();
  1534. }
  1535. else
  1536. {
  1537. return std::string();
  1538. }
  1539. }
  1540. std::string CFtpControlSocket::GetCipherName()
  1541. {
  1542. if (m_pSslLayer != NULL)
  1543. {
  1544. return m_pSslLayer->GetCipherName();
  1545. }
  1546. else
  1547. {
  1548. return std::string();
  1549. }
  1550. }
  1551. CString CFtpControlSocket::GetListingCmd()
  1552. {
  1553. CString cmd;
  1554. if (UsingMlsd())
  1555. {
  1556. cmd = L"MLSD";
  1557. }
  1558. else
  1559. {
  1560. cmd = L"LIST";
  1561. if (GetOptionVal(OPTION_MPEXT_SHOWHIDDEN) && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
  1562. cmd += L" -a";
  1563. }
  1564. return cmd;
  1565. }
  1566. void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath path /*=CServerPath()*/, CString subdir /*=L""*/)
  1567. {
  1568. USES_CONVERSION;
  1569. #define LIST_INIT -1
  1570. #define LIST_PWD 0
  1571. #define LIST_CWD 1
  1572. #define LIST_PWD2 2
  1573. #define LIST_CWD2 3
  1574. #define LIST_PWD3 4
  1575. #define LIST_PORT_PASV 7
  1576. #define LIST_TYPE 8
  1577. #define LIST_LIST 9
  1578. #define LIST_WAITFINISH 10
  1579. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LIST);
  1580. m_Operation.nOpMode|=CSMODE_LIST;
  1581. if (!m_pOwner->IsConnected())
  1582. {
  1583. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  1584. return;
  1585. }
  1586. if (bFinish || nError)
  1587. if (m_Operation.nOpMode!=CSMODE_LIST)
  1588. return; //Old message coming in
  1589. if (nError)
  1590. {
  1591. delete m_pTransferSocket;
  1592. m_pTransferSocket=0;
  1593. if (nError&CSMODE_TRANSFERTIMEOUT)
  1594. DoClose();
  1595. else
  1596. ResetOperation(FZ_REPLY_ERROR);
  1597. return;
  1598. }
  1599. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  1600. if (bFinish)
  1601. {
  1602. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  1603. {
  1604. delete m_pDirectoryListing;
  1605. m_pDirectoryListing = 0;
  1606. delete m_pTransferSocket;
  1607. m_pTransferSocket = 0;
  1608. ResetOperation(FZ_REPLY_ERROR);
  1609. return;
  1610. }
  1611. int num = 0;
  1612. pData->pDirectoryListing = new t_directory;
  1613. pData->pDirectoryListing->direntry = m_pTransferSocket->m_pListResult->getList(num);
  1614. pData->pDirectoryListing->num = num;
  1615. if (m_pTransferSocket->m_pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  1616. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  1617. pData->pDirectoryListing->server = m_CurrentServer;
  1618. pData->pDirectoryListing->path.SetServer(pData->pDirectoryListing->server);
  1619. if (pData->rawpwd != L"")
  1620. {
  1621. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  1622. {
  1623. delete m_pDirectoryListing;
  1624. m_pDirectoryListing=0;
  1625. delete m_pTransferSocket;
  1626. m_pTransferSocket=0;
  1627. ResetOperation(FZ_REPLY_ERROR);
  1628. return;
  1629. }
  1630. m_pOwner->SetCurrentPath(pData->pDirectoryListing->path);
  1631. }
  1632. else
  1633. pData->pDirectoryListing->path = m_pOwner->GetCurrentPath();
  1634. if (m_Operation.nOpState!=LIST_WAITFINISH)
  1635. {
  1636. return;
  1637. }
  1638. else
  1639. {
  1640. delete m_pTransferSocket;
  1641. m_pTransferSocket=0;
  1642. }
  1643. }
  1644. if (m_Operation.nOpState==LIST_WAITFINISH)
  1645. {
  1646. if (!bFinish)
  1647. {
  1648. if (pData->nFinish==-1)
  1649. {
  1650. int code=GetReplyCode();
  1651. if (code== 2)
  1652. {
  1653. pData->nFinish=1;
  1654. }
  1655. else
  1656. pData->nFinish=0;
  1657. }
  1658. }
  1659. else
  1660. {
  1661. if (m_pTransferSocket)
  1662. delete m_pTransferSocket;
  1663. m_pTransferSocket=0;
  1664. }
  1665. if (pData->nFinish==0)
  1666. {
  1667. ResetOperation(FZ_REPLY_ERROR);
  1668. return;
  1669. }
  1670. else if (pData->pDirectoryListing && pData->nFinish==1)
  1671. {
  1672. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,FZ_LOG_PROGRESS);
  1673. SetDirectoryListing(pData->pDirectoryListing);
  1674. ResetOperation(FZ_REPLY_OK);
  1675. return;
  1676. }
  1677. return;
  1678. }
  1679. else if (m_Operation.nOpState != LIST_INIT)
  1680. {
  1681. CString retmsg = GetReply();
  1682. BOOL error = FALSE;
  1683. int code = GetReplyCode();
  1684. switch (m_Operation.nOpState)
  1685. {
  1686. case LIST_PWD: //Reply to PWD command
  1687. if (code != 2 && code !=3 )
  1688. {
  1689. error = TRUE;
  1690. break;
  1691. }
  1692. pData->rawpwd = retmsg;
  1693. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  1694. pData->rawpwd[0] != L'/')
  1695. {
  1696. m_mayBeMvsFilesystem = false;
  1697. m_mayBeBS2000Filesystem = false;
  1698. if (m_mayBeBS2000Filesystem)
  1699. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  1700. else
  1701. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  1702. if (!pData->path.IsEmpty())
  1703. pData->path.SetServer(m_CurrentServer);
  1704. }
  1705. if (!ParsePwdReply(pData->rawpwd))
  1706. return;
  1707. if (pData->path.IsEmpty() || pData->path == m_pOwner->GetCurrentPath())
  1708. {
  1709. m_Operation.nOpState = LIST_TYPE;
  1710. }
  1711. else
  1712. m_Operation.nOpState = LIST_CWD;
  1713. break;
  1714. case LIST_CWD:
  1715. if (code != 2 && code != 3)
  1716. error = TRUE;
  1717. m_Operation.nOpState = LIST_PWD2;
  1718. break;
  1719. case LIST_PWD2: //Reply to PWD command
  1720. if (code !=2 && code != 3)
  1721. error = TRUE;
  1722. else
  1723. {
  1724. pData->rawpwd = retmsg;
  1725. if (!ParsePwdReply(pData->rawpwd))
  1726. return;
  1727. }
  1728. if (pData->subdir != L"")
  1729. {
  1730. if (pData->path != m_pOwner->GetCurrentPath())
  1731. {
  1732. ResetOperation(FZ_REPLY_ERROR);
  1733. return;
  1734. }
  1735. m_Operation.nOpState = LIST_CWD2;
  1736. }
  1737. else
  1738. {
  1739. m_Operation.nOpState = LIST_TYPE;
  1740. }
  1741. break;
  1742. case LIST_CWD2:
  1743. if (pData->lastCmdSentCDUP)
  1744. {
  1745. CString reply = GetReply().Left(3);
  1746. int replycode = _ttoi(reply);
  1747. if (replycode >= 500 && replycode < 505)
  1748. break;
  1749. pData->lastCmdSentCDUP = false;
  1750. }
  1751. if (code != 2 && code != 3)
  1752. error = TRUE;
  1753. m_Operation.nOpState = LIST_PWD3;
  1754. break;
  1755. case LIST_PWD3: //Reply to PWD command
  1756. if (code != 2 && code != 3)
  1757. error = TRUE;
  1758. else
  1759. {
  1760. pData->rawpwd = retmsg;
  1761. if (!ParsePwdReply(pData->rawpwd))
  1762. return;
  1763. }
  1764. m_Operation.nOpState = LIST_TYPE;
  1765. break;
  1766. case LIST_TYPE:
  1767. if (code!=2 && code!=3)
  1768. error=TRUE;
  1769. m_Operation.nOpState = LIST_PORT_PASV;
  1770. break;
  1771. case LIST_PORT_PASV:
  1772. if (code!=2 && code!=3)
  1773. {
  1774. error=TRUE;
  1775. break;
  1776. }
  1777. if (pData->bPasv)
  1778. {
  1779. CString temp;
  1780. int i,j;
  1781. // MP EXT
  1782. if((i=retmsg.Find(L"("))>=0&&(j=retmsg.Find(L")"))>=0)
  1783. {
  1784. i++;
  1785. j--;
  1786. }
  1787. else
  1788. {
  1789. // MP EXT
  1790. if ((i=retmsg.Mid(4).FindOneOf(L"0123456789"))>=0)
  1791. {
  1792. i += 4;
  1793. j = retmsg.GetLength() - 1;
  1794. }
  1795. else
  1796. {
  1797. if (!pData->bTriedPortPasvOnce)
  1798. {
  1799. pData->bTriedPortPasvOnce = TRUE;
  1800. pData->bPasv = !pData->bPasv;
  1801. }
  1802. else
  1803. error=TRUE;
  1804. break;
  1805. }
  1806. }
  1807. temp = retmsg.Mid(i,(j-i)+1);
  1808. if (GetFamily() == AF_INET)
  1809. {
  1810. i=temp.ReverseFind(L',');
  1811. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  1812. temp=temp.Left(i);
  1813. i=temp.ReverseFind(L',');
  1814. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  1815. pData->host = temp.Left(i);
  1816. pData->host.Replace(L',', L'.');
  1817. if (!CheckForcePasvIp(pData->host))
  1818. {
  1819. error = TRUE;
  1820. break;
  1821. }
  1822. }
  1823. else if (GetFamily() == AF_INET6)
  1824. {
  1825. temp = temp.Mid(3);
  1826. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  1827. if (pData->port < 0 || pData->port > 65535)
  1828. {
  1829. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  1830. error = TRUE;
  1831. break;
  1832. }
  1833. pData->host = m_CurrentServer.host;
  1834. }
  1835. else
  1836. {
  1837. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  1838. error = TRUE;
  1839. break;
  1840. }
  1841. }
  1842. m_Operation.nOpState = LIST_LIST;
  1843. break;
  1844. case LIST_LIST:
  1845. if (IsMisleadingListResponse())
  1846. {
  1847. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  1848. t_directory listing;
  1849. listing.server = m_CurrentServer;
  1850. listing.path = m_pOwner->GetCurrentPath();
  1851. SetDirectoryListing(&listing);
  1852. ResetOperation(FZ_REPLY_OK);
  1853. return;
  1854. }
  1855. else if (code != 1)
  1856. error = TRUE;
  1857. else
  1858. m_Operation.nOpState = LIST_WAITFINISH;
  1859. break;
  1860. default:
  1861. error = TRUE;
  1862. }
  1863. if (error)
  1864. {
  1865. ResetOperation(FZ_REPLY_ERROR);
  1866. return;
  1867. }
  1868. }
  1869. if (m_Operation.nOpState==LIST_INIT)
  1870. { //Initialize some variables
  1871. pData=new CListData;
  1872. pData->path=path;
  1873. pData->subdir=subdir;
  1874. m_Operation.pData=pData;
  1875. ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, FZ_LOG_PROGRESS);
  1876. pData->nFinish=-1;
  1877. if (m_pDirectoryListing)
  1878. {
  1879. delete m_pDirectoryListing;
  1880. m_pDirectoryListing=0;
  1881. }
  1882. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  1883. pData->bPasv = TRUE;
  1884. else if (m_CurrentServer.nPasv == 1)
  1885. pData->bPasv = TRUE;
  1886. else if (m_CurrentServer.nPasv == 2)
  1887. pData->bPasv = FALSE;
  1888. else
  1889. pData->bPasv = GetOptionVal(OPTION_PASV);
  1890. CServerPath path = pData->path;
  1891. CServerPath realpath = m_pOwner->GetCurrentPath();
  1892. if (!realpath.IsEmpty())
  1893. {
  1894. if (!pData->path.IsEmpty() && pData->path != realpath)
  1895. m_Operation.nOpState=LIST_CWD;
  1896. else if (!pData->path.IsEmpty() && pData->subdir!=L"")
  1897. m_Operation.nOpState=LIST_CWD2;
  1898. else
  1899. {
  1900. m_Operation.nOpState = LIST_TYPE;
  1901. }
  1902. }
  1903. else
  1904. m_Operation.nOpState = LIST_PWD;
  1905. }
  1906. CString cmd;
  1907. if (m_Operation.nOpState == LIST_PWD)
  1908. cmd=L"PWD";
  1909. else if (m_Operation.nOpState==LIST_CWD)
  1910. cmd=L"CWD " + pData->path.GetPathUnterminated(); //Command to retrieve the current directory
  1911. else if (m_Operation.nOpState==LIST_PWD2)
  1912. cmd=L"PWD";
  1913. else if (m_Operation.nOpState==LIST_CWD2)
  1914. {
  1915. if (!pData->subdir)
  1916. {
  1917. ResetOperation(FZ_REPLY_ERROR);
  1918. return;
  1919. }
  1920. if (pData->subdir != L".." )
  1921. {
  1922. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
  1923. {
  1924. CServerPath path = m_pOwner->GetCurrentPath();
  1925. path.AddSubdir(pData->subdir);
  1926. cmd = L"CWD " + path.GetPathUnterminated();
  1927. }
  1928. else
  1929. cmd = L"CWD " + pData->subdir;
  1930. }
  1931. else
  1932. {
  1933. if (pData->lastCmdSentCDUP)
  1934. {
  1935. pData->lastCmdSentCDUP = false;
  1936. cmd = L"CWD ..";
  1937. }
  1938. else
  1939. {
  1940. pData->lastCmdSentCDUP = true;
  1941. cmd = L"CDUP";
  1942. }
  1943. }
  1944. }
  1945. else if (m_Operation.nOpState == LIST_PWD3)
  1946. cmd=L"PWD";
  1947. else if (m_Operation.nOpState == LIST_PORT_PASV)
  1948. {
  1949. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  1950. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  1951. #ifndef MPEXT_NO_GSS
  1952. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  1953. m_pTransferSocket->UseGSS(m_pGssLayer);
  1954. #endif
  1955. m_pTransferSocket->SetFamily(GetFamily());
  1956. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) ||
  1957. !m_pTransferSocket->AsyncSelect())
  1958. {
  1959. ShowStatus(L"Failed to create socket", FZ_LOG_ERROR);
  1960. ResetOperation(FZ_REPLY_ERROR);
  1961. return;
  1962. }
  1963. if (pData->bPasv)
  1964. switch (GetFamily())
  1965. {
  1966. case AF_INET:
  1967. cmd = L"PASV";
  1968. break;
  1969. case AF_INET6:
  1970. cmd = L"EPSV";
  1971. break;
  1972. default:
  1973. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  1974. ResetOperation(FZ_REPLY_ERROR);
  1975. return;
  1976. }
  1977. else
  1978. {
  1979. m_pTransferSocket->m_bListening=TRUE;
  1980. if (m_pProxyLayer)
  1981. {
  1982. SOCKADDR_IN addr;
  1983. int len=sizeof(addr);
  1984. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  1985. {
  1986. ResetOperation(FZ_REPLY_ERROR);
  1987. return;
  1988. }
  1989. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  1990. {
  1991. ResetOperation(FZ_REPLY_ERROR);
  1992. return;
  1993. }
  1994. }
  1995. else
  1996. {
  1997. //Set up an active file transfer
  1998. CString tempHostname;
  1999. UINT nPort;
  2000. if (// create listen socket (let MFC choose the port) & start the socket listening
  2001. !m_pTransferSocket->Listen() ||
  2002. !m_pTransferSocket->GetSockName(tempHostname, nPort))
  2003. {
  2004. ShowStatus(L"Failed to create listen socket", FZ_LOG_ERROR);
  2005. ResetOperation(FZ_REPLY_ERROR);
  2006. return;
  2007. }
  2008. CString host;
  2009. bool bError = false;
  2010. if (GetFamily() == AF_INET)
  2011. {
  2012. host = GetOption(OPTION_TRANSFERIP);
  2013. if (host != L"")
  2014. {
  2015. DWORD ip = inet_addr(T2CA(host));
  2016. if (ip != INADDR_NONE)
  2017. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2018. else
  2019. {
  2020. hostent *fullname = gethostbyname(T2CA(host));
  2021. if (!fullname)
  2022. host = L"";
  2023. else
  2024. {
  2025. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  2026. if (ip != INADDR_NONE)
  2027. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2028. else
  2029. host = L"";
  2030. }
  2031. }
  2032. }
  2033. if (host == L"")
  2034. {
  2035. UINT temp;
  2036. if (!GetSockName(host, temp))
  2037. {
  2038. ShowStatus(L"Failed to get socket address ", FZ_LOG_ERROR);
  2039. bError = true;
  2040. }
  2041. host.Replace(L'.', L',');
  2042. }
  2043. if (!bError)
  2044. {
  2045. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  2046. cmd = L"PORT " + host; // send PORT cmd to server
  2047. }
  2048. }
  2049. else if (GetFamily() == AF_INET6)
  2050. {
  2051. host = GetOption(OPTION_TRANSFERIP6);
  2052. if (host != L"")
  2053. {
  2054. addrinfo hints, *res;
  2055. memset(&hints, 0, sizeof(addrinfo));
  2056. hints.ai_family = AF_INET6;
  2057. hints.ai_socktype = SOCK_STREAM;
  2058. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  2059. {
  2060. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  2061. freeaddrinfo(res);
  2062. }
  2063. else
  2064. host = L"";
  2065. }
  2066. if (host == L"")
  2067. {
  2068. UINT temp;
  2069. if(!GetSockName(host, temp))
  2070. bError = true;
  2071. }
  2072. if (!bError)
  2073. {
  2074. // assamble EPRT command
  2075. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  2076. }
  2077. }
  2078. else
  2079. {
  2080. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  2081. bError = true;
  2082. }
  2083. if (bError)
  2084. {
  2085. ResetOperation(FZ_REPLY_ERROR);
  2086. return;
  2087. }
  2088. }
  2089. }
  2090. }
  2091. else if (m_Operation.nOpState==LIST_TYPE)
  2092. cmd=L"TYPE A";
  2093. else if (m_Operation.nOpState==LIST_LIST)
  2094. {
  2095. if (!m_pTransferSocket)
  2096. {
  2097. LogMessage(FZ_LOG_APIERROR, L"Error: m_pTransferSocket==NULL" );
  2098. ResetOperation(FZ_REPLY_ERROR);
  2099. return;
  2100. }
  2101. m_pTransferSocket->SetActive();
  2102. cmd = GetListingCmd();
  2103. if (!Send(cmd))
  2104. return;
  2105. if (pData->bPasv)
  2106. {
  2107. // if PASV create the socket & initiate outbound data channel connection
  2108. if (!ConnectTransferSocket(pData->host, pData->port))
  2109. {
  2110. ResetOperation(FZ_REPLY_ERROR);
  2111. return;
  2112. }
  2113. }
  2114. return;
  2115. }
  2116. if (cmd != L"")
  2117. Send(cmd);
  2118. }
  2119. bool CFtpControlSocket::ConnectTransferSocket(const CString & host, UINT port)
  2120. {
  2121. CString hostname;
  2122. hostname.Format(L"%s:%d", (LPCTSTR)host, port);
  2123. CString str;
  2124. str.Format(IDS_STATUSMSG_CONNECTING, (LPCTSTR)hostname);
  2125. ShowStatus(str, FZ_LOG_PROGRESS);
  2126. bool result = true;
  2127. if (!m_pTransferSocket->Connect(host, port))
  2128. {
  2129. if (GetLastError() != WSAEWOULDBLOCK)
  2130. {
  2131. TransferSocketFailed();
  2132. result = false;
  2133. }
  2134. else
  2135. {
  2136. LogMessage(FZ_LOG_INFO, L"Connection pending");
  2137. }
  2138. }
  2139. else
  2140. {
  2141. LogMessage(FZ_LOG_INFO, L"Connected");
  2142. }
  2143. return result;
  2144. }
  2145. void CFtpControlSocket::ListFile(CString filename, const CServerPath &path)
  2146. {
  2147. #define LISTFILE_INIT -1
  2148. #define LISTFILE_MLST 1
  2149. #define LISTFILE_TYPE 2
  2150. #define LISTFILE_SIZE 3
  2151. #define LISTFILE_MDTM 4
  2152. #define LISTFILE_PWD 5
  2153. #define LISTFILE_CWD 6
  2154. #define LISTFILE_CWD2 7
  2155. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LISTFILE);
  2156. m_Operation.nOpMode|=CSMODE_LISTFILE;
  2157. if (!m_pOwner->IsConnected())
  2158. {
  2159. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  2160. return;
  2161. }
  2162. CListFileData * pData = static_cast<CListFileData *>(m_Operation.pData);
  2163. BOOL error = FALSE;
  2164. CString cmd;
  2165. CString retmsg;
  2166. int code = -1;
  2167. int num = -1;
  2168. switch (m_Operation.nOpState)
  2169. {
  2170. case LISTFILE_INIT:
  2171. //Initialize some variables
  2172. pData = new CListFileData;
  2173. pData->fileName = filename;
  2174. pData->dir = path.GetPath();
  2175. // special case for listing a root folder
  2176. pData->path = (filename == L"/") ? pData->dir : path.FormatFilename(filename);
  2177. m_Operation.pData = pData;
  2178. ShowStatus(IDS_STATUSMSG_RETRIEVINGLISTFILE, FZ_LOG_PROGRESS);
  2179. if (UsingMlsd())
  2180. {
  2181. m_Operation.nOpState = LISTFILE_MLST;
  2182. cmd = L"MLST " + pData->path;
  2183. }
  2184. else
  2185. {
  2186. m_Operation.nOpState = LISTFILE_PWD;
  2187. cmd = L"PWD";
  2188. }
  2189. if (!Send(cmd))
  2190. {
  2191. error = TRUE;
  2192. }
  2193. break;
  2194. case LISTFILE_MLST:
  2195. retmsg = GetReply();
  2196. code = GetReplyCode();
  2197. if (IsMisleadingListResponse())
  2198. {
  2199. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL, FZ_LOG_PROGRESS);
  2200. num = 0;
  2201. }
  2202. else if (code != 2)
  2203. {
  2204. error = TRUE;
  2205. }
  2206. else
  2207. {
  2208. RawByteString Buf = m_ListFile + '\n';
  2209. const bool mlst = true;
  2210. CFtpListResult * pListResult = CreateListResult(mlst);
  2211. pListResult->AddData(Buf.c_str(), Buf.Length());
  2212. pData->direntry = pListResult->getList(num);
  2213. if (pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  2214. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2215. delete pListResult;
  2216. }
  2217. break;
  2218. case LISTFILE_PWD:
  2219. code = GetReplyCode();
  2220. retmsg = GetReply();
  2221. if ((code == 2) &&
  2222. ParsePwdReply(retmsg, pData->pwd) &&
  2223. Send(L"CWD " + pData->path))
  2224. {
  2225. m_Operation.nOpState = LISTFILE_CWD;
  2226. }
  2227. else
  2228. {
  2229. error = TRUE;
  2230. }
  2231. break;
  2232. case LISTFILE_CWD:
  2233. code = GetReplyCode();
  2234. pData->direntry = new t_directory::t_direntry[1];
  2235. pData->direntry->name = pData->fileName;
  2236. if (code == 2)
  2237. {
  2238. pData->direntry->dir = TRUE;
  2239. if (Send(L"CWD " + pData->pwd.GetPathUnterminated()))
  2240. {
  2241. m_Operation.nOpState = LISTFILE_CWD2;
  2242. }
  2243. else
  2244. {
  2245. error = TRUE;
  2246. }
  2247. }
  2248. else
  2249. {
  2250. // CWD failed, file is not a directory, we should not need to restore PWD.
  2251. // Force binary mode, as according to RFC 6359,
  2252. // SIZE command returns size as transferred over the stream.
  2253. // Moreover ProFTPD does not even support SIZE command in ASCII mode
  2254. if (Send(L"TYPE I"))
  2255. {
  2256. m_Operation.nOpState = LISTFILE_TYPE;
  2257. }
  2258. else
  2259. {
  2260. error = TRUE;
  2261. }
  2262. }
  2263. break;
  2264. case LISTFILE_CWD2:
  2265. code = GetReplyCode();
  2266. if (code == 2)
  2267. {
  2268. // No point trying SIZE on directories.
  2269. // (More over IIS returns a multi-line response for SIZE /dir and we cannot handle that).
  2270. // IIS fails even for MDTM, so skipping even that.
  2271. num = 1;
  2272. }
  2273. // this should never really happen
  2274. else
  2275. {
  2276. error = TRUE;
  2277. }
  2278. break;
  2279. case LISTFILE_TYPE:
  2280. // Do not really care if TYPE succeeded or not
  2281. if (Send(L"SIZE " + pData->path))
  2282. {
  2283. m_Operation.nOpState = LISTFILE_SIZE;
  2284. }
  2285. else
  2286. {
  2287. error = TRUE;
  2288. }
  2289. break;
  2290. case LISTFILE_SIZE:
  2291. code = GetReplyCode();
  2292. // Ignore SIZE errors for directories
  2293. if ((HandleSize(code, pData->direntry->size) || pData->direntry->dir) &&
  2294. Send(L"MDTM " + pData->path))
  2295. {
  2296. m_Operation.nOpState = LISTFILE_MDTM;
  2297. }
  2298. else
  2299. {
  2300. error = TRUE;
  2301. }
  2302. break;
  2303. case LISTFILE_MDTM:
  2304. code = GetReplyCode();
  2305. if (HandleMdtm(code, pData->direntry->date))
  2306. {
  2307. num = 1;
  2308. }
  2309. else
  2310. {
  2311. error = TRUE;
  2312. }
  2313. break;
  2314. default:
  2315. error = TRUE;
  2316. break;
  2317. }
  2318. if (error)
  2319. {
  2320. ResetOperation(FZ_REPLY_ERROR);
  2321. }
  2322. else if (num >= 0)
  2323. {
  2324. t_directory * pDirectoryListing = new t_directory;
  2325. pDirectoryListing->direntry = pData->direntry;
  2326. pData->direntry = NULL;
  2327. pDirectoryListing->num = num;
  2328. pDirectoryListing->server = m_CurrentServer;
  2329. pDirectoryListing->path.SetServer(pDirectoryListing->server);
  2330. pDirectoryListing->path = pData->dir;
  2331. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL,FZ_LOG_PROGRESS);
  2332. // do not use SetDirectoryListing as that would make
  2333. // later operations believe that there's only this one file in the folder
  2334. m_pOwner->SendDirectoryListing(pDirectoryListing);
  2335. ResetOperation(FZ_REPLY_OK);
  2336. }
  2337. }
  2338. void CFtpControlSocket::TransferSocketFailed()
  2339. {
  2340. // if the control connection is to be used further, the response to LIST/RETR/STOR must be skipped
  2341. m_skipReply = true;
  2342. }
  2343. void CFtpControlSocket::TransferEnd(int nMode)
  2344. {
  2345. if (!m_Operation.nOpMode)
  2346. {
  2347. LogMessage(FZ_LOG_INFO, L"Ignoring old TransferEnd message");
  2348. return;
  2349. }
  2350. m_LastRecvTime=CTime::CreateForCurrentTime();
  2351. int error = nMode & (CSMODE_TRANSFERERROR | CSMODE_TRANSFERTIMEOUT);
  2352. if (error)
  2353. {
  2354. TransferSocketFailed();
  2355. }
  2356. if (m_Operation.nOpMode & CSMODE_TRANSFER)
  2357. {
  2358. FileTransfer(0, TRUE, error);
  2359. }
  2360. else if (m_Operation.nOpMode&CSMODE_LIST)
  2361. {
  2362. List(TRUE, error);
  2363. }
  2364. }
  2365. void CFtpControlSocket::OnClose(int nErrorCode)
  2366. {
  2367. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  2368. if (m_pTransferSocket)
  2369. {
  2370. m_pTransferSocket->OnClose(0);
  2371. m_pTransferSocket->Close();
  2372. delete m_pTransferSocket;
  2373. m_pTransferSocket=0;
  2374. DoClose();
  2375. return;
  2376. }
  2377. if (m_bDidRejectCertificate)
  2378. DoClose(FZ_REPLY_CANCEL);
  2379. else
  2380. DoClose();
  2381. }
  2382. void CFtpControlSocket::ResetTransferSocket(int Error)
  2383. {
  2384. if (Error)
  2385. {
  2386. LogMessage(FZ_LOG_INFO, L"Destroying data socket on error");
  2387. }
  2388. else
  2389. {
  2390. LogMessage(FZ_LOG_INFO, L"Destroying data socket after transfer completed");
  2391. }
  2392. bool Close =
  2393. (Error != 0) &&
  2394. DebugAlwaysTrue(m_pTransferSocket != NULL) &&
  2395. (m_pTransferSocket->m_uploaded > 0) &&
  2396. FLAGCLEAR(Error, FZ_REPLY_CANCEL);
  2397. delete m_pTransferSocket;
  2398. m_pTransferSocket = NULL;
  2399. if (Close)
  2400. {
  2401. // close the control connection too to allow reconnect => transfer resume
  2402. LogMessage(FZ_LOG_WARNING, L"Transfer connection failed, closing");
  2403. DoClose();
  2404. }
  2405. }
  2406. int CFtpControlSocket::OpenTransferFile(CFileTransferData * pData)
  2407. {
  2408. int nReplyError = 0;
  2409. bool res;
  2410. if (pData->transferfile.get)
  2411. {
  2412. if (pData->transferfile.OnTransferOut == NULL)
  2413. {
  2414. m_pDataFile = new CFile();
  2415. if (pData->transferdata.bResume)
  2416. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
  2417. else
  2418. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
  2419. }
  2420. else
  2421. {
  2422. res = true;
  2423. }
  2424. }
  2425. else
  2426. {
  2427. if (pData->transferfile.OnTransferIn == NULL)
  2428. {
  2429. m_pDataFile = new CFile();
  2430. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyNone);
  2431. }
  2432. else
  2433. {
  2434. res = true;
  2435. }
  2436. }
  2437. if (!res)
  2438. {
  2439. wchar_t * Error = m_pTools->LastSysErrorMessage();
  2440. //Error opening the file
  2441. CString str;
  2442. str.Format(IDS_ERRORMSG_FILEOPENFAILED,(LPCTSTR)pData->transferfile.localfile);
  2443. str += L"\n";
  2444. str += Error;
  2445. free(Error);
  2446. ShowStatus(str,FZ_LOG_ERROR);
  2447. nReplyError = FZ_REPLY_ERROR;
  2448. }
  2449. else
  2450. {
  2451. m_pTransferSocket->m_pFile = m_pDataFile;
  2452. m_pTransferSocket->m_OnTransferOut = pData->transferfile.OnTransferOut;
  2453. m_pTransferSocket->m_OnTransferIn = pData->transferfile.OnTransferIn;
  2454. }
  2455. return nReplyError;
  2456. }
  2457. int CFtpControlSocket::ActivateTransferSocket(CFileTransferData * pData)
  2458. {
  2459. int nReplyError = 0;
  2460. if (pData->transferfile.get && (m_pDataFile == NULL))
  2461. {
  2462. nReplyError = OpenTransferFile(pData);
  2463. }
  2464. if (!nReplyError)
  2465. {
  2466. m_pTransferSocket->SetActive();
  2467. }
  2468. return nReplyError;
  2469. }
  2470. void CFtpControlSocket::CancelTransferResume(CFileTransferData * pData)
  2471. {
  2472. pData->transferdata.transferleft = pData->transferdata.transfersize;
  2473. pData->transferdata.bResume = FALSE;
  2474. }
  2475. void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFinish/*=FALSE*/,int nError/*=0*/)
  2476. {
  2477. USES_CONVERSION;
  2478. #define FILETRANSFER_INIT -1
  2479. #define FILETRANSFER_PWD 0
  2480. #define FILETRANSFER_CWD 1
  2481. #define FILETRANSFER_MKD 2
  2482. #define FILETRANSFER_CWD2 3
  2483. #define FILETRANSFER_PWD2 4
  2484. #define FILETRANSFER_LIST_PORTPASV 7
  2485. #define FILETRANSFER_LIST_TYPE 8
  2486. #define FILETRANSFER_LIST_LIST 9
  2487. #define FILETRANSFER_LIST_WAITFINISH 10
  2488. #define FILETRANSFER_NOLIST_SIZE 11
  2489. #define FILETRANSFER_NOLIST_MDTM 12
  2490. #define FILETRANSFER_TYPE 13
  2491. #define FILETRANSFER_REST 14
  2492. #define FILETRANSFER_PORTPASV 17
  2493. #define FILETRANSFER_RETRSTOR 18
  2494. #define FILETRANSFER_WAITFINISH 19
  2495. #define FILETRANSFER_WAIT 20
  2496. #define FILETRANSFER_MFMT 21
  2497. #define FILETRANSFER_OPTS_REST 22
  2498. //Partial flowchart of FileTransfer
  2499. //
  2500. // +----+
  2501. // /------|Init|--------\
  2502. // | +----+ |
  2503. // | | |
  2504. // | /---+ |
  2505. // | | | |
  2506. // | | +---+ |
  2507. // | | |PWD| |
  2508. // | | +---+ |
  2509. // | | | |
  2510. // | \---+ |
  2511. // | | |
  2512. // | +---+ |
  2513. // | |CWD|--\ |
  2514. // | +---+ | |
  2515. // | | | |
  2516. // | | | |
  2517. // | | +---+ |
  2518. // | | |MKD| |
  2519. // | | +---+ |
  2520. // | | | |
  2521. // | | | |
  2522. // | | +----+ |
  2523. // | | |CWD2| |
  2524. // | | +----+ |
  2525. // | | | |
  2526. // | +----/ |
  2527. // | | |
  2528. // | +---+ |
  2529. // +-------|PWD| |
  2530. // | +---+ |
  2531. // | | |
  2532. // | +----------/
  2533. // | |
  2534. // | +---------+
  2535. // | |LIST_TYPE|
  2536. // | +---------+
  2537. // | |
  2538. // | |
  2539. // | +-------------+
  2540. // | |LIST_PORTPASV|
  2541. // | +-------------+
  2542. // | |
  2543. // | |
  2544. // | +---------+
  2545. // | |LIST_LIST|-----\ //List fails, maybe folder is list protected
  2546. // | +---------+ | //Use SIZE and MDTM to get file information
  2547. // | | +----+
  2548. // | | |SIZE|
  2549. // | | +----+
  2550. // | | |
  2551. // | | +----+
  2552. // | | |MDTM|
  2553. // | | +----+
  2554. // | | |
  2555. // | | |
  2556. // | +---------------+ |
  2557. // | |LIST_WAITFINISH| |
  2558. // | +---------------+ |
  2559. // | | |
  2560. // | | |
  2561. // | +----------/
  2562. // | |
  2563. // \---------+
  2564. // |
  2565. // +----+
  2566. // |TYPE|
  2567. // +----+
  2568. // |
  2569. // |
  2570. // +--------+
  2571. // |PORTPASV|--\
  2572. // +--------+ |
  2573. // | |
  2574. // | |
  2575. // | +----+
  2576. // | |REST|
  2577. // | +----+
  2578. // | |
  2579. // +------/
  2580. // |
  2581. // +--------+
  2582. // |RETRSTOR|
  2583. // +--------+
  2584. // |
  2585. // |
  2586. // +----------+
  2587. // |WAITFINISH|
  2588. // +----------+
  2589. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
  2590. if (!m_pOwner->IsConnected())
  2591. {
  2592. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2593. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
  2594. return;
  2595. }
  2596. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2597. //Process finish and error messages
  2598. if (bFinish || nError)
  2599. {
  2600. DebugAssert(m_Operation.nOpMode&CSMODE_TRANSFER);
  2601. // APPE failed, ignore this reply
  2602. if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
  2603. return;
  2604. if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
  2605. return;
  2606. if (nError)
  2607. {
  2608. if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
  2609. { //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
  2610. if (m_pTransferSocket)
  2611. m_pTransferSocket=0;
  2612. delete m_pDirectoryListing;
  2613. m_pDirectoryListing=0;
  2614. }
  2615. else if (nError&CSMODE_TRANSFERTIMEOUT)
  2616. DoClose();
  2617. else
  2618. {
  2619. // we may get here when connection was closed, when the closure
  2620. // was first detected while reading/writing,
  2621. // when we abort file transfer with regular error,
  2622. // possibly preventing automatic reconnect
  2623. LogMessage(FZ_LOG_INFO, L"Transfer error (%x)", nError);
  2624. ResetOperation(FZ_REPLY_ERROR);
  2625. }
  2626. return;
  2627. }
  2628. if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
  2629. {
  2630. ResetOperation(FZ_REPLY_ERROR);
  2631. return;
  2632. }
  2633. else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
  2634. {
  2635. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  2636. {
  2637. delete m_pDirectoryListing;
  2638. m_pDirectoryListing=0;
  2639. ResetOperation(FZ_REPLY_ERROR);
  2640. return;
  2641. }
  2642. int num=0;
  2643. pData->pDirectoryListing=new t_directory;
  2644. pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num);
  2645. pData->pDirectoryListing->num=num;
  2646. if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
  2647. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2648. pData->pDirectoryListing->server = m_CurrentServer;
  2649. pData->pDirectoryListing->path.SetServer(m_CurrentServer);
  2650. pData->pDirectoryListing->path = pData->transferfile.remotepath;
  2651. if (pData->rawpwd!=L"")
  2652. {
  2653. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  2654. {
  2655. delete m_pDirectoryListing;
  2656. m_pDirectoryListing=0;
  2657. delete m_pTransferSocket;
  2658. m_pTransferSocket=0;
  2659. ResetOperation(FZ_REPLY_ERROR);
  2660. return;
  2661. }
  2662. }
  2663. else
  2664. pData->pDirectoryListing->path=pData->transferfile.remotepath;
  2665. if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
  2666. return;
  2667. }
  2668. else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
  2669. {
  2670. ResetOperation(FZ_REPLY_ERROR);
  2671. return;
  2672. }
  2673. else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
  2674. {
  2675. if (m_pTransferSocket->m_bListening)
  2676. {
  2677. ResetOperation(FZ_REPLY_ERROR);
  2678. return;
  2679. }
  2680. pData->nGotTransferEndReply |= 2;
  2681. if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
  2682. return;
  2683. else
  2684. {
  2685. ResetTransferSocket(nError);
  2686. }
  2687. }
  2688. }
  2689. //////////////////
  2690. //Initialization//
  2691. //////////////////
  2692. int nReplyError = 0;
  2693. if (m_Operation.nOpState == FILETRANSFER_INIT)
  2694. {
  2695. DebugAssert(transferfile);
  2696. DebugAssert(!m_Operation.nOpMode);
  2697. DebugAssert(!m_Operation.pData);
  2698. if ((transferfile->OnTransferOut == NULL) &&
  2699. (transferfile->OnTransferIn == NULL))
  2700. {
  2701. CString str;
  2702. str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
  2703. transferfile->get ? (LPCTSTR)transferfile->remotepath.FormatFilename(transferfile->remotefile) : (LPCTSTR)transferfile->localfile);
  2704. ShowStatus(str,FZ_LOG_STATUS);
  2705. }
  2706. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2707. m_Operation.pData=new CFileTransferData;
  2708. pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2709. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  2710. pData->bPasv = TRUE;
  2711. else if (m_CurrentServer.nPasv == 1)
  2712. pData->bPasv = TRUE;
  2713. else if (m_CurrentServer.nPasv == 2)
  2714. pData->bPasv = FALSE;
  2715. else
  2716. pData->bPasv = GetOptionVal(OPTION_PASV);
  2717. //Replace invalid characters in the local filename
  2718. int pos=transferfile->localfile.ReverseFind(L'\\');
  2719. for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
  2720. if (transferfile->localfile[i]==L':')
  2721. transferfile->localfile.SetAt(i, L'_');
  2722. pData->transferfile=*transferfile;
  2723. pData->transferdata.transfersize=pData->transferfile.size;
  2724. pData->transferdata.transferleft=pData->transferfile.size;
  2725. pData->transferdata.bResume = FALSE;
  2726. pData->transferdata.bResumeAppend = FALSE;
  2727. pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
  2728. CServerPath path;
  2729. DebugCheck(m_pOwner->GetCurrentPath(path));
  2730. if (path == pData->transferfile.remotepath)
  2731. {
  2732. if (m_pDirectoryListing)
  2733. {
  2734. m_Operation.nOpState=FILETRANSFER_TYPE;
  2735. CString remotefile=pData->transferfile.remotefile;
  2736. int i;
  2737. for (i=0; i<m_pDirectoryListing->num; i++)
  2738. {
  2739. if (m_pDirectoryListing->direntry[i].name==remotefile &&
  2740. ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
  2741. {
  2742. delete m_pDirectoryListing;
  2743. m_pDirectoryListing=0;
  2744. m_Operation.nOpState = FileTransferListState();
  2745. break;
  2746. }
  2747. }
  2748. if (m_pDirectoryListing && i==m_pDirectoryListing->num)
  2749. {
  2750. nReplyError = CheckOverwriteFileAndCreateTarget();
  2751. }
  2752. }
  2753. else
  2754. {
  2755. m_Operation.nOpState = FileTransferListState();
  2756. }
  2757. }
  2758. else
  2759. {
  2760. if (pData->transferfile.remotepath.IsEmpty() && GetOptionVal(OPTION_MPEXT_WORK_FROM_CWD))
  2761. m_Operation.nOpState = FileTransferListState();
  2762. else if (path.IsEmpty())
  2763. m_Operation.nOpState = FILETRANSFER_PWD;
  2764. else
  2765. m_Operation.nOpState = FILETRANSFER_CWD;
  2766. }
  2767. }
  2768. else
  2769. {
  2770. ///////////
  2771. //Replies//
  2772. ///////////
  2773. int code = TryGetReplyCode();
  2774. // We do not always expect a response here, particularly when closing transfer connection (FILETRANSFER_WAITFINISH).
  2775. // The normalization to 0 is probably not needed.
  2776. if (code < 0)
  2777. {
  2778. code = 0;
  2779. }
  2780. switch(m_Operation.nOpState)
  2781. {
  2782. case FILETRANSFER_PWD:
  2783. if (code != 2 && code != 3)
  2784. {
  2785. nReplyError = FZ_REPLY_ERROR;
  2786. break;
  2787. }
  2788. pData->rawpwd = GetReply();
  2789. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  2790. pData->rawpwd[0] != L'/')
  2791. {
  2792. m_mayBeMvsFilesystem = false;
  2793. m_mayBeBS2000Filesystem = false;
  2794. if (m_mayBeBS2000Filesystem)
  2795. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  2796. else
  2797. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  2798. pData->transferfile.remotepath.SetServer(m_CurrentServer);
  2799. }
  2800. if (!ParsePwdReply(pData->rawpwd))
  2801. return;
  2802. if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
  2803. {
  2804. m_Operation.nOpState = FileTransferListState();
  2805. }
  2806. else
  2807. m_Operation.nOpState = LIST_CWD;
  2808. break;
  2809. case FILETRANSFER_CWD:
  2810. if (code != 2 && code != 3)
  2811. if (pData->transferfile.get)
  2812. {
  2813. pData->bUseAbsolutePaths = TRUE;
  2814. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2815. }
  2816. else
  2817. m_Operation.nOpState = FILETRANSFER_MKD;
  2818. else
  2819. m_Operation.nOpState = FILETRANSFER_PWD2;
  2820. break;
  2821. case FILETRANSFER_MKD:
  2822. switch(pData->nMKDOpState)
  2823. {
  2824. case MKD_FINDPARENT:
  2825. {
  2826. if (code == 2 || code == 3)
  2827. {
  2828. m_pOwner->SetCurrentPath(pData->MKDCurrent);
  2829. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2830. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2831. CString Segment=pData->MKDSegments.front();
  2832. pData->MKDSegments.pop_front();
  2833. if (!Send( L"MKD " + Segment))
  2834. return;
  2835. }
  2836. else
  2837. {
  2838. if (!pData->MKDCurrent.HasParent())
  2839. nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
  2840. else
  2841. {
  2842. pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
  2843. pData->MKDCurrent=pData->MKDCurrent.GetParent();
  2844. if (!Send(L"CWD "+pData->MKDCurrent.GetPathUnterminated()))
  2845. return;
  2846. }
  2847. }
  2848. }
  2849. break;
  2850. case MKD_MAKESUBDIRS:
  2851. {
  2852. if (code == 2 || code == 3)
  2853. { //Create dir entry in parent dir
  2854. DebugAssert(!pData->MKDSegments.empty());
  2855. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2856. CString Segment=pData->MKDSegments.front();
  2857. pData->MKDSegments.pop_front();
  2858. if (Send( L"MKD " + Segment))
  2859. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2860. else
  2861. return;
  2862. }
  2863. else
  2864. nReplyError=FZ_REPLY_ERROR;
  2865. }
  2866. break;
  2867. case MKD_CHANGETOSUBDIR:
  2868. {
  2869. if (code == 2 || code == 3 || //Creation successful
  2870. m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
  2871. {
  2872. CServerPath path2 = pData->MKDCurrent;
  2873. if (path2.HasParent())
  2874. {
  2875. CString name=path2.GetLastSegment();
  2876. path2=path2.GetParent();
  2877. t_directory dir;
  2878. BOOL res=FALSE;
  2879. if (m_pDirectoryListing)
  2880. {
  2881. if (m_pDirectoryListing->path==path2)
  2882. {
  2883. dir=*m_pDirectoryListing;
  2884. res=TRUE;
  2885. }
  2886. }
  2887. t_directory WorkingDir;
  2888. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  2889. if (!res && bFound)
  2890. if (WorkingDir.path==path2)
  2891. {
  2892. dir=WorkingDir;
  2893. res=TRUE;
  2894. }
  2895. if (!res)
  2896. {
  2897. dir.path=path2;
  2898. dir.server=m_CurrentServer;
  2899. }
  2900. int i;
  2901. for (i=0; i<dir.num; i++)
  2902. if (dir.direntry[i].name == name)
  2903. {
  2904. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  2905. break;
  2906. }
  2907. if (i==dir.num)
  2908. {
  2909. t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
  2910. for (i=0;i<dir.num;i++)
  2911. entries[i]=dir.direntry[i];
  2912. entries[i].name=name;
  2913. entries[i].dir=TRUE;
  2914. entries[i].date.hasdate=FALSE;
  2915. entries[i].size=-1;
  2916. entries[i].bUnsure=FALSE;
  2917. delete [] dir.direntry;
  2918. dir.direntry=entries;
  2919. dir.num++;
  2920. BOOL updated=FALSE;
  2921. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  2922. {
  2923. updated=TRUE;
  2924. SetDirectoryListing(&dir);
  2925. }
  2926. if (!updated)
  2927. if (WorkingDir.path==dir.path)
  2928. {
  2929. updated=TRUE;
  2930. m_pOwner->SetWorkingDir(&dir);
  2931. }
  2932. }
  2933. }
  2934. }
  2935. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  2936. if (pData->MKDSegments.empty())
  2937. m_Operation.nOpState=FILETRANSFER_CWD2;
  2938. else
  2939. {
  2940. if (Send( L"CWD " + pData->MKDCurrent.GetPathUnterminated()))
  2941. pData->nMKDOpState=MKD_MAKESUBDIRS;
  2942. else
  2943. return;
  2944. }
  2945. }
  2946. break;
  2947. default:
  2948. DebugFail();
  2949. }
  2950. break;
  2951. case FILETRANSFER_CWD2:
  2952. if (code != 2 && code != 3)
  2953. if (code == 4)
  2954. nReplyError=FZ_REPLY_ERROR;
  2955. else
  2956. nReplyError=FZ_REPLY_CRITICALERROR;
  2957. else
  2958. m_Operation.nOpState=FILETRANSFER_PWD2;
  2959. break;
  2960. case FILETRANSFER_PWD2:
  2961. if (code != 2 && code != 3)
  2962. nReplyError = FZ_REPLY_ERROR;
  2963. else
  2964. {
  2965. pData->rawpwd = GetReply();
  2966. if (!ParsePwdReply(pData->rawpwd))
  2967. return;
  2968. m_Operation.nOpState = FileTransferListState();
  2969. }
  2970. break;
  2971. case FILETRANSFER_LIST_TYPE:
  2972. if (code != 2 && code != 3)
  2973. nReplyError = FZ_REPLY_ERROR;
  2974. else
  2975. m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
  2976. break;
  2977. case FILETRANSFER_LIST_PORTPASV:
  2978. if (code!=3 && code!=2)
  2979. {
  2980. if (!pData->bTriedPortPasvOnce)
  2981. {
  2982. pData->bTriedPortPasvOnce = TRUE;
  2983. pData->bPasv = !pData->bPasv;
  2984. }
  2985. else
  2986. nReplyError=FZ_REPLY_ERROR;
  2987. break;
  2988. }
  2989. if (pData->bPasv)
  2990. {
  2991. CString reply = GetReply();
  2992. int i,j;
  2993. // MP EXT
  2994. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  2995. {
  2996. i++;
  2997. j--;
  2998. }
  2999. else
  3000. {
  3001. // MP EXT
  3002. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  3003. {
  3004. i += 4;
  3005. j = reply.GetLength() - 1;
  3006. }
  3007. else
  3008. {
  3009. if (!pData->bTriedPortPasvOnce)
  3010. {
  3011. pData->bTriedPortPasvOnce = TRUE;
  3012. pData->bPasv = !pData->bPasv;
  3013. }
  3014. else
  3015. nReplyError = FZ_REPLY_ERROR;
  3016. break;
  3017. }
  3018. }
  3019. CString temp = reply.Mid(i,(j-i)+1);
  3020. if (GetFamily() == AF_INET)
  3021. {
  3022. int count=0;
  3023. int pos=0;
  3024. //Convert commas to dots
  3025. temp.Replace( L",", L"." );
  3026. while(1)
  3027. {
  3028. pos=temp.Find(L".",pos);
  3029. if (pos!=-1)
  3030. count++;
  3031. else
  3032. break;
  3033. pos++;
  3034. }
  3035. if (count!=5)
  3036. {
  3037. if (!pData->bTriedPortPasvOnce)
  3038. {
  3039. pData->bTriedPortPasvOnce = TRUE;
  3040. pData->bPasv = !pData->bPasv;
  3041. }
  3042. else
  3043. nReplyError = FZ_REPLY_ERROR;
  3044. break;
  3045. }
  3046. i=temp.ReverseFind(L'.');
  3047. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3048. temp=temp.Left(i);
  3049. i=temp.ReverseFind(L'.');
  3050. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3051. pData->host=temp.Left(i);
  3052. if (!CheckForcePasvIp(pData->host))
  3053. {
  3054. nReplyError = FZ_REPLY_ERROR;
  3055. break;
  3056. }
  3057. }
  3058. else if (GetFamily() == AF_INET6)
  3059. {
  3060. temp = temp.Mid(3);
  3061. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3062. if (pData->port < 0 || pData->port > 65535)
  3063. {
  3064. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3065. nReplyError = FZ_REPLY_ERROR;
  3066. break;
  3067. }
  3068. pData->host = m_CurrentServer.host;
  3069. }
  3070. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3071. #ifndef MPEXT_NO_GSS
  3072. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3073. m_pTransferSocket->UseGSS(m_pGssLayer);
  3074. #endif
  3075. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3076. m_pTransferSocket->SetFamily(GetFamily());
  3077. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3078. {
  3079. nReplyError = FZ_REPLY_ERROR;
  3080. break;
  3081. }
  3082. DebugCheck(m_pTransferSocket->AsyncSelect());
  3083. }
  3084. m_Operation.nOpState=FILETRANSFER_LIST_LIST;
  3085. break;
  3086. case FILETRANSFER_LIST_LIST:
  3087. if (IsMisleadingListResponse())
  3088. {
  3089. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  3090. t_directory listing;
  3091. listing.server = m_CurrentServer;
  3092. listing.path.SetServer(m_CurrentServer);
  3093. if (pData->rawpwd != L"")
  3094. {
  3095. if (!listing.path.SetPath(pData->rawpwd))
  3096. {
  3097. delete m_pDirectoryListing;
  3098. m_pDirectoryListing = 0;
  3099. delete m_pTransferSocket;
  3100. m_pTransferSocket = 0;
  3101. ResetOperation(FZ_REPLY_ERROR);
  3102. return;
  3103. }
  3104. }
  3105. else
  3106. listing.path = pData->transferfile.remotepath;
  3107. nReplyError = FileTransferHandleDirectoryListing(&listing);
  3108. }
  3109. else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
  3110. {
  3111. TransferHandleListError();
  3112. }
  3113. else if (code!=1)
  3114. nReplyError=FZ_REPLY_ERROR;
  3115. else
  3116. m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
  3117. break;
  3118. case FILETRANSFER_LIST_WAITFINISH:
  3119. if (!bFinish)
  3120. {
  3121. if (code!=2 && code!=3)
  3122. {
  3123. if (code==4 || code==5)
  3124. {
  3125. TransferHandleListError();
  3126. }
  3127. else
  3128. {
  3129. nReplyError=FZ_REPLY_ERROR;
  3130. }
  3131. }
  3132. else
  3133. pData->nGotTransferEndReply = 1;
  3134. }
  3135. if (pData->nGotTransferEndReply && pData->pDirectoryListing)
  3136. {
  3137. nReplyError = FileTransferHandleDirectoryListing(pData->pDirectoryListing);
  3138. pData->nGotTransferEndReply=0;
  3139. }
  3140. break;
  3141. case FILETRANSFER_NOLIST_SIZE:
  3142. {
  3143. __int64 size;
  3144. if (HandleSize(code, size))
  3145. {
  3146. DebugAssert(!pData->pFileSize);
  3147. pData->pFileSize=new _int64;
  3148. *pData->pFileSize=size;
  3149. }
  3150. }
  3151. m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
  3152. break;
  3153. case FILETRANSFER_NOLIST_MDTM:
  3154. if (HandleMdtm(code, pData->remoteDate))
  3155. {
  3156. pData->hasRemoteDate = true;
  3157. }
  3158. m_Operation.nOpState=FILETRANSFER_TYPE;
  3159. nReplyError=CheckOverwriteFile();
  3160. break;
  3161. case FILETRANSFER_TYPE:
  3162. if (code!=2 && code!=3)
  3163. nReplyError = FZ_REPLY_ERROR;
  3164. m_Operation.nOpState = !pData->transferfile.get && pData->transferdata.bResume ? FILETRANSFER_OPTS_REST : FILETRANSFER_PORTPASV;
  3165. break;
  3166. case FILETRANSFER_WAIT:
  3167. if (!pData->nWaitNextOpState)
  3168. nReplyError=FZ_REPLY_ERROR;
  3169. else
  3170. m_Operation.nOpState=pData->nWaitNextOpState;
  3171. break;
  3172. case FILETRANSFER_PORTPASV:
  3173. if (code == 3 || code == 2)
  3174. {
  3175. if (pData->bPasv)
  3176. {
  3177. CString reply = GetReply();
  3178. int i,j;
  3179. // MP EXT
  3180. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  3181. {
  3182. i++;
  3183. j--;
  3184. }
  3185. else
  3186. {
  3187. // MP EXT
  3188. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  3189. {
  3190. i += 4;
  3191. j = reply.GetLength() - 1;
  3192. }
  3193. else
  3194. {
  3195. if (!pData->bTriedPortPasvOnce)
  3196. {
  3197. pData->bTriedPortPasvOnce = TRUE;
  3198. pData->bPasv = !pData->bPasv;
  3199. }
  3200. else
  3201. nReplyError = FZ_REPLY_ERROR;
  3202. break;
  3203. }
  3204. }
  3205. CString temp = reply.Mid(i,(j-i)+1);
  3206. if (GetFamily() == AF_INET)
  3207. {
  3208. int count=0;
  3209. int pos=0;
  3210. //Convert commas to dots
  3211. temp.Replace( L",", L"." );
  3212. while(1)
  3213. {
  3214. pos=temp.Find( L".", pos);
  3215. if (pos!=-1)
  3216. count++;
  3217. else
  3218. break;
  3219. pos++;
  3220. }
  3221. if (count!=5)
  3222. {
  3223. if (!pData->bTriedPortPasvOnce)
  3224. {
  3225. pData->bTriedPortPasvOnce = TRUE;
  3226. pData->bPasv = !pData->bPasv;
  3227. }
  3228. else
  3229. nReplyError = FZ_REPLY_ERROR;
  3230. break;
  3231. }
  3232. i=temp.ReverseFind(L'.');
  3233. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3234. temp=temp.Left(i);
  3235. i=temp.ReverseFind(L'.');
  3236. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3237. pData->host=temp.Left(i);
  3238. if (!CheckForcePasvIp(pData->host))
  3239. {
  3240. nReplyError = FZ_REPLY_ERROR;
  3241. break;
  3242. }
  3243. }
  3244. else if (GetFamily() == AF_INET6)
  3245. {
  3246. temp = temp.Mid(3);
  3247. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3248. if (pData->port < 0 || pData->port > 65535)
  3249. {
  3250. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3251. nReplyError = FZ_REPLY_ERROR;
  3252. break;
  3253. }
  3254. pData->host = m_CurrentServer.host;
  3255. }
  3256. else
  3257. {
  3258. nReplyError = FZ_REPLY_ERROR;
  3259. break;
  3260. }
  3261. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  3262. #ifndef MPEXT_NO_GSS
  3263. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3264. m_pTransferSocket->UseGSS(m_pGssLayer);
  3265. #endif
  3266. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3267. m_pTransferSocket->SetFamily(GetFamily());
  3268. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3269. {
  3270. nReplyError = FZ_REPLY_ERROR;
  3271. break;
  3272. }
  3273. DebugCheck(m_pTransferSocket->AsyncSelect());
  3274. }
  3275. if (pData->transferdata.bResume)
  3276. m_Operation.nOpState = FILETRANSFER_REST;
  3277. else
  3278. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3279. if (m_pDataFile != NULL)
  3280. {
  3281. delete m_pDataFile;
  3282. m_pDataFile = NULL;
  3283. }
  3284. if (!m_pTransferSocket)
  3285. {
  3286. nReplyError=FZ_REPLY_ERROR;
  3287. break;
  3288. }
  3289. if (!pData->transferfile.get)
  3290. {
  3291. nReplyError = OpenTransferFile(pData);
  3292. if (nReplyError)
  3293. {
  3294. break;
  3295. }
  3296. if (m_pDataFile != NULL)
  3297. {
  3298. // See comment in !get branch below
  3299. pData->transferdata.transfersize=GetLength64(*m_pDataFile);
  3300. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3301. }
  3302. if (pData->transferdata.bResume)
  3303. {
  3304. CString remotefile=pData->transferfile.remotefile;
  3305. if (m_pDirectoryListing)
  3306. for (int i = 0; i < m_pDirectoryListing->num; i++)
  3307. {
  3308. if (m_pDirectoryListing->direntry[i].name == remotefile)
  3309. {
  3310. pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
  3311. break;
  3312. }
  3313. }
  3314. _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
  3315. LONG low = static_cast<LONG>(size&0xFFFFFFFF);
  3316. LONG high = static_cast<LONG>(size>>32);
  3317. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3318. {
  3319. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3320. nReplyError = FZ_REPLY_ERROR;
  3321. }
  3322. }
  3323. }
  3324. else
  3325. {
  3326. if (pData->transferdata.bResume)
  3327. {
  3328. nReplyError = OpenTransferFile(pData);
  3329. if (nReplyError)
  3330. {
  3331. break;
  3332. }
  3333. }
  3334. CString remotefile=pData->transferfile.remotefile;
  3335. if (m_pDirectoryListing)
  3336. for (int i=0; i<m_pDirectoryListing->num; i++)
  3337. {
  3338. if (m_pDirectoryListing->direntry[i].name==remotefile)
  3339. {
  3340. pData->hasRemoteDate = true;
  3341. pData->remoteDate = m_pDirectoryListing->direntry[i].date;
  3342. pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
  3343. }
  3344. }
  3345. else if (pData->pFileSize)
  3346. pData->transferdata.transfersize=*pData->pFileSize;
  3347. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3348. }
  3349. }
  3350. else
  3351. if (!pData->bTriedPortPasvOnce)
  3352. {
  3353. pData->bTriedPortPasvOnce = TRUE;
  3354. pData->bPasv = !pData->bPasv;
  3355. }
  3356. else
  3357. nReplyError = FZ_REPLY_ERROR;
  3358. break;
  3359. case FILETRANSFER_OPTS_REST:
  3360. // anything else means the resume is allowed (2xx) or the server does not understand OPTS REST STOR (5xx)
  3361. if (code == 4)
  3362. {
  3363. ShowStatus(L"Resume not allowed by the server, restarting upload from the scratch.", FZ_LOG_PROGRESS);
  3364. CancelTransferResume(pData);
  3365. }
  3366. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3367. break;
  3368. case FILETRANSFER_REST:
  3369. { //Resume
  3370. if (code==3 || code==2)
  3371. {
  3372. LONG high = 0;
  3373. if (pData->transferfile.get)
  3374. {
  3375. pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
  3376. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3377. {
  3378. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3379. nReplyError = FZ_REPLY_ERROR;
  3380. }
  3381. else
  3382. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3383. }
  3384. else
  3385. {
  3386. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3387. }
  3388. }
  3389. else
  3390. {
  3391. if (code==5 && GetReply()[1]==L'0')
  3392. {
  3393. if (pData->transferfile.get)
  3394. {
  3395. if (pData->transferdata.transfersize!=-1)
  3396. {
  3397. DebugAssert(m_pDataFile);
  3398. if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
  3399. {
  3400. ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, FZ_LOG_STATUS);
  3401. ResetOperation(FZ_REPLY_OK);
  3402. return;
  3403. }
  3404. }
  3405. ShowStatus(IDS_ERRORMSG_CANTRESUME, FZ_LOG_ERROR);
  3406. CancelTransferResume(pData);
  3407. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3408. }
  3409. else
  3410. {
  3411. ShowStatus(L"Resume command not supported by server, trying append.", FZ_LOG_PROGRESS);
  3412. pData->transferdata.bResumeAppend=TRUE;
  3413. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3414. }
  3415. }
  3416. else
  3417. nReplyError=FZ_REPLY_ERROR;
  3418. }
  3419. }
  3420. break;
  3421. case FILETRANSFER_RETRSTOR:
  3422. // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
  3423. // is successful.
  3424. // On failure, it's a 4xy or 5xy reply.
  3425. // However, some servers send a 2xy transfer complete reply without opening a data
  3426. // connection if there's no data to send.
  3427. if (code==2)
  3428. {
  3429. //Transfer successful, however server did not open data connection
  3430. ResetOperation(FZ_REPLY_OK);
  3431. return;
  3432. }
  3433. else if (code!=1)
  3434. {
  3435. if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
  3436. {
  3437. pData->askOnResumeFail = false;
  3438. delete m_pTransferSocket;
  3439. m_pTransferSocket = 0;
  3440. delete m_pDataFile;
  3441. m_pDataFile = 0;
  3442. pData->nGotTransferEndReply = 0;
  3443. nReplyError = CheckOverwriteFile();
  3444. }
  3445. else
  3446. {
  3447. nReplyError = FZ_REPLY_ERROR;
  3448. if (code == 5)
  3449. nReplyError |= FZ_REPLY_CRITICALERROR;
  3450. }
  3451. }
  3452. else
  3453. {
  3454. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  3455. //Look if we can find any information about the resume offset
  3456. if (!pData->transferfile.get && pData->transferdata.bResumeAppend)
  3457. {
  3458. _int64 nOffset = -1;
  3459. CString reply = GetReply();
  3460. reply.MakeLower();
  3461. int pos = reply.Find(L"restarting at offset ");
  3462. if (pos != -1)
  3463. pos += _tcslen(L"restarting at offset ");
  3464. reply = reply.Mid(pos);
  3465. int i;
  3466. for (i=0; i<reply.GetLength(); i++)
  3467. {
  3468. if (reply[i] < L'0' || reply[i] > L'9')
  3469. break;
  3470. }
  3471. if (i == reply.GetLength())
  3472. nOffset = _ttoi64(reply);
  3473. if (nOffset != -1 && m_pDataFile)
  3474. {
  3475. LONG low = 0;
  3476. LONG high = 0;
  3477. if (nOffset >= GetLength64(*m_pDataFile))
  3478. {
  3479. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3480. {
  3481. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3482. nReplyError = FZ_REPLY_ERROR;
  3483. }
  3484. }
  3485. else
  3486. {
  3487. low=static_cast<LONG>(nOffset&0xFFFFFFFF);
  3488. high=static_cast<LONG>(nOffset>>32);
  3489. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3490. {
  3491. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3492. nReplyError = FZ_REPLY_ERROR;
  3493. }
  3494. }
  3495. }
  3496. if (!nReplyError && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3497. {
  3498. nReplyError = ActivateTransferSocket(pData);
  3499. }
  3500. }
  3501. else if (!nReplyError && pData->bPasv && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3502. {
  3503. nReplyError = ActivateTransferSocket(pData);
  3504. }
  3505. }
  3506. break;
  3507. case FILETRANSFER_WAITFINISH:
  3508. if (bFinish)
  3509. {
  3510. if (nError)
  3511. {
  3512. LogMessage(FZ_LOG_INFO, L"Transfer failed");
  3513. }
  3514. else
  3515. {
  3516. LogMessage(FZ_LOG_INFO, L"Transfer completed");
  3517. }
  3518. }
  3519. if (!bFinish)
  3520. {
  3521. if (code == 1)
  3522. {
  3523. /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
  3524. * Just ignore the additional ones.
  3525. */
  3526. LogMessage(FZ_LOG_WARNING, L"Server sent more than one code 1yz reply, ignoring additional reply");
  3527. break;
  3528. }
  3529. else if (code!=2 && code!=3)
  3530. nReplyError = FZ_REPLY_ERROR;
  3531. else
  3532. {
  3533. pData->nGotTransferEndReply |= 1;
  3534. }
  3535. }
  3536. if (pData->nGotTransferEndReply==3)
  3537. {
  3538. // Not really sure about a reason for the m_pDataFile condition here
  3539. TransferFinished(m_pDataFile != NULL);
  3540. return;
  3541. }
  3542. break;
  3543. case FILETRANSFER_MFMT:
  3544. //Transfer successful
  3545. ResetOperation(FZ_REPLY_OK);
  3546. break;
  3547. }
  3548. if (nReplyError)
  3549. { //Error transferring the file
  3550. LogMessage(FZ_LOG_INFO, L"Transfer response error (%x)", nReplyError);
  3551. ResetOperation(nReplyError);
  3552. return;
  3553. }
  3554. }
  3555. /////////////////
  3556. //Send commands//
  3557. /////////////////
  3558. BOOL bError=FALSE;
  3559. switch(m_Operation.nOpState)
  3560. {
  3561. case FILETRANSFER_PWD:
  3562. if (!Send(L"PWD"))
  3563. bError = TRUE;
  3564. break;
  3565. case FILETRANSFER_CWD:
  3566. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3567. bError=TRUE;
  3568. break;
  3569. case FILETRANSFER_MKD:
  3570. if (pData->nMKDOpState==MKD_INIT)
  3571. {
  3572. if (!pData->transferfile.remotepath.HasParent())
  3573. {
  3574. LogMessage(FZ_LOG_WARNING, L"Can't create root dir");
  3575. ResetOperation(FZ_REPLY_CRITICALERROR);
  3576. return;
  3577. }
  3578. if (!Send(L"CWD "+pData->transferfile.remotepath.GetParent().GetPathUnterminated()))
  3579. bError=TRUE;
  3580. pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
  3581. pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
  3582. pData->nMKDOpState=MKD_FINDPARENT;
  3583. }
  3584. break;
  3585. case FILETRANSFER_CWD2:
  3586. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3587. bError=TRUE;
  3588. break;
  3589. case FILETRANSFER_PWD2:
  3590. if (!Send(L"PWD"))
  3591. bError=TRUE;
  3592. break;
  3593. case FILETRANSFER_LIST_PORTPASV:
  3594. delete m_pDirectoryListing;
  3595. m_pDirectoryListing=0;
  3596. if (pData->bPasv)
  3597. {
  3598. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3599. bError=TRUE;
  3600. }
  3601. else
  3602. {
  3603. if (m_pTransferSocket)
  3604. {
  3605. delete m_pTransferSocket;
  3606. }
  3607. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3608. #ifndef MPEXT_NO_GSS
  3609. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3610. m_pTransferSocket->UseGSS(m_pGssLayer);
  3611. #endif
  3612. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3613. m_pTransferSocket->m_bListening = TRUE;
  3614. m_pTransferSocket->SetFamily(GetFamily());
  3615. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3616. bError=TRUE;
  3617. else if (m_pProxyLayer)
  3618. {
  3619. SOCKADDR_IN addr;
  3620. int len=sizeof(addr);
  3621. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3622. {
  3623. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3624. bError=TRUE;
  3625. }
  3626. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3627. {
  3628. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3629. bError=TRUE;
  3630. }
  3631. //Don't send PORT command yet, params are unknown.
  3632. //will be sent in TransfersocketListenFinished
  3633. }
  3634. else
  3635. {
  3636. //Set up an active file transfer
  3637. CString temp;
  3638. UINT nPort;
  3639. if (//create listen socket (let Windows choose the port) & start listening
  3640. !m_pTransferSocket->Listen() ||
  3641. !m_pTransferSocket->GetSockName(temp, nPort))
  3642. {
  3643. bError = TRUE;
  3644. break;
  3645. }
  3646. CString host;
  3647. if (GetFamily() == AF_INET)
  3648. {
  3649. host = GetOption(OPTION_TRANSFERIP);
  3650. if (host != L"")
  3651. {
  3652. DWORD ip = inet_addr(T2CA(host));
  3653. if (ip != INADDR_NONE)
  3654. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3655. else
  3656. {
  3657. hostent *fullname = gethostbyname(T2CA(host));
  3658. if (!fullname)
  3659. host = L"";
  3660. else
  3661. {
  3662. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3663. if (ip != INADDR_NONE)
  3664. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3665. else
  3666. host = L"";
  3667. }
  3668. }
  3669. }
  3670. if (host == L"")
  3671. {
  3672. UINT temp;
  3673. if (!GetSockName(host, temp))
  3674. {
  3675. bError = true;
  3676. break;
  3677. }
  3678. host.Replace(L'.', L',');
  3679. }
  3680. if (!bError)
  3681. {
  3682. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3683. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3684. bError = TRUE;
  3685. }
  3686. }
  3687. else if (GetFamily() == AF_INET6)
  3688. {
  3689. host = GetOption(OPTION_TRANSFERIP6);
  3690. if (host != L"")
  3691. {
  3692. USES_CONVERSION;
  3693. addrinfo hints, *res;
  3694. memset(&hints, 0, sizeof(addrinfo));
  3695. hints.ai_family = AF_INET6;
  3696. hints.ai_socktype = SOCK_STREAM;
  3697. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3698. {
  3699. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3700. freeaddrinfo(res);
  3701. }
  3702. else
  3703. host = L"";
  3704. }
  3705. if (host == L"")
  3706. {
  3707. UINT temp;
  3708. if(!GetSockName(host, temp))
  3709. bError = true;
  3710. }
  3711. if (!bError)
  3712. {
  3713. // assamble EPRT command
  3714. CString cmd;
  3715. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3716. if (!Send(cmd))
  3717. bError = TRUE;
  3718. }
  3719. }
  3720. else
  3721. {
  3722. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3723. bError = true;
  3724. }
  3725. }
  3726. }
  3727. break;
  3728. case FILETRANSFER_LIST_TYPE:
  3729. if (!Send(L"TYPE A"))
  3730. bError=TRUE;
  3731. break;
  3732. case FILETRANSFER_LIST_LIST:
  3733. {
  3734. if (!m_pTransferSocket)
  3735. {
  3736. ResetOperation(FZ_REPLY_ERROR);
  3737. return;
  3738. }
  3739. m_pTransferSocket->SetActive();
  3740. CString cmd = GetListingCmd();
  3741. if(!Send(cmd))
  3742. bError=TRUE;
  3743. else if(pData->bPasv)
  3744. {
  3745. if (!ConnectTransferSocket(pData->host, pData->port))
  3746. {
  3747. bError=TRUE;
  3748. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3749. }
  3750. }
  3751. }
  3752. break;
  3753. case FILETRANSFER_NOLIST_SIZE:
  3754. {
  3755. CString command = L"SIZE ";
  3756. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3757. if (!Send(command))
  3758. bError=TRUE;
  3759. }
  3760. break;
  3761. case FILETRANSFER_NOLIST_MDTM:
  3762. {
  3763. CString command = L"MDTM ";
  3764. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3765. if (!Send(command))
  3766. bError=TRUE;
  3767. }
  3768. break;
  3769. case FILETRANSFER_TYPE:
  3770. if (pData->transferfile.nType==1)
  3771. {
  3772. if (!Send(L"TYPE A"))
  3773. bError=TRUE;
  3774. }
  3775. else
  3776. if (!Send(L"TYPE I"))
  3777. bError=TRUE;
  3778. break;
  3779. case FILETRANSFER_PORTPASV:
  3780. if (pData->bPasv)
  3781. {
  3782. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3783. bError=TRUE;
  3784. }
  3785. else
  3786. {
  3787. if (m_pTransferSocket)
  3788. {
  3789. delete m_pTransferSocket;
  3790. }
  3791. m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
  3792. #ifndef MPEXT_NO_GSS
  3793. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3794. m_pTransferSocket->UseGSS(m_pGssLayer);
  3795. #endif
  3796. m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
  3797. m_pTransferSocket->m_bListening = TRUE;
  3798. m_pTransferSocket->SetFamily(GetFamily());
  3799. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3800. bError = TRUE;
  3801. else if (m_pProxyLayer)
  3802. {
  3803. SOCKADDR_IN addr;
  3804. int len=sizeof(addr);
  3805. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3806. {
  3807. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3808. bError=TRUE;
  3809. }
  3810. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3811. {
  3812. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3813. bError=TRUE;
  3814. }
  3815. //Don't send PORT command yet, params are unknown.
  3816. //will be sent in TransfersocketListenFinished
  3817. }
  3818. else
  3819. {
  3820. //Set up an active file transfer
  3821. CString temp;
  3822. UINT nPort;
  3823. if (//create listen socket (let Windows choose the port) & start listening
  3824. !m_pTransferSocket->Listen() ||
  3825. !m_pTransferSocket->GetSockName(temp, nPort))
  3826. {
  3827. bError = TRUE;
  3828. break;
  3829. }
  3830. CString host;
  3831. if (GetFamily() == AF_INET)
  3832. {
  3833. host = GetOption(OPTION_TRANSFERIP);
  3834. if (host != L"")
  3835. {
  3836. DWORD ip = inet_addr(T2CA(host));
  3837. if (ip != INADDR_NONE)
  3838. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3839. else
  3840. {
  3841. hostent *fullname = gethostbyname(T2CA(host));
  3842. if (!fullname)
  3843. host = L"";
  3844. else
  3845. {
  3846. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3847. if (ip != INADDR_NONE)
  3848. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3849. else
  3850. host = L"";
  3851. }
  3852. }
  3853. }
  3854. if (host == L"")
  3855. {
  3856. UINT temp;
  3857. if (!GetSockName(host, temp))
  3858. bError = true;
  3859. host.Replace(L'.', L',');
  3860. }
  3861. if (!bError)
  3862. {
  3863. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3864. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3865. bError = TRUE;
  3866. }
  3867. }
  3868. else if (GetFamily() == AF_INET6)
  3869. {
  3870. host = GetOption(OPTION_TRANSFERIP6);
  3871. if (host != L"")
  3872. {
  3873. USES_CONVERSION;
  3874. addrinfo hints, *res;
  3875. memset(&hints, 0, sizeof(addrinfo));
  3876. hints.ai_family = AF_INET6;
  3877. hints.ai_socktype = SOCK_STREAM;
  3878. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3879. {
  3880. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3881. freeaddrinfo(res);
  3882. }
  3883. else
  3884. host = L"";
  3885. }
  3886. if (host == L"")
  3887. {
  3888. UINT temp;
  3889. if(!GetSockName(host, temp))
  3890. bError = true;
  3891. }
  3892. if (!bError)
  3893. {
  3894. // assamble EPRT command
  3895. CString cmd;
  3896. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3897. if (!Send(cmd))
  3898. bError = TRUE;
  3899. }
  3900. }
  3901. else
  3902. {
  3903. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3904. bError = true;
  3905. }
  3906. if (bError)
  3907. {
  3908. ResetOperation(FZ_REPLY_ERROR);
  3909. return;
  3910. }
  3911. }
  3912. }
  3913. break;
  3914. case FILETRANSFER_OPTS_REST:
  3915. if (!Send(L"OPTS REST STOR"))
  3916. bError = TRUE;
  3917. break;
  3918. case FILETRANSFER_REST:
  3919. DebugAssert(m_pDataFile);
  3920. {
  3921. CString command;
  3922. __int64 transferoffset =
  3923. pData->transferfile.get ?
  3924. GetLength64(*m_pDataFile) :
  3925. pData->transferdata.transfersize-pData->transferdata.transferleft;
  3926. command.Format(L"REST %I64d", transferoffset);
  3927. if (!Send(command))
  3928. bError=TRUE;
  3929. }
  3930. break;
  3931. case FILETRANSFER_RETRSTOR:
  3932. // send RETR/STOR command to server
  3933. if (!m_pTransferSocket)
  3934. {
  3935. ResetOperation(FZ_REPLY_ERROR);
  3936. return;
  3937. }
  3938. m_pTransferSocket->m_transferdata=pData->transferdata;
  3939. if (GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY) || !pData->bPasv)
  3940. {
  3941. if (ActivateTransferSocket(pData))
  3942. {
  3943. bError = TRUE;
  3944. }
  3945. }
  3946. CString filename;
  3947. filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3948. if(!Send((pData->transferfile.get?L"RETR ":(pData->transferdata.bResumeAppend)?L"APPE ":L"STOR ")+ filename))
  3949. bError = TRUE;
  3950. else
  3951. {
  3952. if (pData->bPasv)
  3953. {
  3954. // if PASV create the socket & initiate outbound data channel connection
  3955. if (!ConnectTransferSocket(pData->host, pData->port))
  3956. {
  3957. bError=TRUE;
  3958. }
  3959. }
  3960. }
  3961. break;
  3962. }
  3963. if (bError)
  3964. { //Error transferring the file
  3965. LogMessage(FZ_LOG_INFO, L"Transfer error");
  3966. ResetOperation(FZ_REPLY_ERROR);
  3967. return;
  3968. }
  3969. }
  3970. void CFtpControlSocket::TransferHandleListError()
  3971. {
  3972. if (m_pTransferSocket)
  3973. delete m_pTransferSocket;
  3974. m_pTransferSocket=0;
  3975. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  3976. }
  3977. static int atoui(const wchar_t * s)
  3978. {
  3979. wchar_t * endptr;
  3980. int result = wcstol(s, &endptr, 10);
  3981. if ((*s == L'\0') || (*endptr != L'\0'))
  3982. {
  3983. result = -1;
  3984. }
  3985. return result;
  3986. }
  3987. bool CFtpControlSocket::HandleMdtm(int code, t_directory::t_direntry::t_date & date)
  3988. {
  3989. bool result = false;
  3990. if (code==2)
  3991. {
  3992. CString line = GetReply();
  3993. if ( line.GetLength()>4 && line.Left(4) == L"213 " )
  3994. {
  3995. int y=0, M=0, d=0, h=0, m=0, s=0;
  3996. bool hasseconds = false;
  3997. line=line.Mid(4);
  3998. y=atoui(line.Left(4));
  3999. if ((y >= 0) && (line.GetLength() > 4))
  4000. {
  4001. line=line.Mid(4);
  4002. M=atoui(line.Left(2));
  4003. if ((M >= 0) && (line.GetLength() > 2))
  4004. {
  4005. line=line.Mid(2);
  4006. d=atoui(line.Left(2));
  4007. if ((d >= 0) && (line.GetLength() > 2))
  4008. {
  4009. line=line.Mid(2);
  4010. h=atoui(line.Left(2));
  4011. if ((h >= 0) && (line.GetLength() > 2))
  4012. {
  4013. line=line.Mid(2);
  4014. m=atoui(line.Left(2));
  4015. if ((m >= 0) && (line.GetLength() > 2))
  4016. {
  4017. line=line.Mid(2);
  4018. s=_ttoi(line.Left(2));
  4019. hasseconds = true;
  4020. }
  4021. }
  4022. }
  4023. if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60 && s>=0 && s<60)
  4024. {
  4025. result = true;
  4026. date.year = y;
  4027. date.month = M;
  4028. date.day = d;
  4029. date.hour = h;
  4030. date.minute = m;
  4031. date.second = s;
  4032. date.hastime = true;
  4033. date.hasyear = true;
  4034. date.hasseconds = hasseconds;
  4035. date.hasdate = true;
  4036. date.utc = true;
  4037. }
  4038. }
  4039. }
  4040. }
  4041. }
  4042. return result;
  4043. }
  4044. bool CFtpControlSocket::HandleSize(int code, __int64 & size)
  4045. {
  4046. bool result = false;
  4047. if (code == 2)
  4048. {
  4049. CString line = GetReply();
  4050. if ((line.GetLength() > 4) && (line.Left(4) == L"213 "))
  4051. {
  4052. size = _ttoi64(line.Mid(4));
  4053. result = true;
  4054. }
  4055. }
  4056. return result;
  4057. }
  4058. void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads)
  4059. {
  4060. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  4061. if (GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) &&
  4062. m_pDataFile &&
  4063. pData->transferfile.get &&
  4064. DebugAlwaysTrue(pData->transferfile.OnTransferOut == NULL))
  4065. {
  4066. m_pTools->PreserveDownloadFileTime(
  4067. (HANDLE)m_pDataFile->m_hFile, reinterpret_cast<void *>(pData->transferfile.nUserData));
  4068. }
  4069. if (!pData->transferfile.get &&
  4070. GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && preserveFileTimeForUploads &&
  4071. ((m_serverCapabilities.GetCapability(mfmt_command) == yes) ||
  4072. (m_serverCapabilities.GetCapability(mdtm_command) == yes)) &&
  4073. DebugAlwaysTrue(pData->transferfile.OnTransferIn == NULL))
  4074. {
  4075. CString filename =
  4076. pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4077. struct tm tm;
  4078. if (m_pTools->GetFileModificationTimeInUtc((LPCTSTR)pData->transferfile.localfile, tm))
  4079. {
  4080. CString timestr;
  4081. timestr.Format(L"%02d%02d%02d%02d%02d%02d",
  4082. 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  4083. CString command;
  4084. if (m_serverCapabilities.GetCapability(mfmt_command) == yes)
  4085. {
  4086. command = L"MFMT";
  4087. }
  4088. else
  4089. {
  4090. // Support for MDTM does not necessarily mean
  4091. // that the server supports non-standard hack
  4092. // of setting timestamp using
  4093. // MFMT-like (two argument) call to MDTM.
  4094. // IIS definitely does.
  4095. command = L"MDTM";
  4096. }
  4097. if (Send( command + L" " + timestr + L" " + filename))
  4098. {
  4099. m_Operation.nOpState = FILETRANSFER_MFMT;
  4100. return;
  4101. }
  4102. }
  4103. }
  4104. //Transfer successful
  4105. ResetOperation(FZ_REPLY_OK);
  4106. }
  4107. void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
  4108. {
  4109. const int nOpMode = m_Operation.nOpMode;
  4110. if (nOpMode==CSMODE_CONNECT)
  4111. DoClose(FZ_REPLY_CANCEL);
  4112. else if (nOpMode & CSMODE_LIST)
  4113. {
  4114. if (m_Operation.nOpState == LIST_WAITFINISH)
  4115. m_skipReply = true;
  4116. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4117. }
  4118. else if (nOpMode & CSMODE_TRANSFER)
  4119. {
  4120. if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
  4121. m_skipReply = true;
  4122. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
  4123. }
  4124. else if (nOpMode != CSMODE_NONE)
  4125. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4126. if (nOpMode != CSMODE_NONE && !bQuit)
  4127. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  4128. if (m_awaitsReply)
  4129. m_skipReply = true;
  4130. }
  4131. void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
  4132. {
  4133. if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
  4134. {
  4135. CString host;
  4136. host.Format(L"%d,%d,%d,%d,%d,%d",ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
  4137. Send(L"PORT "+host);
  4138. }
  4139. }
  4140. void CFtpControlSocket::ResumeTransfer()
  4141. {
  4142. if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
  4143. {
  4144. m_pTransferSocket->OnSend(0);
  4145. m_pTransferSocket->OnReceive(0);
  4146. }
  4147. }
  4148. BOOL CFtpControlSocket::Create()
  4149. {
  4150. return CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET);
  4151. }
  4152. void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
  4153. {
  4154. if (nSuccessful & FZ_REPLY_CRITICALERROR)
  4155. nSuccessful |= FZ_REPLY_ERROR;
  4156. if (m_pTransferSocket)
  4157. {
  4158. ResetTransferSocket(nSuccessful & (FZ_REPLY_ERROR | FZ_REPLY_CANCEL));
  4159. }
  4160. if (m_pDataFile)
  4161. delete m_pDataFile;
  4162. m_pDataFile=0;
  4163. if (m_Operation.nOpMode)
  4164. {
  4165. //Unset busy attribute so that new commands can be executed
  4166. m_pOwner->SetBusy(FALSE);
  4167. if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
  4168. {
  4169. nSuccessful|=FZ_REPLY_DISCONNECTED;
  4170. ShowStatus(IDS_ERRORMSG_CANTCONNECT, FZ_LOG_ERROR);
  4171. }
  4172. if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_LISTFILE|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
  4173. m_LastSendTime=CTime::CreateForCurrentTime();
  4174. //Update remote file entry
  4175. if (m_Operation.pData &&
  4176. m_Operation.nOpMode&CSMODE_TRANSFER &&
  4177. (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
  4178. m_pDirectoryListing &&
  4179. m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
  4180. {
  4181. CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
  4182. CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
  4183. t_directory dir;
  4184. BOOL res=FALSE;
  4185. if (m_pDirectoryListing)
  4186. {
  4187. if (m_pDirectoryListing->path==path)
  4188. {
  4189. dir=*m_pDirectoryListing;
  4190. res=TRUE;
  4191. }
  4192. }
  4193. t_directory WorkingDir;
  4194. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4195. if (!res && bFound)
  4196. if (WorkingDir.path==path)
  4197. {
  4198. dir=WorkingDir;
  4199. res=TRUE;
  4200. }
  4201. if (res)
  4202. {
  4203. int i;
  4204. for (i=0; i<dir.num; i++)
  4205. if (dir.direntry[i].name==filename)
  4206. {
  4207. dir.direntry[i].bUnsure = TRUE;
  4208. if (nSuccessful & FZ_REPLY_ERROR)
  4209. {
  4210. dir.direntry[i].bUnsure = TRUE;
  4211. if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
  4212. dir.direntry[i].size = -1;
  4213. if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
  4214. dir.direntry[i].size = -1;
  4215. }
  4216. dir.direntry[i].date.hasdate = false;
  4217. break;
  4218. }
  4219. if (i==dir.num)
  4220. {
  4221. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4222. int i;
  4223. for (i=0; i<dir.num; i++)
  4224. entries[i]=dir.direntry[i];
  4225. entries[i].name=filename;
  4226. entries[i].dir=FALSE;
  4227. entries[i].date.hasdate=FALSE;
  4228. entries[i].size=-1;
  4229. if (nSuccessful&FZ_REPLY_OK)
  4230. entries[i].bUnsure=FALSE;
  4231. else
  4232. entries[i].bUnsure=TRUE;
  4233. delete [] dir.direntry;
  4234. dir.direntry=entries;
  4235. dir.num++;
  4236. }
  4237. BOOL updated=FALSE;
  4238. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  4239. {
  4240. updated=TRUE;
  4241. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4242. }
  4243. if (!updated)
  4244. if (bFound && WorkingDir.path==dir.path)
  4245. {
  4246. updated = TRUE;
  4247. m_pOwner->SetWorkingDir(&dir);
  4248. }
  4249. }
  4250. }
  4251. if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
  4252. {
  4253. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  4254. if (nSuccessful&FZ_REPLY_ABORTED)
  4255. //Transfer aborted by user
  4256. ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,FZ_LOG_ERROR);
  4257. else
  4258. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR);
  4259. else if (m_Operation.nOpMode&CSMODE_LIST)
  4260. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  4261. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  4262. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4263. }
  4264. else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
  4265. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS);
  4266. }
  4267. else
  4268. {
  4269. // When control socket is waiting for reply
  4270. // to keepalive (!IsReady), while new command comes,
  4271. // its execution is postponed
  4272. // (CMainThread::m_pPostKeepAliveCommand),
  4273. // but the main thread
  4274. // is set to busy state already (CMainThread::Command).
  4275. // if connection is closed before without receiving reply,
  4276. // main thread would stay busy forever.
  4277. m_pOwner->SetBusy(FALSE);
  4278. //No operation in progress
  4279. nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
  4280. }
  4281. if (nSuccessful&FZ_REPLY_DISCONNECTED)
  4282. m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
  4283. if (m_Operation.nOpMode)
  4284. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
  4285. else
  4286. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
  4287. m_Operation.nOpMode=0;
  4288. m_Operation.nOpState=-1;
  4289. if (m_Operation.pData)
  4290. delete m_Operation.pData;
  4291. m_Operation.pData=0;
  4292. }
  4293. void CFtpControlSocket::Delete(CString filename, const CServerPath &path, bool filenameOnly)
  4294. {
  4295. class CDeleteData : public CFtpControlSocket::t_operation::COpData
  4296. {
  4297. public:
  4298. CDeleteData() {}
  4299. virtual ~CDeleteData() {}
  4300. CString m_FileName;
  4301. CServerPath path;
  4302. };
  4303. if (filename!=L"")
  4304. {
  4305. DebugAssert(!path.IsEmpty());
  4306. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4307. DebugAssert(m_Operation.nOpState==-1);
  4308. DebugAssert(!m_Operation.pData);
  4309. m_Operation.nOpMode=CSMODE_DELETE;
  4310. CString command = L"DELE ";
  4311. if (!filenameOnly)
  4312. {
  4313. command += path.FormatFilename(filename);
  4314. }
  4315. else
  4316. {
  4317. command += filename;
  4318. }
  4319. if (!Send(command))
  4320. return;
  4321. CDeleteData *data=new CDeleteData;
  4322. data->m_FileName=filename;
  4323. data->path=path;
  4324. m_Operation.pData=data;
  4325. }
  4326. else
  4327. {
  4328. DebugAssert(path.IsEmpty());
  4329. DebugAssert(m_Operation.nOpMode==CSMODE_DELETE);
  4330. DebugAssert(m_Operation.nOpState==-1);
  4331. DebugAssert(m_Operation.pData);
  4332. int res=GetReplyCode();
  4333. if (res==2 || res==3)
  4334. { //Remove file from cached dirs
  4335. CDeleteData *pData=(CDeleteData *)m_Operation.pData;
  4336. t_directory dir;
  4337. BOOL res=FALSE;
  4338. if (m_pDirectoryListing)
  4339. {
  4340. if (m_pDirectoryListing->path==pData->path)
  4341. {
  4342. dir=*m_pDirectoryListing;
  4343. res=TRUE;
  4344. }
  4345. }
  4346. t_directory WorkingDir;
  4347. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4348. if (!res && bFound)
  4349. if (WorkingDir.path==pData->path)
  4350. {
  4351. dir=WorkingDir;
  4352. res=TRUE;
  4353. }
  4354. if (res)
  4355. {
  4356. BOOL found=FALSE;
  4357. for (int i=0;i<dir.num;i++)
  4358. {
  4359. if (dir.direntry[i].name==pData->m_FileName)
  4360. {
  4361. DebugAssert(!dir.direntry[i].dir || dir.direntry[i].bLink);
  4362. found=TRUE;
  4363. break;
  4364. }
  4365. }
  4366. if (found)
  4367. {
  4368. t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
  4369. int j=0;
  4370. int i;
  4371. for (i=0; i<dir.num; i++)
  4372. {
  4373. if (dir.direntry[i].name==pData->m_FileName)
  4374. continue;
  4375. direntry[j]=dir.direntry[i];
  4376. j++;
  4377. }
  4378. delete [] dir.direntry;
  4379. dir.direntry=direntry;
  4380. dir.num--;
  4381. BOOL updated=FALSE;
  4382. if (m_pDirectoryListing)
  4383. if (m_pDirectoryListing->path==dir.path)
  4384. {
  4385. updated=TRUE;
  4386. SetDirectoryListing(&dir);
  4387. }
  4388. if (!updated)
  4389. if (WorkingDir.path==dir.path)
  4390. {
  4391. updated=TRUE;
  4392. m_pOwner->SetWorkingDir(&dir);
  4393. }
  4394. }
  4395. }
  4396. }
  4397. ResetOperation(FZ_REPLY_OK);
  4398. }
  4399. }
  4400. void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
  4401. {
  4402. class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
  4403. {
  4404. public:
  4405. CRemoveDirData() {}
  4406. virtual ~CRemoveDirData() {}
  4407. CString m_DirName;
  4408. CServerPath path;
  4409. };
  4410. if (dirname != L"")
  4411. {
  4412. DebugAssert(!path.IsEmpty());
  4413. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4414. DebugAssert(m_Operation.nOpState == -1);
  4415. DebugAssert(!m_Operation.pData);
  4416. m_Operation.nOpMode = CSMODE_RMDIR;
  4417. CServerPath newPath = path;
  4418. if (!newPath.AddSubdir(dirname))
  4419. {
  4420. ShowStatus(L"Unable to concatenate path", FZ_LOG_ERROR);
  4421. return;
  4422. }
  4423. if (!Send(L"RMD "+ newPath.GetPathUnterminated()))
  4424. return;
  4425. CRemoveDirData *data = new CRemoveDirData;
  4426. data->m_DirName = dirname;
  4427. data->path = path;
  4428. m_Operation.pData = data;
  4429. }
  4430. else
  4431. {
  4432. DebugAssert(path.IsEmpty());
  4433. DebugAssert(m_Operation.nOpMode == CSMODE_RMDIR);
  4434. DebugAssert(m_Operation.nOpState == -1);
  4435. DebugAssert(m_Operation.pData);
  4436. int res = GetReplyCode();
  4437. if (res == 2 || res == 3)
  4438. { //Remove dir from cached dirs
  4439. CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData;
  4440. t_directory dir;
  4441. BOOL res = FALSE;
  4442. if (m_pDirectoryListing)
  4443. {
  4444. if (m_pDirectoryListing->path == pData->path)
  4445. {
  4446. dir = *m_pDirectoryListing;
  4447. res = TRUE;
  4448. }
  4449. }
  4450. t_directory WorkingDir;
  4451. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4452. if (!res && bFound)
  4453. if (WorkingDir.path == pData->path)
  4454. {
  4455. dir = WorkingDir;
  4456. res = TRUE;
  4457. }
  4458. if (res)
  4459. {
  4460. BOOL found = FALSE;
  4461. for (int i = 0; i < dir.num; i++)
  4462. {
  4463. if (dir.direntry[i].name == pData->m_DirName)
  4464. {
  4465. DebugAssert(dir.direntry[i].dir);
  4466. found = TRUE;
  4467. break;
  4468. }
  4469. }
  4470. if (found)
  4471. {
  4472. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
  4473. int j = 0;
  4474. int i;
  4475. for (i = 0; i < dir.num; i++)
  4476. {
  4477. if (dir.direntry[i].name == pData->m_DirName)
  4478. continue;
  4479. direntry[j] = dir.direntry[i];
  4480. j++;
  4481. }
  4482. delete [] dir.direntry;
  4483. dir.direntry = direntry;
  4484. dir.num--;
  4485. BOOL updated = FALSE;
  4486. if (m_pDirectoryListing)
  4487. if (m_pDirectoryListing->path == dir.path)
  4488. {
  4489. updated = TRUE;
  4490. SetDirectoryListing(&dir);
  4491. }
  4492. if (!updated)
  4493. if (WorkingDir.path == dir.path)
  4494. {
  4495. updated = TRUE;
  4496. m_pOwner->SetWorkingDir(&dir);
  4497. }
  4498. }
  4499. }
  4500. ResetOperation(FZ_REPLY_OK);
  4501. }
  4502. else
  4503. ResetOperation(FZ_REPLY_ERROR);
  4504. }
  4505. }
  4506. int CFtpControlSocket::FileTransferHandleDirectoryListing(t_directory * pDirectory)
  4507. {
  4508. SetDirectoryListing(pDirectory);
  4509. m_Operation.nOpState = FILETRANSFER_TYPE;
  4510. delete m_pTransferSocket;
  4511. m_pTransferSocket = 0;
  4512. return CheckOverwriteFileAndCreateTarget();
  4513. }
  4514. int CFtpControlSocket::CheckOverwriteFileAndCreateTarget()
  4515. {
  4516. int nReplyError = CheckOverwriteFile();
  4517. if (!nReplyError)
  4518. {
  4519. CFileTransferData * pData = static_cast<CFileTransferData *>(m_Operation.pData);
  4520. if (pData->transferfile.get && (pData->transferfile.OnTransferOut == NULL))
  4521. {
  4522. CString path = pData->transferfile.localfile;
  4523. if (path.ReverseFind(L'\\') != -1)
  4524. {
  4525. path = path.Left(path.ReverseFind(L'\\')+1);
  4526. CString path2;
  4527. while (path != L"")
  4528. {
  4529. path2 += path.Left(path.Find(L"\\") + 1);
  4530. path = path.Mid(path.Find(L"\\") + 1);
  4531. CreateDirectory(path2, 0);
  4532. }
  4533. }
  4534. }
  4535. }
  4536. return nReplyError;
  4537. }
  4538. int CFtpControlSocket::CheckOverwriteFile()
  4539. {
  4540. if (!m_Operation.pData)
  4541. {
  4542. return FZ_REPLY_ERROR;
  4543. }
  4544. CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
  4545. int nReplyError = 0;
  4546. CFileStatus status;
  4547. if ((pData->transferfile.OnTransferOut != NULL) ||
  4548. (pData->transferfile.OnTransferIn != NULL))
  4549. {
  4550. m_Operation.nOpState = FILETRANSFER_TYPE;
  4551. }
  4552. else if (!GetFileStatus(pData->transferfile.localfile, status))
  4553. {
  4554. if (!pData->transferfile.get)
  4555. {
  4556. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4557. nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
  4558. }
  4559. else
  4560. {
  4561. m_Operation.nOpState = FILETRANSFER_TYPE;
  4562. }
  4563. }
  4564. else
  4565. {
  4566. if (status.m_attribute & 0x10)
  4567. {
  4568. nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
  4569. }
  4570. else
  4571. {
  4572. _int64 localsize;
  4573. if (!GetLength64(pData->transferfile.localfile, localsize))
  4574. if (!pData->transferfile.get)
  4575. nReplyError = FZ_REPLY_CRITICALERROR;
  4576. else
  4577. m_Operation.nOpState = FILETRANSFER_TYPE;
  4578. CTime *localtime = NULL;
  4579. if (status.m_mtime != -1)
  4580. localtime = new CTime(status.m_mtime);
  4581. BOOL bRemoteFileExists = FALSE;
  4582. __int64 remotesize = -1;
  4583. t_directory::t_direntry::t_date remotetime;
  4584. if (m_pDirectoryListing)
  4585. {
  4586. for (int i=0; i<m_pDirectoryListing->num; i++)
  4587. {
  4588. CString remotefile = pData->transferfile.remotefile;
  4589. if (m_pDirectoryListing->direntry[i].name == remotefile)
  4590. {
  4591. remotesize = m_pDirectoryListing->direntry[i].size;
  4592. remotetime = m_pDirectoryListing->direntry[i].date;
  4593. bRemoteFileExists = TRUE;
  4594. break;
  4595. }
  4596. }
  4597. }
  4598. if (!bRemoteFileExists && pData->hasRemoteDate)
  4599. {
  4600. remotetime = pData->remoteDate;
  4601. bRemoteFileExists = TRUE;
  4602. }
  4603. if (remotesize == -1 && pData->pFileSize)
  4604. {
  4605. remotesize = *pData->pFileSize;
  4606. bRemoteFileExists = TRUE;
  4607. }
  4608. if (bRemoteFileExists || pData->transferfile.get )
  4609. {
  4610. COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
  4611. t_transferfile *pTransferFile = new t_transferfile;
  4612. *pTransferFile = pData->transferfile;
  4613. pOverwriteData->pTransferFile = pTransferFile;
  4614. if (pData->transferfile.get)
  4615. {
  4616. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4617. // pos can be -1 here, e.g. in scripting, the code below still works then
  4618. pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
  4619. pOverwriteData->FileName2 = pData->transferfile.remotefile;
  4620. pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
  4621. pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
  4622. pOverwriteData->size1 = localsize;
  4623. pOverwriteData->size2 = remotesize;
  4624. }
  4625. else
  4626. {
  4627. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4628. // pos can be -1 here, e.g. in scripting, the code below still works then
  4629. pOverwriteData->FileName1 = pData->transferfile.remotefile;
  4630. pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
  4631. pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
  4632. pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
  4633. pOverwriteData->size1 = remotesize;
  4634. pOverwriteData->size2 = localsize;
  4635. }
  4636. pOverwriteData->localtime = localtime;
  4637. pOverwriteData->remotetime = remotetime;
  4638. pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  4639. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
  4640. {
  4641. delete pOverwriteData;
  4642. nReplyError = FZ_REPLY_ERROR;
  4643. }
  4644. else
  4645. {
  4646. m_bCheckForTimeout = FALSE;
  4647. m_Operation.nOpState = FILETRANSFER_WAIT;
  4648. }
  4649. }
  4650. else
  4651. {
  4652. m_Operation.nOpState = FILETRANSFER_TYPE;
  4653. delete localtime;
  4654. }
  4655. }
  4656. }
  4657. return nReplyError;
  4658. }
  4659. void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
  4660. {
  4661. if (!pData)
  4662. return;
  4663. if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
  4664. return;
  4665. if (m_Operation.nOpState != FILETRANSFER_WAIT)
  4666. return;
  4667. CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
  4668. if (!pTransferData)
  4669. return;
  4670. pTransferData->transferdata.bResume = false;
  4671. m_bCheckForTimeout = TRUE;
  4672. int nReplyError = 0;
  4673. switch (nAction)
  4674. {
  4675. case FILEEXISTS_SKIP:
  4676. nReplyError = FZ_REPLY_OK;
  4677. break;
  4678. case FILEEXISTS_OVERWRITE:
  4679. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4680. break;
  4681. case FILEEXISTS_RENAME:
  4682. if (pTransferData->transferfile.get)
  4683. {
  4684. if (CFile::IsValid(pData->FileName1))
  4685. {
  4686. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4687. nReplyError= FZ_REPLY_CRITICALERROR;
  4688. }
  4689. else
  4690. {
  4691. pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
  4692. //Replace invalid characters in the local filename
  4693. int pos = pTransferData->transferfile.localfile.ReverseFind(L'\\');
  4694. for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
  4695. if (pTransferData->transferfile.localfile[i] == L':')
  4696. pTransferData->transferfile.localfile.SetAt(i, L'_');
  4697. pTransferData->nWaitNextOpState= FILETRANSFER_TYPE;
  4698. }
  4699. }
  4700. else
  4701. {
  4702. DebugAssert(m_pDirectoryListing);
  4703. int i;
  4704. for (i = 0; i < m_pDirectoryListing->num; i++)
  4705. {
  4706. if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
  4707. {
  4708. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4709. nReplyError = FZ_REPLY_CRITICALERROR;
  4710. break;
  4711. }
  4712. }
  4713. if (i==m_pDirectoryListing->num)
  4714. {
  4715. pTransferData->transferfile.remotefile = pData->FileName1;
  4716. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4717. }
  4718. }
  4719. break;
  4720. case FILEEXISTS_RESUME:
  4721. if (pData->size1 >= 0)
  4722. {
  4723. pTransferData->transferdata.bResume = TRUE;
  4724. }
  4725. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4726. break;
  4727. case FILEEXISTS_COMPLETE:
  4728. // Simulating transfer finish
  4729. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  4730. TransferFinished(true);
  4731. return; // Avoid call to FileTransfer below
  4732. }
  4733. if (nReplyError == FZ_REPLY_OK)
  4734. ResetOperation(FZ_REPLY_OK);
  4735. else if (nReplyError)
  4736. ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
  4737. else
  4738. FileTransfer();
  4739. }
  4740. void CFtpControlSocket::SendKeepAliveCommand()
  4741. {
  4742. ShowStatus(L"Sending dummy command to keep session alive.", FZ_LOG_PROGRESS);
  4743. m_bKeepAliveActive=TRUE;
  4744. //Choose a random command from the list
  4745. TCHAR commands[4][7]={L"PWD",L"REST 0",L"TYPE A",L"TYPE I"};
  4746. int choice=(rand()*4)/(RAND_MAX+1);
  4747. Send(commands[choice]);
  4748. }
  4749. void CFtpControlSocket::MakeDir(const CServerPath &path)
  4750. {
  4751. //Directory creation works like this:
  4752. //Find existing parent and create subdirs one by one
  4753. if (m_Operation.nOpState == MKD_INIT)
  4754. {
  4755. DebugAssert(!path.IsEmpty());
  4756. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4757. DebugAssert(!m_Operation.pData);
  4758. m_Operation.nOpMode = CSMODE_MKDIR;
  4759. if (!Send(L"CWD "+path.GetParent().GetPathUnterminated()))
  4760. return;
  4761. CMakeDirData *data = new CMakeDirData;
  4762. data->path = path;
  4763. data->Current = path.GetParent();
  4764. data->Segments.push_front(path.GetLastSegment());
  4765. m_Operation.pData = data;
  4766. m_Operation.nOpState = MKD_FINDPARENT;
  4767. }
  4768. else if (m_Operation.nOpState==MKD_FINDPARENT)
  4769. {
  4770. DebugAssert(m_Operation.nOpMode==CSMODE_MKDIR);
  4771. DebugAssert(path.IsEmpty());
  4772. DebugAssert(m_Operation.pData);
  4773. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4774. int res=GetReplyCode();
  4775. if (res==2 || res==3)
  4776. {
  4777. m_pOwner->SetCurrentPath(pData->Current);
  4778. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4779. pData->Current.AddSubdir(pData->Segments.front());
  4780. CString Segment=pData->Segments.front();
  4781. pData->Segments.pop_front();
  4782. if (Send( L"MKD " + Segment))
  4783. m_Operation.nOpState = MKD_CHANGETOSUBDIR;
  4784. else
  4785. return;
  4786. }
  4787. else
  4788. {
  4789. if (!pData->Current.HasParent())
  4790. ResetOperation(FZ_REPLY_ERROR);
  4791. else
  4792. {
  4793. pData->Segments.push_front(pData->Current.GetLastSegment());
  4794. pData->Current=pData->Current.GetParent();
  4795. if (!Send(L"CWD "+pData->Current.GetPathUnterminated()))
  4796. return;
  4797. }
  4798. }
  4799. }
  4800. else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
  4801. {
  4802. int res=GetReplyCode();
  4803. if (res==2 || res==3)
  4804. { //Create dir entry in parent dir
  4805. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4806. DebugAssert(!pData->Segments.empty());
  4807. m_pOwner->SetCurrentPath(pData->Current);
  4808. pData->Current.AddSubdir(pData->Segments.front());
  4809. CString Segment=pData->Segments.front();
  4810. pData->Segments.pop_front();
  4811. if (Send( L"MKD " + Segment))
  4812. m_Operation.nOpState=MKD_CHANGETOSUBDIR;
  4813. else
  4814. return;
  4815. }
  4816. else
  4817. ResetOperation(FZ_REPLY_ERROR);
  4818. }
  4819. else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
  4820. {
  4821. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4822. int res=GetReplyCode();
  4823. if (res==2 || res==3 || //Creation successful
  4824. GetReply() == L"550 Directory already exists")//Creation was successful, although someone else did the work for us
  4825. { //Create dir entry in parent dir
  4826. CServerPath path2=pData->Current;
  4827. if (path2.HasParent())
  4828. {
  4829. CString name=path2.GetLastSegment();
  4830. path2=path2.GetParent();
  4831. t_directory dir;
  4832. BOOL res = FALSE;
  4833. if (m_pDirectoryListing)
  4834. {
  4835. if (m_pDirectoryListing->path == path2)
  4836. {
  4837. dir = *m_pDirectoryListing;
  4838. res = TRUE;
  4839. }
  4840. }
  4841. t_directory WorkingDir;
  4842. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4843. if (!res && bFound)
  4844. if (WorkingDir.path == path2)
  4845. {
  4846. dir = WorkingDir;
  4847. res = TRUE;
  4848. }
  4849. if (!res)
  4850. {
  4851. dir.path = path2;
  4852. dir.server = m_CurrentServer;
  4853. }
  4854. int i;
  4855. for (i=0; i<dir.num; i++)
  4856. if (dir.direntry[i].name==name)
  4857. {
  4858. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  4859. break;
  4860. }
  4861. if (i==dir.num)
  4862. {
  4863. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4864. for (i=0;i<dir.num;i++)
  4865. entries[i]=dir.direntry[i];
  4866. entries[i].name=name;
  4867. entries[i].dir=TRUE;
  4868. entries[i].date.hasdate=FALSE;
  4869. entries[i].size=-1;
  4870. entries[i].bUnsure=FALSE;
  4871. delete [] dir.direntry;
  4872. dir.direntry=entries;
  4873. dir.num++;
  4874. BOOL updated = FALSE;
  4875. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4876. {
  4877. updated = TRUE;
  4878. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4879. }
  4880. if (!updated)
  4881. if (bFound && WorkingDir.path == dir.path)
  4882. {
  4883. updated = TRUE;
  4884. m_pOwner->SetWorkingDir(&dir);
  4885. }
  4886. }
  4887. }
  4888. }
  4889. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  4890. if (pData->Segments.empty())
  4891. ResetOperation(FZ_REPLY_OK);
  4892. else
  4893. {
  4894. if (Send( L"CWD " + pData->Current.GetPathUnterminated()))
  4895. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4896. else
  4897. return;
  4898. }
  4899. }
  4900. else
  4901. DebugFail();
  4902. }
  4903. void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
  4904. {
  4905. class CRenameData : public CFtpControlSocket::t_operation::COpData
  4906. {
  4907. public:
  4908. CRenameData() {}
  4909. virtual ~CRenameData() {}
  4910. CString oldName, newName;
  4911. CServerPath path;
  4912. CServerPath newPath;
  4913. };
  4914. if (oldName != L"")
  4915. {
  4916. DebugAssert(newName != L"");
  4917. DebugAssert(!path.IsEmpty());
  4918. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4919. DebugAssert(m_Operation.nOpState == -1);
  4920. DebugAssert(!m_Operation.pData);
  4921. m_Operation.nOpMode = CSMODE_RENAME;
  4922. if (!Send(L"RNFR " + path.FormatFilename(oldName)))
  4923. return;
  4924. CRenameData *data = new CRenameData;
  4925. data->oldName = oldName;
  4926. data->newName = newName;
  4927. data->path = path;
  4928. data->newPath = newPath;
  4929. m_Operation.pData = data;
  4930. }
  4931. else
  4932. {
  4933. DebugAssert(oldName == L"");
  4934. DebugAssert(path.IsEmpty());
  4935. DebugAssert(m_Operation.nOpMode == CSMODE_RENAME);
  4936. DebugAssert(m_Operation.pData);
  4937. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  4938. if (m_Operation.nOpState == -1)
  4939. {
  4940. int res = GetReplyCode();
  4941. if (res == 2 || res == 3)
  4942. {
  4943. m_Operation.nOpState++;
  4944. if (pData->newPath.IsEmpty())
  4945. {
  4946. if (!Send(L"RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  4947. return;
  4948. }
  4949. else
  4950. if (!Send(L"RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  4951. return;
  4952. }
  4953. else
  4954. ResetOperation(FZ_REPLY_ERROR);
  4955. }
  4956. else
  4957. {
  4958. int res = GetReplyCode();
  4959. if (res == 2 || res == 3)
  4960. { //Rename entry in cached directory
  4961. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  4962. t_directory dir;
  4963. BOOL res = FALSE;
  4964. if (m_pDirectoryListing)
  4965. {
  4966. if (m_pDirectoryListing->path == pData->path)
  4967. {
  4968. dir = *m_pDirectoryListing;
  4969. res = TRUE;
  4970. }
  4971. }
  4972. t_directory WorkingDir;
  4973. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4974. if (!res && bFound)
  4975. if (WorkingDir.path == pData->path)
  4976. {
  4977. dir = WorkingDir;
  4978. res = TRUE;
  4979. }
  4980. if (res)
  4981. {
  4982. for (int i=0; i<dir.num; i++)
  4983. if (dir.direntry[i].name == pData->oldName)
  4984. {
  4985. if (pData->newPath.IsEmpty())
  4986. {
  4987. dir.direntry[i].name = pData->newName;
  4988. BOOL updated = FALSE;
  4989. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4990. {
  4991. updated = TRUE;
  4992. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  4993. }
  4994. if (!updated)
  4995. if (WorkingDir.path == dir.path)
  4996. {
  4997. updated = TRUE;
  4998. m_pOwner->SetWorkingDir(&dir);
  4999. }
  5000. }
  5001. else
  5002. {
  5003. t_directory::t_direntry oldentry = dir.direntry[i];
  5004. for (int j = i+1; j < dir.num; j++)
  5005. {
  5006. dir.direntry[j-1] = dir.direntry[j];
  5007. }
  5008. dir.num--;
  5009. BOOL updated = FALSE;
  5010. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5011. {
  5012. updated = TRUE;
  5013. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5014. }
  5015. if (!updated)
  5016. if (WorkingDir.path == dir.path)
  5017. {
  5018. updated = TRUE;
  5019. m_pOwner->SetWorkingDir(&dir);
  5020. }
  5021. BOOL res = FALSE;
  5022. if (m_pDirectoryListing)
  5023. {
  5024. if (m_pDirectoryListing->path == pData->newPath)
  5025. {
  5026. dir = *m_pDirectoryListing;
  5027. res = TRUE;
  5028. }
  5029. }
  5030. t_directory WorkingDir;
  5031. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5032. if (!res && bFound)
  5033. if (WorkingDir.path == pData->newPath)
  5034. {
  5035. dir = WorkingDir;
  5036. res = TRUE;
  5037. }
  5038. if (res)
  5039. {
  5040. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
  5041. for (int i = 0; i < dir.num; i++)
  5042. direntry[i] = dir.direntry[i];
  5043. direntry[dir.num] = oldentry;
  5044. direntry[dir.num].name = pData->newName;
  5045. dir.num++;
  5046. delete [] dir.direntry;
  5047. dir.direntry = direntry;
  5048. BOOL updated = FALSE;
  5049. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5050. {
  5051. updated = TRUE;
  5052. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5053. }
  5054. if (!updated)
  5055. if (bFound && WorkingDir.path == dir.path)
  5056. {
  5057. updated = TRUE;
  5058. m_pOwner->SetWorkingDir(&dir);
  5059. }
  5060. }
  5061. }
  5062. break;
  5063. }
  5064. }
  5065. ResetOperation(FZ_REPLY_OK);
  5066. }
  5067. else
  5068. ResetOperation(FZ_REPLY_ERROR);
  5069. }
  5070. }
  5071. }
  5072. void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
  5073. {
  5074. DebugAssert(pData);
  5075. if (!m_pSslLayer)
  5076. return;
  5077. if (DebugAlwaysFalse(m_Operation.nOpMode != CSMODE_CONNECT))
  5078. return;
  5079. m_bCheckForTimeout = TRUE;
  5080. m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
  5081. m_LastRecvTime = CTime::CreateForCurrentTime();
  5082. }
  5083. void CFtpControlSocket::OnTimer()
  5084. {
  5085. CheckForTimeout();
  5086. ResumeTransfer();
  5087. if (GetOptionVal(OPTION_KEEPALIVE))
  5088. {
  5089. if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
  5090. {
  5091. //Getting intervals for the Keep Alive feature
  5092. int low=GetOptionVal(OPTION_INTERVALLOW);
  5093. int diff=GetOptionVal(OPTION_INTERVALHIGH)-low;
  5094. //Choose a new delay
  5095. int delay=low+(rand()*diff)/RAND_MAX;
  5096. CTimeSpan span=CTime::CreateForCurrentTime()-m_LastSendTime;
  5097. if (span.GetTotalSeconds()>=delay)
  5098. SendKeepAliveCommand();
  5099. }
  5100. }
  5101. }
  5102. BOOL CFtpControlSocket::IsReady()
  5103. {
  5104. return !m_bKeepAliveActive;
  5105. }
  5106. void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
  5107. {
  5108. m_Operation.nOpMode=CSMODE_CHMOD;
  5109. CString str;
  5110. str.Format( L"SITE CHMOD %03d %s", nValue, (LPCTSTR)path.FormatFilename(filename));
  5111. Send(str);
  5112. }
  5113. void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
  5114. {
  5115. switch (pData->nRequestType)
  5116. {
  5117. case FZ_ASYNCREQUEST_OVERWRITE:
  5118. SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
  5119. break;
  5120. case FZ_ASYNCREQUEST_VERIFYCERT:
  5121. SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
  5122. break;
  5123. case FZ_ASYNCREQUEST_NEEDPASS:
  5124. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5125. m_Operation.nOpState != CONNECT_NEEDPASS)
  5126. break;
  5127. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5128. {
  5129. DoClose();
  5130. break;
  5131. }
  5132. if (!nAction)
  5133. {
  5134. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5135. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5136. break;
  5137. }
  5138. else
  5139. {
  5140. m_bCheckForTimeout = TRUE;
  5141. m_CurrentServer.pass=((CNeedPassRequestData *)pData)->Password;
  5142. m_Operation.nOpState=((CNeedPassRequestData *)pData)->nOldOpState;
  5143. CLogonData *pLogonData = static_cast<CLogonData *>(m_Operation.pData);
  5144. pLogonData->waitForAsyncRequest = false;
  5145. pLogonData->gotPassword = true;
  5146. LogOnToServer(TRUE);
  5147. }
  5148. break;
  5149. #ifndef MPEXT_NO_GSS
  5150. case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
  5151. if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
  5152. break;
  5153. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5154. {
  5155. DoClose();
  5156. break;
  5157. }
  5158. if (!nAction)
  5159. {
  5160. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5161. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5162. break;
  5163. }
  5164. m_bCheckForTimeout = TRUE;
  5165. m_Operation.nOpState=-1;
  5166. LogOnToServer(TRUE);
  5167. break;
  5168. case FZ_ASYNCREQUEST_GSS_NEEDPASS:
  5169. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5170. m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
  5171. break;
  5172. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5173. {
  5174. DoClose();
  5175. break;
  5176. }
  5177. if (!nAction)
  5178. {
  5179. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5180. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5181. break;
  5182. }
  5183. else
  5184. {
  5185. m_bCheckForTimeout = TRUE;
  5186. m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
  5187. m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
  5188. LogOnToServer(TRUE);
  5189. }
  5190. break;
  5191. case FZ_ASYNCREQUEST_GSS_NEEDUSER:
  5192. if (m_Operation.nOpMode != CSMODE_CONNECT ||
  5193. m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
  5194. break;
  5195. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5196. {
  5197. DoClose();
  5198. break;
  5199. }
  5200. if (!nAction)
  5201. {
  5202. DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
  5203. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  5204. break;
  5205. }
  5206. else
  5207. {
  5208. m_bCheckForTimeout = TRUE;
  5209. m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
  5210. m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
  5211. LogOnToServer(TRUE);
  5212. }
  5213. break;
  5214. #endif
  5215. default:
  5216. LogMessage(FZ_LOG_WARNING, L"Unknown request reply %d", pData->nRequestType);
  5217. break;
  5218. }
  5219. }
  5220. int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  5221. {
  5222. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  5223. {
  5224. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  5225. {
  5226. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  5227. {
  5228. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  5229. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  5230. if (iter->pLayer == m_pProxyLayer)
  5231. LogMessage(FZ_LOG_INFO, L"Proxy layer changed state from %s to %s", state2Desc, state1Desc);
  5232. #ifndef MPEXT_NO_GSS
  5233. else if (iter->pLayer == m_pGssLayer)
  5234. LogMessage(FZ_LOG_INFO, L"m_pGssLayer changed state from %s to %s", state2Desc, state1Desc);
  5235. #endif
  5236. else if (iter->pLayer == m_pSslLayer)
  5237. {
  5238. delete [] iter->str;
  5239. LogMessage(FZ_LOG_INFO, L"TLS layer changed state from %s to %s", state2Desc, state1Desc);
  5240. }
  5241. else
  5242. LogMessage(FZ_LOG_INFO, L"Layer @ %d changed state from %s to %s", iter->pLayer, state2Desc, state1Desc);
  5243. }
  5244. }
  5245. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  5246. {
  5247. USES_CONVERSION;
  5248. if (iter->pLayer == m_pProxyLayer)
  5249. {
  5250. switch (iter->nParam1)
  5251. {
  5252. case PROXYERROR_NOERROR:
  5253. ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  5254. break;
  5255. case PROXYERROR_NOCONN:
  5256. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  5257. break;
  5258. case PROXYERROR_REQUESTFAILED:
  5259. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  5260. if (iter->str)
  5261. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  5262. break;
  5263. case PROXYERROR_AUTHTYPEUNKNOWN:
  5264. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  5265. break;
  5266. case PROXYERROR_AUTHFAILED:
  5267. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  5268. break;
  5269. case PROXYERROR_AUTHNOLOGON:
  5270. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  5271. break;
  5272. case PROXYERROR_CANTRESOLVEHOST:
  5273. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  5274. break;
  5275. default:
  5276. LogMessage(FZ_LOG_WARNING, L"Unknown proxy error" );
  5277. }
  5278. }
  5279. #ifndef MPEXT_NO_GSS
  5280. else if (iter->pLayer == m_pGssLayer)
  5281. {
  5282. switch (iter->nParam1)
  5283. {
  5284. case GSS_INFO:
  5285. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  5286. break;
  5287. case GSS_ERROR:
  5288. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  5289. break;
  5290. case GSS_COMMAND:
  5291. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  5292. break;
  5293. case GSS_REPLY:
  5294. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  5295. break;
  5296. }
  5297. }
  5298. #endif
  5299. else if (iter->pLayer == m_pSslLayer)
  5300. {
  5301. switch (iter->nParam1)
  5302. {
  5303. case SSL_INFO:
  5304. switch (iter->nParam2)
  5305. {
  5306. case SSL_INFO_ESTABLISHED:
  5307. ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, FZ_LOG_STATUS);
  5308. if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  5309. {
  5310. LogOnToServer();
  5311. }
  5312. break;
  5313. }
  5314. break;
  5315. case SSL_FAILURE:
  5316. switch (iter->nParam2)
  5317. {
  5318. case SSL_FAILURE_UNKNOWN:
  5319. // CTransferSocket has a special treatment of SSL_FAILURE_UNKNOWN,
  5320. // as an indication of a re-key failure.
  5321. ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, FZ_LOG_ERROR);
  5322. break;
  5323. case SSL_FAILURE_ESTABLISH:
  5324. ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  5325. break;
  5326. case SSL_FAILURE_INITSSL:
  5327. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  5328. break;
  5329. case SSL_FAILURE_VERIFYCERT:
  5330. ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, FZ_LOG_ERROR);
  5331. break;
  5332. case SSL_FAILURE_CERTREJECTED:
  5333. ShowStatus(IDS_ERRORMSG_CERTREJECTED, FZ_LOG_ERROR);
  5334. m_bDidRejectCertificate = TRUE;
  5335. break;
  5336. }
  5337. TriggerEvent(FD_CLOSE);
  5338. break;
  5339. case SSL_VERIFY_CERT:
  5340. t_SslCertData *pData = new t_SslCertData;
  5341. LPCTSTR CertError = NULL;
  5342. if (m_pSslLayer->GetPeerCertificateData(*pData, CertError))
  5343. {
  5344. CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
  5345. pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  5346. pRequestData->pCertData = pData;
  5347. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
  5348. {
  5349. delete pRequestData->pCertData;
  5350. delete pRequestData;
  5351. ResetOperation(FZ_REPLY_ERROR);
  5352. }
  5353. else
  5354. {
  5355. m_bCheckForTimeout = FALSE;
  5356. }
  5357. delete [] iter->str;
  5358. continue;
  5359. }
  5360. else
  5361. {
  5362. delete pData;
  5363. delete [] iter->str;
  5364. CString str;
  5365. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  5366. ShowStatus(str, FZ_LOG_ERROR);
  5367. ResetOperation(FZ_REPLY_ERROR);
  5368. continue;
  5369. }
  5370. break;
  5371. }
  5372. delete [] iter->str;
  5373. continue;
  5374. }
  5375. #ifndef MPEXT_NO_GSS
  5376. else
  5377. if (iter->pLayer == m_pGssLayer)
  5378. {
  5379. if (iter->nParam1 == GSS_AUTHCOMPLETE ||
  5380. iter->nParam1 == GSS_AUTHFAILED)
  5381. {
  5382. LogOnToServer(TRUE);
  5383. delete [] iter->str;
  5384. continue;
  5385. }
  5386. }
  5387. #endif
  5388. }
  5389. delete [] iter->str;
  5390. }
  5391. return 0;
  5392. }
  5393. _int64 CFtpControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  5394. {
  5395. int type = GetOptionVal(valType);
  5396. if ( type == 1)
  5397. return ( _int64)GetOptionVal(valValue) * 1024;
  5398. return ( _int64)1000000000000; // I hope that when there will be something with 1000GB/s then I'll change it :)
  5399. }
  5400. _int64 CFtpControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  5401. {
  5402. if (direction == download)
  5403. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  5404. else
  5405. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  5406. return ( _int64)1000000000000;
  5407. }
  5408. _int64 CFtpControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CFtpControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction)
  5409. {
  5410. beenWaiting = false;
  5411. CTime nowTime = CTime::CreateForCurrentTime();
  5412. _int64 ableToRead = BUFSIZE;
  5413. if ( nowTime == curTime)
  5414. {
  5415. ableToRead = iter->nBytesAvailable;
  5416. if (ableToRead <= 0)
  5417. {
  5418. // we should wait till next second
  5419. nowTime = CTime::CreateForCurrentTime();
  5420. while (nowTime == curTime && !iter->nBytesAvailable)
  5421. {
  5422. if (beenWaiting)
  5423. {
  5424. //Check if there are other commands in the command queue.
  5425. MSG msg;
  5426. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  5427. {
  5428. LogMessage(FZ_LOG_INFO, L"Message waiting in queue, resuming later");
  5429. return 0;
  5430. }
  5431. }
  5432. m_SpeedLimitSync.Unlock();
  5433. Sleep(100);
  5434. m_SpeedLimitSync.Lock();
  5435. nowTime = CTime::CreateForCurrentTime();
  5436. beenWaiting = true;
  5437. // Since we didn't hold the critical section for some time, we have to renew the iterator
  5438. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5439. if (iter->pOwner == this)
  5440. break;
  5441. if (iter == m_InstanceList[direction].end())
  5442. return 0;
  5443. }
  5444. }
  5445. ableToRead = iter->nBytesAvailable;
  5446. }
  5447. if (nowTime != curTime)
  5448. {
  5449. if (ableToRead > 0)
  5450. ableToRead = 0;
  5451. curLimit = GetSpeedLimit(direction, curTime);
  5452. __int64 nMax = curLimit / m_InstanceList[direction].size();
  5453. _int64 nLeft = 0;
  5454. int nCount = 0;
  5455. std::list<t_ActiveList>::iterator iter2;
  5456. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5457. {
  5458. if (iter2->nBytesAvailable>0)
  5459. {
  5460. nLeft += iter2->nBytesAvailable;
  5461. iter2->nBytesTransferred = 1;
  5462. }
  5463. else
  5464. {
  5465. nCount++;
  5466. iter2->nBytesTransferred = 0;
  5467. }
  5468. iter2->nBytesAvailable = nMax;
  5469. }
  5470. if (nLeft && nCount)
  5471. {
  5472. nMax = nLeft / nCount;
  5473. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5474. {
  5475. if (!iter2->nBytesTransferred)
  5476. iter2->nBytesAvailable += nMax;
  5477. else
  5478. iter2->nBytesTransferred = 0;
  5479. }
  5480. }
  5481. ableToRead = iter->nBytesAvailable;
  5482. }
  5483. curTime = nowTime;
  5484. ableToRead = std::min(ableToRead, static_cast<_int64>(BUFSIZE));
  5485. return ableToRead;
  5486. }
  5487. _int64 CFtpControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting)
  5488. {
  5489. m_SpeedLimitSync.Lock();
  5490. std::list<t_ActiveList>::iterator iter;
  5491. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5492. if (iter->pOwner == this)
  5493. break;
  5494. if (iter == m_InstanceList[direction].end())
  5495. {
  5496. t_ActiveList item;
  5497. CTime time = CTime::CreateForCurrentTime();
  5498. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  5499. item.nBytesTransferred = 0;
  5500. item.pOwner = this;
  5501. m_InstanceList[direction].push_back(item);
  5502. iter = m_InstanceList[direction].end();
  5503. iter--;
  5504. }
  5505. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction);
  5506. m_SpeedLimitSync.Unlock();
  5507. return limit;
  5508. }
  5509. BOOL CFtpControlSocket::RemoveActiveTransfer()
  5510. {
  5511. BOOL bFound = FALSE;
  5512. m_SpeedLimitSync.Lock();
  5513. std::list<t_ActiveList>::iterator iter;
  5514. for (int i = 0; i < 2; i++)
  5515. {
  5516. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  5517. if (iter->pOwner == this)
  5518. {
  5519. m_InstanceList[i].erase(iter);
  5520. bFound = TRUE;
  5521. break;
  5522. }
  5523. }
  5524. m_SpeedLimitSync.Unlock();
  5525. return bFound;
  5526. }
  5527. BOOL CFtpControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  5528. {
  5529. m_SpeedLimitSync.Lock();
  5530. std::list<t_ActiveList>::iterator iter;
  5531. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5532. if (iter->pOwner == this)
  5533. {
  5534. if (iter->nBytesAvailable > nBytesTransferred)
  5535. iter->nBytesAvailable -= nBytesTransferred;
  5536. else
  5537. iter->nBytesAvailable = 0;
  5538. iter->nBytesTransferred += nBytesTransferred;
  5539. m_SpeedLimitSync.Unlock();
  5540. return TRUE;
  5541. }
  5542. m_SpeedLimitSync.Unlock();
  5543. return FALSE;
  5544. }
  5545. CString CFtpControlSocket::ConvertDomainName(CString domain)
  5546. {
  5547. USES_CONVERSION;
  5548. LPCWSTR buffer = T2CW(domain);
  5549. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  5550. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  5551. {
  5552. delete [] utf8;
  5553. LogMessage(FZ_LOG_WARNING, L"Could not convert domain name");
  5554. return domain;
  5555. }
  5556. char *output = 0;
  5557. output = strdup(utf8);
  5558. delete [] utf8;
  5559. CString result = A2T(output);
  5560. free(output);
  5561. return result;
  5562. }
  5563. void CFtpControlSocket::LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg)
  5564. {
  5565. LogMessageRaw(nMessageType, pMsg);
  5566. }
  5567. bool CFtpControlSocket::LoggingSocketMessage(int nMessageType)
  5568. {
  5569. return LoggingMessageType(nMessageType);
  5570. }
  5571. int CFtpControlSocket::GetSocketOptionVal(int OptionID) const
  5572. {
  5573. return GetOptionVal(OptionID);
  5574. }
  5575. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
  5576. {
  5577. CServerPath realPath;
  5578. BOOL Result = ParsePwdReply(rawpwd, realPath);
  5579. if (Result)
  5580. {
  5581. m_pOwner->SetCurrentPath(realPath);
  5582. }
  5583. return Result;
  5584. }
  5585. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd, CServerPath & realPath)
  5586. {
  5587. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  5588. DebugAssert(pData);
  5589. int pos1 = rawpwd.Find(L'"');
  5590. int pos2 = rawpwd.ReverseFind(L'"');
  5591. if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
  5592. {
  5593. LogMessage(FZ_LOG_WARNING, L"No quoted path found, try using first token as path");
  5594. pos1 = rawpwd.Find(L' ');
  5595. if (pos1 != -1)
  5596. {
  5597. pos2 = rawpwd.Find(L' ', pos1 + 1);
  5598. if (pos2 == -1)
  5599. pos2 = rawpwd.GetLength();
  5600. }
  5601. if (pos1 == -1)
  5602. {
  5603. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5604. ResetOperation(FZ_REPLY_ERROR);
  5605. return FALSE;
  5606. }
  5607. }
  5608. rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
  5609. realPath = m_pOwner->GetCurrentPath();
  5610. realPath.SetServer(m_CurrentServer);
  5611. if (!realPath.SetPath(rawpwd))
  5612. {
  5613. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5614. ResetOperation(FZ_REPLY_ERROR);
  5615. return FALSE;
  5616. }
  5617. return TRUE;
  5618. }
  5619. void CFtpControlSocket::DiscardLine(RawByteString line)
  5620. {
  5621. if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
  5622. {
  5623. line = line.UpperCase();
  5624. while (line.SubString(1, 1) == " ")
  5625. {
  5626. line = line.SubString(2, line.Length() - 1);
  5627. }
  5628. if (line == "UTF8" && m_CurrentServer.nUTF8 != 2)
  5629. m_bAnnouncesUTF8 = true;
  5630. else if (line == "CLNT" || line.SubString(1, 5) == "CLNT ")
  5631. m_hasClntCmd = true;
  5632. else if (line == "MLSD")
  5633. {
  5634. m_serverCapabilities.SetCapability(mlsd_command, yes);
  5635. }
  5636. else if (line == "MDTM")
  5637. {
  5638. m_serverCapabilities.SetCapability(mdtm_command, yes);
  5639. }
  5640. else if (line.SubString(1, 4) == "MLST")
  5641. {
  5642. std::string facts;
  5643. if (line.Length() > 5)
  5644. {
  5645. facts = line.SubString(6, line.Length() - 5).c_str();
  5646. }
  5647. m_serverCapabilities.SetCapability(mlsd_command, yes, facts);
  5648. }
  5649. else if (line == "MFMT")
  5650. {
  5651. m_serverCapabilities.SetCapability(mfmt_command, yes);
  5652. }
  5653. }
  5654. else if (m_Operation.nOpMode == CSMODE_LISTFILE)
  5655. {
  5656. m_ListFile = line;
  5657. }
  5658. }
  5659. int CFtpControlSocket::FileTransferListState()
  5660. {
  5661. return GetOptionVal(OPTION_MPEXT_NOLIST) ? FILETRANSFER_TYPE : FILETRANSFER_LIST_TYPE;
  5662. }
  5663. CString CFtpControlSocket::GetReply()
  5664. {
  5665. if (m_RecvBuffer.empty())
  5666. return L"";
  5667. USES_CONVERSION;
  5668. LPCSTR line;
  5669. if ((m_Operation.nOpMode&CSMODE_LISTFILE) && (m_Operation.nOpState==LISTFILE_MLST) &&
  5670. (GetReplyCode() == 2))
  5671. {
  5672. // this is probably never used anyway
  5673. line = m_ListFile.c_str();
  5674. }
  5675. else
  5676. {
  5677. line = m_RecvBuffer.front().c_str();
  5678. }
  5679. if (m_bUTF8)
  5680. {
  5681. // convert from UTF-8 to ANSI
  5682. if (DetectUTF8Encoding(RawByteString(line)) == etANSI)
  5683. {
  5684. if (m_CurrentServer.nUTF8 != 1)
  5685. {
  5686. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  5687. m_bUTF8 = false;
  5688. }
  5689. return A2CT(line);
  5690. }
  5691. // convert from UTF-8 to ANSI
  5692. int len = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
  5693. if (!len)
  5694. {
  5695. m_RecvBuffer.pop_front();
  5696. if (m_RecvBuffer.empty())
  5697. m_RecvBuffer.push_back("");
  5698. return L"";
  5699. }
  5700. else
  5701. {
  5702. LPWSTR p1 = new WCHAR[len + 1];
  5703. MultiByteToWideChar(CP_UTF8, 0, line, -1 , (LPWSTR)p1, len + 1);
  5704. CString reply = W2CT(p1);
  5705. delete [] p1;
  5706. return reply;
  5707. }
  5708. }
  5709. else
  5710. return A2CT(line);
  5711. }
  5712. void CFtpControlSocket::OnSend(int nErrorCode)
  5713. {
  5714. if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
  5715. return;
  5716. int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
  5717. if (res == -1)
  5718. {
  5719. int Error = GetLastError();
  5720. if (Error != WSAEWOULDBLOCK)
  5721. {
  5722. LogError(Error);
  5723. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5724. DoClose();
  5725. }
  5726. return;
  5727. }
  5728. if (!res)
  5729. {
  5730. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5731. DoClose();
  5732. }
  5733. m_awaitsReply = true;
  5734. m_LastSendTime = CTime::CreateForCurrentTime();
  5735. if (res == m_sendBufferLen)
  5736. {
  5737. delete [] m_sendBuffer;
  5738. m_sendBuffer = 0;
  5739. m_sendBufferLen = 0;
  5740. }
  5741. else
  5742. {
  5743. char* tmp = new char[m_sendBufferLen - res];
  5744. memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
  5745. delete [] m_sendBuffer;
  5746. m_sendBuffer = tmp;
  5747. m_sendBufferLen -= res;
  5748. }
  5749. }
  5750. bool CFtpControlSocket::IsMisleadingListResponse()
  5751. {
  5752. // Some servers are broken. Instead of an empty listing, some MVS servers
  5753. // for example they return something "550 no members found"
  5754. // Other servers return "550 No files found."
  5755. CString retmsg = GetReply();
  5756. if (!retmsg.CompareNoCase(L"550 No members found."))
  5757. return true;
  5758. if (!retmsg.CompareNoCase(L"550 No data sets found."))
  5759. return true;
  5760. if (!retmsg.CompareNoCase(L"550 No files found."))
  5761. return true;
  5762. return false;
  5763. }
  5764. bool CFtpControlSocket::IsRoutableAddress(const CString & host)
  5765. {
  5766. USES_CONVERSION;
  5767. if (host.Left(3) == L"127" ||
  5768. host.Left(3) == L"10." ||
  5769. host.Left(7) == L"192.168" ||
  5770. host.Left(7) == L"169.254" ||
  5771. host.Left(2) == L"0.")
  5772. {
  5773. return false;
  5774. }
  5775. else if (host.Left(3) == L"172")
  5776. {
  5777. CString middle = host.Mid(4);
  5778. int pos = middle.Find(L".");
  5779. long part = atol(T2CA(middle.Left(pos)));
  5780. if ((part >= 16) && (part <= 31))
  5781. {
  5782. return false;
  5783. }
  5784. }
  5785. return true;
  5786. }
  5787. bool CFtpControlSocket::CheckForcePasvIp(CString & host)
  5788. {
  5789. bool result = true;
  5790. unsigned int tmpPort;
  5791. CString ahost;
  5792. switch (m_CurrentServer.iForcePasvIp)
  5793. {
  5794. case 0: // on
  5795. if (!GetPeerName(ahost, tmpPort))
  5796. {
  5797. // this should happen with proxy server only
  5798. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  5799. // do not know what to do, if there's FTP proxy
  5800. if (!logontype)
  5801. {
  5802. // this is a host name, not an IP, but it should not be a problem
  5803. ahost = m_CurrentServer.host;
  5804. }
  5805. }
  5806. if (ahost != host)
  5807. {
  5808. LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", (LPCTSTR)ahost, (LPCTSTR)host);
  5809. host = ahost;
  5810. }
  5811. break;
  5812. case 1: // off
  5813. // noop
  5814. break;
  5815. default: // auto
  5816. if (!GetPeerName(ahost, tmpPort))
  5817. {
  5818. LogMessage(FZ_LOG_PROGRESS, L"Error retrieving server address, cannot test if address is routable");
  5819. }
  5820. else if (!IsRoutableAddress(host) && IsRoutableAddress(ahost))
  5821. {
  5822. LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", (LPCTSTR)host);
  5823. host = ahost;
  5824. }
  5825. break;
  5826. }
  5827. return result;
  5828. }
  5829. CFtpListResult * CFtpControlSocket::CreateListResult(bool mlst)
  5830. {
  5831. CFtpListResult * Result =
  5832. new CFtpListResult(
  5833. m_CurrentServer, mlst, &m_bUTF8, GetOptionVal(OPTION_VMSALLREVISIONS), GetOptionVal(OPTION_DEBUGSHOWLISTING));
  5834. Result->InitIntern(GetIntern());
  5835. return Result;
  5836. }
  5837. //---------------------------------------------------------------------------
  5838. ftp_capabilities_t TFTPServerCapabilities::GetCapability(ftp_capability_names_t Name)
  5839. {
  5840. t_cap tcap = FCapabilityMap[Name];
  5841. return tcap.cap;
  5842. }
  5843. ftp_capabilities_t TFTPServerCapabilities::GetCapabilityString(ftp_capability_names_t Name, std::string * Option)
  5844. {
  5845. t_cap tcap = FCapabilityMap[Name];
  5846. if (Option)
  5847. *Option = tcap.option;
  5848. return tcap.cap;
  5849. }
  5850. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap)
  5851. {
  5852. t_cap tcap = FCapabilityMap[Name];
  5853. tcap.cap = Cap;
  5854. tcap.number = 1;
  5855. FCapabilityMap[Name] = tcap;
  5856. }
  5857. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap, const std::string & Option)
  5858. {
  5859. t_cap tcap = FCapabilityMap[Name];
  5860. tcap.cap = Cap;
  5861. tcap.option = Option;
  5862. tcap.number = 0;
  5863. FCapabilityMap[Name] = tcap;
  5864. }