FtpControlSocket.cpp 182 KB

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