FtpControlSocket.cpp 183 KB

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