FtpControlSocket.cpp 181 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_hasClntCmd)
  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(CString(L"CLNT ") + m_pTools->GetClientString().c_str()))
  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. // https://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
  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. pData->host = m_CurrentServer.host;
  1822. }
  1823. else
  1824. {
  1825. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  1826. error = TRUE;
  1827. break;
  1828. }
  1829. }
  1830. m_Operation.nOpState = LIST_LIST;
  1831. break;
  1832. case LIST_LIST:
  1833. if (IsMisleadingListResponse())
  1834. {
  1835. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  1836. t_directory listing;
  1837. listing.server = m_CurrentServer;
  1838. listing.path = m_pOwner->GetCurrentPath();
  1839. SetDirectoryListing(&listing);
  1840. ResetOperation(FZ_REPLY_OK);
  1841. return;
  1842. }
  1843. else if (code != 1)
  1844. error = TRUE;
  1845. else
  1846. m_Operation.nOpState = LIST_WAITFINISH;
  1847. break;
  1848. default:
  1849. error = TRUE;
  1850. }
  1851. if (error)
  1852. {
  1853. ResetOperation(FZ_REPLY_ERROR);
  1854. return;
  1855. }
  1856. }
  1857. if (m_Operation.nOpState==LIST_INIT)
  1858. { //Initialize some variables
  1859. pData=new CListData;
  1860. pData->path=path;
  1861. pData->subdir=subdir;
  1862. m_Operation.pData=pData;
  1863. ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, FZ_LOG_PROGRESS);
  1864. pData->nFinish=-1;
  1865. if (m_pDirectoryListing)
  1866. {
  1867. delete m_pDirectoryListing;
  1868. m_pDirectoryListing=0;
  1869. }
  1870. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  1871. pData->bPasv = TRUE;
  1872. else if (m_CurrentServer.nPasv == 1)
  1873. pData->bPasv = TRUE;
  1874. else if (m_CurrentServer.nPasv == 2)
  1875. pData->bPasv = FALSE;
  1876. else
  1877. pData->bPasv = GetOptionVal(OPTION_PASV);
  1878. CServerPath path = pData->path;
  1879. CServerPath realpath = m_pOwner->GetCurrentPath();
  1880. if (!realpath.IsEmpty())
  1881. {
  1882. if (!pData->path.IsEmpty() && pData->path != realpath)
  1883. m_Operation.nOpState=LIST_CWD;
  1884. else if (!pData->path.IsEmpty() && pData->subdir!=L"")
  1885. m_Operation.nOpState=LIST_CWD2;
  1886. else
  1887. {
  1888. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);;
  1889. }
  1890. }
  1891. else
  1892. m_Operation.nOpState = LIST_PWD;
  1893. }
  1894. CString cmd;
  1895. if (m_Operation.nOpState == LIST_PWD)
  1896. cmd=L"PWD";
  1897. else if (m_Operation.nOpState==LIST_CWD)
  1898. cmd=L"CWD " + pData->path.GetPath(); //Command to retrieve the current directory
  1899. else if (m_Operation.nOpState==LIST_PWD2)
  1900. cmd=L"PWD";
  1901. else if (m_Operation.nOpState==LIST_CWD2)
  1902. {
  1903. if (!pData->subdir)
  1904. {
  1905. ResetOperation(FZ_REPLY_ERROR);
  1906. return;
  1907. }
  1908. if (pData->subdir != L".." )
  1909. {
  1910. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
  1911. {
  1912. CServerPath path = m_pOwner->GetCurrentPath();
  1913. path.AddSubdir(pData->subdir);
  1914. cmd = L"CWD " + path.GetPath();
  1915. }
  1916. else
  1917. cmd = L"CWD " + pData->subdir;
  1918. }
  1919. else
  1920. {
  1921. if (pData->lastCmdSentCDUP)
  1922. {
  1923. pData->lastCmdSentCDUP = false;
  1924. cmd = L"CWD ..";
  1925. }
  1926. else
  1927. {
  1928. pData->lastCmdSentCDUP = true;
  1929. cmd = L"CDUP";
  1930. }
  1931. }
  1932. }
  1933. else if (m_Operation.nOpState == LIST_PWD3)
  1934. cmd=L"PWD";
  1935. else if (m_Operation.nOpState == LIST_MODE)
  1936. {
  1937. #ifdef MPEXT_NO_ZLIB
  1938. DebugFail();
  1939. #else
  1940. if (m_useZlib)
  1941. #endif
  1942. cmd = L"MODE S";
  1943. #ifndef MPEXT_NO_ZLIB
  1944. else
  1945. cmd = L"MODE Z";
  1946. #endif
  1947. }
  1948. else if (m_Operation.nOpState == LIST_OPTS)
  1949. {
  1950. #ifdef MPEXT_NO_ZLIB
  1951. DebugFail();
  1952. #else
  1953. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  1954. cmd.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  1955. #endif
  1956. }
  1957. else if (m_Operation.nOpState == LIST_PORT_PASV)
  1958. {
  1959. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  1960. #ifndef MPEXT_NO_ZLIB
  1961. if (m_useZlib)
  1962. {
  1963. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  1964. {
  1965. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  1966. ResetOperation(FZ_REPLY_ERROR);
  1967. return;
  1968. }
  1969. }
  1970. #endif
  1971. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  1972. #ifndef MPEXT_NO_GSS
  1973. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  1974. m_pTransferSocket->UseGSS(m_pGssLayer);
  1975. #endif
  1976. m_pTransferSocket->SetFamily(GetFamily());
  1977. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) ||
  1978. !m_pTransferSocket->AsyncSelect())
  1979. {
  1980. ShowStatus(L"Failed to create socket", FZ_LOG_ERROR);
  1981. ResetOperation(FZ_REPLY_ERROR);
  1982. return;
  1983. }
  1984. if (pData->bPasv)
  1985. switch (GetFamily())
  1986. {
  1987. case AF_INET:
  1988. cmd = L"PASV";
  1989. break;
  1990. case AF_INET6:
  1991. cmd = L"EPSV";
  1992. break;
  1993. default:
  1994. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  1995. ResetOperation(FZ_REPLY_ERROR);
  1996. return;
  1997. }
  1998. else
  1999. {
  2000. m_pTransferSocket->m_bListening=TRUE;
  2001. if (m_pProxyLayer)
  2002. {
  2003. SOCKADDR_IN addr;
  2004. int len=sizeof(addr);
  2005. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  2006. {
  2007. ResetOperation(FZ_REPLY_ERROR);
  2008. return;
  2009. }
  2010. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  2011. {
  2012. ResetOperation(FZ_REPLY_ERROR);
  2013. return;
  2014. }
  2015. }
  2016. else
  2017. {
  2018. //Set up an active file transfer
  2019. CString tempHostname;
  2020. UINT nPort;
  2021. if (// create listen socket (let MFC choose the port) & start the socket listening
  2022. !m_pTransferSocket->Listen() ||
  2023. !m_pTransferSocket->GetSockName(tempHostname, nPort))
  2024. {
  2025. ShowStatus(L"Failed to create listen socket", FZ_LOG_ERROR);
  2026. ResetOperation(FZ_REPLY_ERROR);
  2027. return;
  2028. }
  2029. CString host;
  2030. bool bError = false;
  2031. if (GetFamily() == AF_INET)
  2032. {
  2033. host = GetOption(OPTION_TRANSFERIP);
  2034. if (host != L"")
  2035. {
  2036. DWORD ip = inet_addr(T2CA(host));
  2037. if (ip != INADDR_NONE)
  2038. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2039. else
  2040. {
  2041. hostent *fullname = gethostbyname(T2CA(host));
  2042. if (!fullname)
  2043. host = L"";
  2044. else
  2045. {
  2046. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  2047. if (ip != INADDR_NONE)
  2048. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2049. else
  2050. host = L"";
  2051. }
  2052. }
  2053. }
  2054. if (host == L"")
  2055. {
  2056. UINT temp;
  2057. if (!GetSockName(host, temp))
  2058. {
  2059. ShowStatus(L"Failed to get socket address ", FZ_LOG_ERROR);
  2060. bError = true;
  2061. }
  2062. host.Replace(L'.', L',');
  2063. }
  2064. if (!bError)
  2065. {
  2066. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  2067. cmd = L"PORT " + host; // send PORT cmd to server
  2068. }
  2069. }
  2070. else if (GetFamily() == AF_INET6)
  2071. {
  2072. host = GetOption(OPTION_TRANSFERIP6);
  2073. if (host != L"")
  2074. {
  2075. USES_CONVERSION;
  2076. addrinfo hints, *res;
  2077. memset(&hints, 0, sizeof(addrinfo));
  2078. hints.ai_family = AF_INET6;
  2079. hints.ai_socktype = SOCK_STREAM;
  2080. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  2081. {
  2082. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  2083. freeaddrinfo(res);
  2084. }
  2085. else
  2086. host = L"";
  2087. }
  2088. if (host == L"")
  2089. {
  2090. UINT temp;
  2091. if(!GetSockName(host, temp))
  2092. bError = true;
  2093. }
  2094. if (!bError)
  2095. {
  2096. // assamble EPRT command
  2097. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  2098. }
  2099. }
  2100. else
  2101. {
  2102. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  2103. bError = true;
  2104. }
  2105. if (bError)
  2106. {
  2107. ResetOperation(FZ_REPLY_ERROR);
  2108. return;
  2109. }
  2110. }
  2111. }
  2112. }
  2113. else if (m_Operation.nOpState==LIST_TYPE)
  2114. cmd=L"TYPE A";
  2115. else if (m_Operation.nOpState==LIST_LIST)
  2116. {
  2117. if (!m_pTransferSocket)
  2118. {
  2119. LogMessage(FZ_LOG_APIERROR, L"Error: m_pTransferSocket==NULL" );
  2120. ResetOperation(FZ_REPLY_ERROR);
  2121. return;
  2122. }
  2123. m_pTransferSocket->SetActive();
  2124. cmd = GetListingCmd();
  2125. if (!Send(cmd))
  2126. return;
  2127. if (pData->bPasv)
  2128. {
  2129. // if PASV create the socket & initiate outbound data channel connection
  2130. if (!ConnectTransferSocket(pData->host, pData->port))
  2131. {
  2132. ResetOperation(FZ_REPLY_ERROR);
  2133. return;
  2134. }
  2135. }
  2136. return;
  2137. }
  2138. if (cmd != L"")
  2139. Send(cmd);
  2140. }
  2141. bool CFtpControlSocket::ConnectTransferSocket(const CString & host, UINT port)
  2142. {
  2143. CString hostname;
  2144. hostname.Format(L"%s:%d", host, port);
  2145. CString str;
  2146. str.Format(IDS_STATUSMSG_CONNECTING, hostname);
  2147. ShowStatus(str, FZ_LOG_PROGRESS);
  2148. bool result = true;
  2149. if (!m_pTransferSocket->Connect(host, port))
  2150. {
  2151. if (GetLastError() != WSAEWOULDBLOCK)
  2152. {
  2153. result = false;
  2154. }
  2155. }
  2156. return result;
  2157. }
  2158. void CFtpControlSocket::ListFile(CString filename, const CServerPath &path)
  2159. {
  2160. USES_CONVERSION;
  2161. #define LISTFILE_INIT -1
  2162. #define LISTFILE_MLST 1
  2163. #define LISTFILE_TYPE 2
  2164. #define LISTFILE_SIZE 3
  2165. #define LISTFILE_MDTM 4
  2166. #define LISTFILE_PWD 5
  2167. #define LISTFILE_CWD 6
  2168. #define LISTFILE_CWD2 7
  2169. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LISTFILE);
  2170. m_Operation.nOpMode|=CSMODE_LISTFILE;
  2171. if (!m_pOwner->IsConnected())
  2172. {
  2173. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  2174. return;
  2175. }
  2176. CListFileData * pData = static_cast<CListFileData *>(m_Operation.pData);
  2177. BOOL error = FALSE;
  2178. CString cmd;
  2179. CString retmsg;
  2180. int code = -1;
  2181. int num = -1;
  2182. switch (m_Operation.nOpState)
  2183. {
  2184. case LISTFILE_INIT:
  2185. //Initialize some variables
  2186. pData = new CListFileData;
  2187. pData->fileName = filename;
  2188. pData->dir = path.GetPath();
  2189. // special case for listing a root folder
  2190. pData->path = (filename == L"/") ? pData->dir : path.FormatFilename(filename);
  2191. m_Operation.pData = pData;
  2192. ShowStatus(IDS_STATUSMSG_RETRIEVINGLISTFILE, FZ_LOG_PROGRESS);
  2193. if (UsingMlsd())
  2194. {
  2195. m_Operation.nOpState = LISTFILE_MLST;
  2196. cmd = L"MLST " + pData->path;
  2197. }
  2198. else
  2199. {
  2200. m_Operation.nOpState = LISTFILE_PWD;
  2201. cmd = L"PWD";
  2202. }
  2203. if (!Send(cmd))
  2204. {
  2205. error = TRUE;
  2206. }
  2207. break;
  2208. case LISTFILE_MLST:
  2209. retmsg = GetReply();
  2210. code = GetReplyCode();
  2211. if (IsMisleadingListResponse())
  2212. {
  2213. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL, FZ_LOG_PROGRESS);
  2214. num = 0;
  2215. }
  2216. else if (code != 2)
  2217. {
  2218. error = TRUE;
  2219. }
  2220. else
  2221. {
  2222. USES_CONVERSION;
  2223. int size = m_ListFile.GetLength();
  2224. char *buffer = new char[size + 1];
  2225. memmove(buffer, (LPCSTR)m_ListFile, m_ListFile.GetLength());
  2226. CFtpListResult * pListResult = new CFtpListResult(m_CurrentServer, &m_bUTF8);
  2227. pListResult->InitIntern(GetIntern());
  2228. pListResult->AddData(buffer, size);
  2229. if (GetOptionVal(OPTION_DEBUGSHOWLISTING))
  2230. pListResult->SendToMessageLog();
  2231. pData->direntry = pListResult->getList(num, true);
  2232. if (pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  2233. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2234. delete pListResult;
  2235. }
  2236. break;
  2237. case LISTFILE_PWD:
  2238. code = GetReplyCode();
  2239. retmsg = GetReply();
  2240. if ((code == 2) &&
  2241. ParsePwdReply(retmsg, pData->pwd) &&
  2242. Send(L"CWD " + pData->path))
  2243. {
  2244. m_Operation.nOpState = LISTFILE_CWD;
  2245. }
  2246. else
  2247. {
  2248. error = TRUE;
  2249. }
  2250. break;
  2251. case LISTFILE_CWD:
  2252. code = GetReplyCode();
  2253. pData->direntry = new t_directory::t_direntry[1];
  2254. pData->direntry->name = pData->fileName;
  2255. if (code == 2)
  2256. {
  2257. pData->direntry->dir = TRUE;
  2258. if (Send(L"CWD " + pData->pwd.GetPath()))
  2259. {
  2260. m_Operation.nOpState = LISTFILE_CWD2;
  2261. }
  2262. else
  2263. {
  2264. error = TRUE;
  2265. }
  2266. }
  2267. else
  2268. {
  2269. // CWD failed, file is not a directory, we should not need to restore PWD.
  2270. // Force binary mode, as according to RFC 6359,
  2271. // SIZE command returns size as transferred over the stream.
  2272. // Moreover ProFTPD does not even support SIZE command in ASCII mode
  2273. if (Send(L"TYPE I"))
  2274. {
  2275. m_Operation.nOpState = LISTFILE_TYPE;
  2276. }
  2277. else
  2278. {
  2279. error = TRUE;
  2280. }
  2281. }
  2282. break;
  2283. case LISTFILE_CWD2:
  2284. code = GetReplyCode();
  2285. if (code == 2)
  2286. {
  2287. // No point trying SIZE on directories.
  2288. // (More over IIS returns a multi-line response for SIZE /dir and we cannot handle that).
  2289. // IIS fails even for MDTM, so skipping even that.
  2290. num = 1;
  2291. }
  2292. // this should never really happen
  2293. else
  2294. {
  2295. error = TRUE;
  2296. }
  2297. break;
  2298. case LISTFILE_TYPE:
  2299. // Do not really care if TYPE succeeded or not
  2300. if (Send(L"SIZE " + pData->path))
  2301. {
  2302. m_Operation.nOpState = LISTFILE_SIZE;
  2303. }
  2304. else
  2305. {
  2306. error = TRUE;
  2307. }
  2308. break;
  2309. case LISTFILE_SIZE:
  2310. code = GetReplyCode();
  2311. // Ignore SIZE errors for directories
  2312. if ((HandleSize(code, pData->direntry->size) || pData->direntry->dir) &&
  2313. Send(L"MDTM " + pData->path))
  2314. {
  2315. m_Operation.nOpState = LISTFILE_MDTM;
  2316. }
  2317. else
  2318. {
  2319. error = TRUE;
  2320. }
  2321. break;
  2322. case LISTFILE_MDTM:
  2323. code = GetReplyCode();
  2324. if (HandleMdtm(code, pData->direntry->date))
  2325. {
  2326. num = 1;
  2327. }
  2328. else
  2329. {
  2330. error = TRUE;
  2331. }
  2332. break;
  2333. default:
  2334. error = TRUE;
  2335. break;
  2336. }
  2337. if (error)
  2338. {
  2339. ResetOperation(FZ_REPLY_ERROR);
  2340. }
  2341. else if (num >= 0)
  2342. {
  2343. t_directory * pDirectoryListing = new t_directory;
  2344. pDirectoryListing->direntry = pData->direntry;
  2345. pData->direntry = NULL;
  2346. pDirectoryListing->num = num;
  2347. pDirectoryListing->server = m_CurrentServer;
  2348. pDirectoryListing->path.SetServer(pDirectoryListing->server);
  2349. pDirectoryListing->path = pData->dir;
  2350. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL,FZ_LOG_PROGRESS);
  2351. // do not use SetDirectoryListing as that would make
  2352. // later operations believe that there's only this one file in the folder
  2353. m_pOwner->SendDirectoryListing(pDirectoryListing);
  2354. ResetOperation(FZ_REPLY_OK);
  2355. }
  2356. }
  2357. void CFtpControlSocket::TransferEnd(int nMode)
  2358. {
  2359. if (!m_Operation.nOpMode)
  2360. {
  2361. LogMessage(FZ_LOG_INFO, L"Ignoring old TransferEnd message");
  2362. return;
  2363. }
  2364. m_LastRecvTime=CTime::GetCurrentTime();
  2365. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  2366. FileTransfer(0,TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2367. else if (m_Operation.nOpMode&CSMODE_LIST)
  2368. List(TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2369. }
  2370. void CFtpControlSocket::OnClose(int nErrorCode)
  2371. {
  2372. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  2373. if (m_pTransferSocket)
  2374. {
  2375. m_pTransferSocket->OnClose(0);
  2376. m_pTransferSocket->Close();
  2377. delete m_pTransferSocket;
  2378. m_pTransferSocket=0;
  2379. DoClose();
  2380. return;
  2381. }
  2382. if (m_bDidRejectCertificate)
  2383. DoClose(FZ_REPLY_CANCEL);
  2384. else
  2385. DoClose();
  2386. }
  2387. void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFinish/*=FALSE*/,int nError/*=0*/)
  2388. {
  2389. USES_CONVERSION;
  2390. #define FILETRANSFER_INIT -1
  2391. #define FILETRANSFER_PWD 0
  2392. #define FILETRANSFER_CWD 1
  2393. #define FILETRANSFER_MKD 2
  2394. #define FILETRANSFER_CWD2 3
  2395. #define FILETRANSFER_PWD2 4
  2396. #define FILETRANSFER_LIST_MODE 5
  2397. #define FILETRANSFER_LIST_OPTS 6
  2398. #define FILETRANSFER_LIST_PORTPASV 7
  2399. #define FILETRANSFER_LIST_TYPE 8
  2400. #define FILETRANSFER_LIST_LIST 9
  2401. #define FILETRANSFER_LIST_WAITFINISH 10
  2402. #define FILETRANSFER_NOLIST_SIZE 11
  2403. #define FILETRANSFER_NOLIST_MDTM 12
  2404. #define FILETRANSFER_TYPE 13
  2405. #define FILETRANSFER_REST 14
  2406. #define FILETRANSFER_MODE 15
  2407. #define FILETRANSFER_OPTS 16
  2408. #define FILETRANSFER_PORTPASV 17
  2409. #define FILETRANSFER_RETRSTOR 18
  2410. #define FILETRANSFER_WAITFINISH 19
  2411. #define FILETRANSFER_WAIT 20
  2412. #define FILETRANSFER_MFMT 21
  2413. //Partial flowchart of FileTransfer
  2414. //
  2415. // +----+
  2416. // /------|Init|--------\
  2417. // | +----+ |
  2418. // | | |
  2419. // | /---+ |
  2420. // | | | |
  2421. // | | +---+ |
  2422. // | | |PWD| |
  2423. // | | +---+ |
  2424. // | | | |
  2425. // | \---+ |
  2426. // | | |
  2427. // | +---+ |
  2428. // | |CWD|--\ |
  2429. // | +---+ | |
  2430. // | | | |
  2431. // | | | |
  2432. // | | +---+ |
  2433. // | | |MKD| |
  2434. // | | +---+ |
  2435. // | | | |
  2436. // | | | |
  2437. // | | +----+ |
  2438. // | | |CWD2| |
  2439. // | | +----+ |
  2440. // | | | |
  2441. // | +----/ |
  2442. // | | |
  2443. // | +---+ |
  2444. // +-------|PWD| |
  2445. // | +---+ |
  2446. // | | |
  2447. // | +----------/
  2448. // | |
  2449. // | +---------+
  2450. // | |LIST_TYPE|
  2451. // | +---------+
  2452. // | |
  2453. // | |
  2454. // | +-------------+
  2455. // | |LIST_PORTPASV|
  2456. // | +-------------+
  2457. // | |
  2458. // | |
  2459. // | +---------+
  2460. // | |LIST_LIST|-----\ //List fails, maybe folder is list protected
  2461. // | +---------+ | //Use SIZE and MDTM to get file information
  2462. // | | +----+
  2463. // | | |SIZE|
  2464. // | | +----+
  2465. // | | |
  2466. // | | +----+
  2467. // | | |MDTM|
  2468. // | | +----+
  2469. // | | |
  2470. // | | |
  2471. // | +---------------+ |
  2472. // | |LIST_WAITFINISH| |
  2473. // | +---------------+ |
  2474. // | | |
  2475. // | | |
  2476. // | +----------/
  2477. // | |
  2478. // \---------+
  2479. // |
  2480. // +----+
  2481. // |TYPE|
  2482. // +----+
  2483. // |
  2484. // |
  2485. // +--------+
  2486. // |PORTPASV|--\
  2487. // +--------+ |
  2488. // | |
  2489. // | |
  2490. // | +----+
  2491. // | |REST|
  2492. // | +----+
  2493. // | |
  2494. // +------/
  2495. // |
  2496. // +--------+
  2497. // |RETRSTOR|
  2498. // +--------+
  2499. // |
  2500. // |
  2501. // +----------+
  2502. // |WAITFINISH|
  2503. // +----------+
  2504. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
  2505. if (!m_pOwner->IsConnected())
  2506. {
  2507. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2508. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
  2509. return;
  2510. }
  2511. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2512. //Process finish and error messages
  2513. if (bFinish || nError)
  2514. {
  2515. DebugAssert(m_Operation.nOpMode&CSMODE_TRANSFER);
  2516. // APPE failed, ignore this reply
  2517. if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
  2518. return;
  2519. if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
  2520. return;
  2521. if (nError)
  2522. {
  2523. if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
  2524. { //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
  2525. if (m_pTransferSocket)
  2526. m_pTransferSocket=0;
  2527. delete m_pDirectoryListing;
  2528. m_pDirectoryListing=0;
  2529. }
  2530. else if (nError&CSMODE_TRANSFERTIMEOUT)
  2531. DoClose();
  2532. else
  2533. // we may get here when connection was closed, when the closure
  2534. // was first detected while reading/writing,
  2535. // when we abort file transfer with regular error,
  2536. // possibly preventing automatic reconnect
  2537. ResetOperation(FZ_REPLY_ERROR);
  2538. return;
  2539. }
  2540. if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
  2541. {
  2542. ResetOperation(FZ_REPLY_ERROR);
  2543. return;
  2544. }
  2545. else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
  2546. {
  2547. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  2548. {
  2549. delete m_pDirectoryListing;
  2550. m_pDirectoryListing=0;
  2551. ResetOperation(FZ_REPLY_ERROR);
  2552. return;
  2553. }
  2554. int num=0;
  2555. pData->pDirectoryListing=new t_directory;
  2556. if (GetOptionVal(OPTION_DEBUGSHOWLISTING))
  2557. m_pTransferSocket->m_pListResult->SendToMessageLog();
  2558. pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num, false);
  2559. pData->pDirectoryListing->num=num;
  2560. if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
  2561. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2562. pData->pDirectoryListing->server = m_CurrentServer;
  2563. pData->pDirectoryListing->path.SetServer(m_CurrentServer);
  2564. pData->pDirectoryListing->path = pData->transferfile.remotepath;
  2565. if (pData->rawpwd!=L"")
  2566. {
  2567. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  2568. {
  2569. delete m_pDirectoryListing;
  2570. m_pDirectoryListing=0;
  2571. delete m_pTransferSocket;
  2572. m_pTransferSocket=0;
  2573. ResetOperation(FZ_REPLY_ERROR);
  2574. return;
  2575. }
  2576. }
  2577. else
  2578. pData->pDirectoryListing->path=pData->transferfile.remotepath;
  2579. if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
  2580. return;
  2581. }
  2582. else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
  2583. {
  2584. ResetOperation(FZ_REPLY_ERROR);
  2585. return;
  2586. }
  2587. else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
  2588. {
  2589. if (m_pTransferSocket->m_bListening)
  2590. {
  2591. ResetOperation(FZ_REPLY_ERROR);
  2592. return;
  2593. }
  2594. pData->nGotTransferEndReply |= 2;
  2595. if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
  2596. return;
  2597. else
  2598. {
  2599. delete m_pTransferSocket;
  2600. m_pTransferSocket=0;
  2601. }
  2602. }
  2603. }
  2604. //////////////////
  2605. //Initialization//
  2606. //////////////////
  2607. int nReplyError = 0;
  2608. if (m_Operation.nOpState == FILETRANSFER_INIT)
  2609. {
  2610. DebugAssert(transferfile);
  2611. DebugAssert(!m_Operation.nOpMode);
  2612. DebugAssert(!m_Operation.pData);
  2613. CString str;
  2614. str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
  2615. transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
  2616. ShowStatus(str,FZ_LOG_STATUS);
  2617. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2618. m_Operation.pData=new CFileTransferData;
  2619. pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2620. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  2621. pData->bPasv = TRUE;
  2622. else if (m_CurrentServer.nPasv == 1)
  2623. pData->bPasv = TRUE;
  2624. else if (m_CurrentServer.nPasv == 2)
  2625. pData->bPasv = FALSE;
  2626. else
  2627. pData->bPasv = GetOptionVal(OPTION_PASV);
  2628. //Replace invalid characters in the local filename
  2629. int pos=transferfile->localfile.ReverseFind(L'\\');
  2630. for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
  2631. if (transferfile->localfile[i]==L':')
  2632. transferfile->localfile.SetAt(i, L'_');
  2633. pData->transferfile=*transferfile;
  2634. pData->transferdata.transfersize=pData->transferfile.size;
  2635. pData->transferdata.transferleft=pData->transferfile.size;
  2636. pData->transferdata.bResume = FALSE;
  2637. pData->transferdata.bResumeAppend = FALSE;
  2638. pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
  2639. CServerPath path;
  2640. DebugCheck(m_pOwner->GetCurrentPath(path));
  2641. if (path == pData->transferfile.remotepath)
  2642. {
  2643. if (m_pDirectoryListing)
  2644. {
  2645. m_Operation.nOpState=FILETRANSFER_TYPE;
  2646. CString remotefile=pData->transferfile.remotefile;
  2647. int i;
  2648. for (i=0; i<m_pDirectoryListing->num; i++)
  2649. {
  2650. if (m_pDirectoryListing->direntry[i].name==remotefile &&
  2651. ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
  2652. {
  2653. delete m_pDirectoryListing;
  2654. m_pDirectoryListing=0;
  2655. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2656. break;
  2657. }
  2658. }
  2659. if (m_pDirectoryListing && i==m_pDirectoryListing->num)
  2660. {
  2661. nReplyError = CheckOverwriteFile();
  2662. if (!nReplyError)
  2663. {
  2664. if (pData->transferfile.get)
  2665. {
  2666. CString path=pData->transferfile.localfile;
  2667. if (path.ReverseFind(L'\\')!=-1)
  2668. {
  2669. path=path.Left(path.ReverseFind(L'\\')+1);
  2670. CString path2;
  2671. while (path!=L"")
  2672. {
  2673. path2+=path.Left(path.Find( L"\\" )+1);
  2674. path=path.Mid(path.Find( L"\\" )+1);
  2675. CreateDirectory(path2, 0);
  2676. }
  2677. }
  2678. }
  2679. }
  2680. }
  2681. }
  2682. else
  2683. {
  2684. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2685. }
  2686. }
  2687. else
  2688. {
  2689. if (path.IsEmpty())
  2690. m_Operation.nOpState = FILETRANSFER_PWD;
  2691. else
  2692. m_Operation.nOpState = FILETRANSFER_CWD;
  2693. }
  2694. }
  2695. else
  2696. {
  2697. ///////////
  2698. //Replies//
  2699. ///////////
  2700. int code = GetReplyCode();
  2701. switch(m_Operation.nOpState)
  2702. {
  2703. case FILETRANSFER_PWD:
  2704. if (code != 2 && code != 3)
  2705. {
  2706. nReplyError = FZ_REPLY_ERROR;
  2707. break;
  2708. }
  2709. pData->rawpwd = GetReply();
  2710. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  2711. pData->rawpwd[0] != L'/')
  2712. {
  2713. m_mayBeMvsFilesystem = false;
  2714. m_mayBeBS2000Filesystem = false;
  2715. if (m_mayBeBS2000Filesystem)
  2716. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  2717. else
  2718. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  2719. pData->transferfile.remotepath.SetServer(m_CurrentServer);
  2720. }
  2721. if (!ParsePwdReply(pData->rawpwd))
  2722. return;
  2723. if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
  2724. {
  2725. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2726. }
  2727. else
  2728. m_Operation.nOpState = LIST_CWD;
  2729. break;
  2730. case FILETRANSFER_CWD:
  2731. if (code != 2 && code != 3)
  2732. if (pData->transferfile.get)
  2733. {
  2734. pData->bUseAbsolutePaths = TRUE;
  2735. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2736. }
  2737. else
  2738. m_Operation.nOpState = FILETRANSFER_MKD;
  2739. else
  2740. m_Operation.nOpState = FILETRANSFER_PWD2;
  2741. break;
  2742. case FILETRANSFER_MKD:
  2743. switch(pData->nMKDOpState)
  2744. {
  2745. case MKD_FINDPARENT:
  2746. {
  2747. if (code == 2 || code == 3)
  2748. {
  2749. m_pOwner->SetCurrentPath(pData->MKDCurrent);
  2750. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2751. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2752. CString Segment=pData->MKDSegments.front();
  2753. pData->MKDSegments.pop_front();
  2754. if (!Send( L"MKD " + Segment))
  2755. return;
  2756. }
  2757. else
  2758. {
  2759. if (!pData->MKDCurrent.HasParent())
  2760. nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
  2761. else
  2762. {
  2763. pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
  2764. pData->MKDCurrent=pData->MKDCurrent.GetParent();
  2765. if (!Send(L"CWD "+pData->MKDCurrent.GetPath()))
  2766. return;
  2767. }
  2768. }
  2769. }
  2770. break;
  2771. case MKD_MAKESUBDIRS:
  2772. {
  2773. if (code == 2 || code == 3)
  2774. { //Create dir entry in parent dir
  2775. DebugAssert(!pData->MKDSegments.empty());
  2776. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2777. CString Segment=pData->MKDSegments.front();
  2778. pData->MKDSegments.pop_front();
  2779. if (Send( L"MKD " + Segment))
  2780. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2781. else
  2782. return;
  2783. }
  2784. else
  2785. nReplyError=FZ_REPLY_ERROR;
  2786. }
  2787. break;
  2788. case MKD_CHANGETOSUBDIR:
  2789. {
  2790. if (code == 2 || code == 3 || //Creation successful
  2791. m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
  2792. {
  2793. CServerPath path2 = pData->MKDCurrent;
  2794. if (path2.HasParent())
  2795. {
  2796. CString name=path2.GetLastSegment();
  2797. path2=path2.GetParent();
  2798. t_directory dir;
  2799. BOOL res=FALSE;
  2800. if (m_pDirectoryListing)
  2801. {
  2802. if (m_pDirectoryListing->path==path2)
  2803. {
  2804. dir=*m_pDirectoryListing;
  2805. res=TRUE;
  2806. }
  2807. }
  2808. t_directory WorkingDir;
  2809. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  2810. if (!res && bFound)
  2811. if (WorkingDir.path==path2)
  2812. {
  2813. dir=WorkingDir;
  2814. res=TRUE;
  2815. }
  2816. if (!res)
  2817. {
  2818. dir.path=path2;
  2819. dir.server=m_CurrentServer;
  2820. }
  2821. int i;
  2822. for (i=0; i<dir.num; i++)
  2823. if (dir.direntry[i].name == name)
  2824. {
  2825. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  2826. break;
  2827. }
  2828. if (i==dir.num)
  2829. {
  2830. t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
  2831. for (i=0;i<dir.num;i++)
  2832. entries[i]=dir.direntry[i];
  2833. entries[i].name=name;
  2834. entries[i].dir=TRUE;
  2835. entries[i].date.hasdate=FALSE;
  2836. entries[i].size=-1;
  2837. entries[i].bUnsure=FALSE;
  2838. delete [] dir.direntry;
  2839. dir.direntry=entries;
  2840. dir.num++;
  2841. BOOL updated=FALSE;
  2842. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  2843. {
  2844. updated=TRUE;
  2845. SetDirectoryListing(&dir);
  2846. }
  2847. if (!updated)
  2848. if (WorkingDir.path==dir.path)
  2849. {
  2850. updated=TRUE;
  2851. m_pOwner->SetWorkingDir(&dir);
  2852. }
  2853. }
  2854. }
  2855. }
  2856. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  2857. if (pData->MKDSegments.empty())
  2858. m_Operation.nOpState=FILETRANSFER_CWD2;
  2859. else
  2860. {
  2861. if (Send( L"CWD " + pData->MKDCurrent.GetPath()))
  2862. pData->nMKDOpState=MKD_MAKESUBDIRS;
  2863. else
  2864. return;
  2865. }
  2866. }
  2867. break;
  2868. default:
  2869. DebugFail();
  2870. }
  2871. break;
  2872. case FILETRANSFER_CWD2:
  2873. if (code != 2 && code != 3)
  2874. if (code == 4)
  2875. nReplyError=FZ_REPLY_ERROR;
  2876. else
  2877. nReplyError=FZ_REPLY_CRITICALERROR;
  2878. else
  2879. m_Operation.nOpState=FILETRANSFER_PWD2;
  2880. break;
  2881. case FILETRANSFER_PWD2:
  2882. if (code != 2 && code != 3)
  2883. nReplyError = FZ_REPLY_ERROR;
  2884. else
  2885. {
  2886. pData->rawpwd = GetReply();
  2887. if (!ParsePwdReply(pData->rawpwd))
  2888. return;
  2889. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2890. }
  2891. break;
  2892. case FILETRANSFER_LIST_MODE:
  2893. #ifdef MPEXT_NO_ZLIB
  2894. DebugFail();
  2895. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2896. #else
  2897. if (code == 2 || code == 3)
  2898. m_useZlib = !m_useZlib;
  2899. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
  2900. #endif
  2901. break;
  2902. case FILETRANSFER_LIST_OPTS:
  2903. #ifdef MPEXT_NO_ZLIB
  2904. DebugFail();
  2905. #else
  2906. if (code == 2 || code == 3)
  2907. m_zlibLevel = pData->newZlibLevel;
  2908. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2909. #endif
  2910. break;
  2911. case FILETRANSFER_LIST_TYPE:
  2912. if (code != 2 && code != 3)
  2913. nReplyError = FZ_REPLY_ERROR;
  2914. else
  2915. m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
  2916. break;
  2917. case FILETRANSFER_LIST_PORTPASV:
  2918. if (code!=3 && code!=2)
  2919. {
  2920. if (!pData->bTriedPortPasvOnce)
  2921. {
  2922. pData->bTriedPortPasvOnce = TRUE;
  2923. pData->bPasv = !pData->bPasv;
  2924. }
  2925. else
  2926. nReplyError=FZ_REPLY_ERROR;
  2927. break;
  2928. }
  2929. if (pData->bPasv)
  2930. {
  2931. CString reply = GetReply();
  2932. int i,j;
  2933. // MP EXT
  2934. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  2935. {
  2936. i++;
  2937. j--;
  2938. }
  2939. else
  2940. {
  2941. // MP EXT
  2942. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  2943. {
  2944. i += 4;
  2945. j = reply.GetLength() - 1;
  2946. }
  2947. else
  2948. {
  2949. if (!pData->bTriedPortPasvOnce)
  2950. {
  2951. pData->bTriedPortPasvOnce = TRUE;
  2952. pData->bPasv = !pData->bPasv;
  2953. }
  2954. else
  2955. nReplyError = FZ_REPLY_ERROR;
  2956. break;
  2957. }
  2958. }
  2959. CString temp = reply.Mid(i,(j-i)+1);
  2960. if (GetFamily() == AF_INET)
  2961. {
  2962. int count=0;
  2963. int pos=0;
  2964. //Convert commas to dots
  2965. temp.Replace( L",", L"." );
  2966. while(1)
  2967. {
  2968. pos=temp.Find(L".",pos);
  2969. if (pos!=-1)
  2970. count++;
  2971. else
  2972. break;
  2973. pos++;
  2974. }
  2975. if (count!=5)
  2976. {
  2977. if (!pData->bTriedPortPasvOnce)
  2978. {
  2979. pData->bTriedPortPasvOnce = TRUE;
  2980. pData->bPasv = !pData->bPasv;
  2981. }
  2982. else
  2983. nReplyError = FZ_REPLY_ERROR;
  2984. break;
  2985. }
  2986. i=temp.ReverseFind(L'.');
  2987. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  2988. temp=temp.Left(i);
  2989. i=temp.ReverseFind(L'.');
  2990. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  2991. pData->host=temp.Left(i);
  2992. if (!CheckForcePasvIp(pData->host))
  2993. {
  2994. nReplyError = FZ_REPLY_ERROR;
  2995. break;
  2996. }
  2997. }
  2998. else if (GetFamily() == AF_INET6)
  2999. {
  3000. temp = temp.Mid(3);
  3001. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3002. if (pData->port < 0 || pData->port > 65535)
  3003. {
  3004. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3005. nReplyError = FZ_REPLY_ERROR;
  3006. break;
  3007. }
  3008. pData->host = m_CurrentServer.host;
  3009. }
  3010. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3011. #ifndef MPEXT_NO_ZLIB
  3012. if (m_useZlib)
  3013. {
  3014. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3015. {
  3016. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3017. ResetOperation(FZ_REPLY_ERROR);
  3018. return;
  3019. }
  3020. }
  3021. #endif
  3022. #ifndef MPEXT_NO_GSS
  3023. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3024. m_pTransferSocket->UseGSS(m_pGssLayer);
  3025. #endif
  3026. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3027. m_pTransferSocket->SetFamily(GetFamily());
  3028. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3029. {
  3030. nReplyError = FZ_REPLY_ERROR;
  3031. break;
  3032. }
  3033. DebugCheck(m_pTransferSocket->AsyncSelect());
  3034. }
  3035. m_Operation.nOpState=FILETRANSFER_LIST_LIST;
  3036. break;
  3037. case FILETRANSFER_LIST_LIST:
  3038. if (IsMisleadingListResponse())
  3039. {
  3040. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  3041. t_directory listing;
  3042. listing.server = m_CurrentServer;
  3043. listing.path.SetServer(m_CurrentServer);
  3044. if (pData->rawpwd != L"")
  3045. {
  3046. if (!listing.path.SetPath(pData->rawpwd))
  3047. {
  3048. delete m_pDirectoryListing;
  3049. m_pDirectoryListing = 0;
  3050. delete m_pTransferSocket;
  3051. m_pTransferSocket = 0;
  3052. ResetOperation(FZ_REPLY_ERROR);
  3053. return;
  3054. }
  3055. }
  3056. else
  3057. listing.path = pData->transferfile.remotepath;
  3058. SetDirectoryListing(&listing);
  3059. m_Operation.nOpState = FILETRANSFER_TYPE;
  3060. delete m_pTransferSocket;
  3061. m_pTransferSocket = 0;
  3062. nReplyError = CheckOverwriteFile();
  3063. if (!nReplyError)
  3064. {
  3065. if (pData->transferfile.get)
  3066. {
  3067. CString path=pData->transferfile.localfile;
  3068. if (path.ReverseFind(L'\\')!=-1)
  3069. {
  3070. path=path.Left(path.ReverseFind(L'\\')+1);
  3071. CString path2;
  3072. while (path!=L"")
  3073. {
  3074. path2+=path.Left(path.Find( L"\\" )+1);
  3075. path=path.Mid(path.Find( L"\\" )+1);
  3076. CreateDirectory(path2, 0);
  3077. }
  3078. }
  3079. }
  3080. }
  3081. }
  3082. else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
  3083. {
  3084. TransferHandleListError();
  3085. }
  3086. else if (code!=1)
  3087. nReplyError=FZ_REPLY_ERROR;
  3088. else
  3089. m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
  3090. break;
  3091. case FILETRANSFER_LIST_WAITFINISH:
  3092. if (!bFinish)
  3093. {
  3094. if (code!=2 && code!=3)
  3095. {
  3096. if (code==4 || code==5)
  3097. {
  3098. TransferHandleListError();
  3099. }
  3100. else
  3101. {
  3102. nReplyError=FZ_REPLY_ERROR;
  3103. }
  3104. }
  3105. else
  3106. pData->nGotTransferEndReply = 1;
  3107. }
  3108. if (pData->nGotTransferEndReply && pData->pDirectoryListing)
  3109. {
  3110. SetDirectoryListing(pData->pDirectoryListing);
  3111. delete m_pTransferSocket;
  3112. m_pTransferSocket=0;
  3113. m_Operation.nOpState=FILETRANSFER_TYPE;
  3114. nReplyError = CheckOverwriteFile();
  3115. if (!nReplyError)
  3116. {
  3117. if (pData->transferfile.get)
  3118. {
  3119. CString path=pData->transferfile.localfile;
  3120. if (path.ReverseFind(L'\\')!=-1)
  3121. {
  3122. path=path.Left(path.ReverseFind(L'\\')+1);
  3123. CString path2;
  3124. while (path!=L"")
  3125. {
  3126. path2+=path.Left(path.Find( L"\\" )+1);
  3127. path=path.Mid(path.Find( L"\\" )+1);
  3128. CreateDirectory(path2, 0);
  3129. }
  3130. }
  3131. }
  3132. }
  3133. pData->nGotTransferEndReply=0;
  3134. }
  3135. break;
  3136. case FILETRANSFER_NOLIST_SIZE:
  3137. {
  3138. __int64 size;
  3139. if (HandleSize(code, size))
  3140. {
  3141. DebugAssert(!pData->pFileSize);
  3142. pData->pFileSize=new _int64;
  3143. *pData->pFileSize=size;
  3144. }
  3145. }
  3146. m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
  3147. break;
  3148. case FILETRANSFER_NOLIST_MDTM:
  3149. if (HandleMdtm(code, pData->remoteDate))
  3150. {
  3151. pData->hasRemoteDate = true;
  3152. }
  3153. m_Operation.nOpState=FILETRANSFER_TYPE;
  3154. nReplyError=CheckOverwriteFile();
  3155. break;
  3156. case FILETRANSFER_TYPE:
  3157. if (code!=2 && code!=3)
  3158. nReplyError = FZ_REPLY_ERROR;
  3159. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
  3160. break;
  3161. case FILETRANSFER_WAIT:
  3162. if (!pData->nWaitNextOpState)
  3163. nReplyError=FZ_REPLY_ERROR;
  3164. else
  3165. m_Operation.nOpState=pData->nWaitNextOpState;
  3166. break;
  3167. case FILETRANSFER_MODE:
  3168. #ifdef MPEXT_NO_ZLIB
  3169. DebugFail();
  3170. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3171. #else
  3172. if (code == 2 || code == 3)
  3173. m_useZlib = !m_useZlib;
  3174. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
  3175. #endif
  3176. break;
  3177. case FILETRANSFER_OPTS:
  3178. #ifdef MPEXT_NO_ZLIB
  3179. DebugFail();
  3180. #else
  3181. if (code == 2 || code == 3)
  3182. m_zlibLevel = pData->newZlibLevel;
  3183. #endif
  3184. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3185. break;
  3186. case FILETRANSFER_PORTPASV:
  3187. if (code == 3 || code == 2)
  3188. {
  3189. if (pData->bPasv)
  3190. {
  3191. CString reply = GetReply();
  3192. int i,j;
  3193. // MP EXT
  3194. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  3195. {
  3196. i++;
  3197. j--;
  3198. }
  3199. else
  3200. {
  3201. // MP EXT
  3202. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  3203. {
  3204. i += 4;
  3205. j = reply.GetLength() - 1;
  3206. }
  3207. else
  3208. {
  3209. if (!pData->bTriedPortPasvOnce)
  3210. {
  3211. pData->bTriedPortPasvOnce = TRUE;
  3212. pData->bPasv = !pData->bPasv;
  3213. }
  3214. else
  3215. nReplyError = FZ_REPLY_ERROR;
  3216. break;
  3217. }
  3218. }
  3219. CString temp = reply.Mid(i,(j-i)+1);
  3220. if (GetFamily() == AF_INET)
  3221. {
  3222. int count=0;
  3223. int pos=0;
  3224. //Convert commas to dots
  3225. temp.Replace( L",", L"." );
  3226. while(1)
  3227. {
  3228. pos=temp.Find( L".", pos);
  3229. if (pos!=-1)
  3230. count++;
  3231. else
  3232. break;
  3233. pos++;
  3234. }
  3235. if (count!=5)
  3236. {
  3237. if (!pData->bTriedPortPasvOnce)
  3238. {
  3239. pData->bTriedPortPasvOnce = TRUE;
  3240. pData->bPasv = !pData->bPasv;
  3241. }
  3242. else
  3243. nReplyError = FZ_REPLY_ERROR;
  3244. break;
  3245. }
  3246. i=temp.ReverseFind(L'.');
  3247. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3248. temp=temp.Left(i);
  3249. i=temp.ReverseFind(L'.');
  3250. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3251. pData->host=temp.Left(i);
  3252. if (!CheckForcePasvIp(pData->host))
  3253. {
  3254. nReplyError = FZ_REPLY_ERROR;
  3255. break;
  3256. }
  3257. }
  3258. else if (GetFamily() == AF_INET6)
  3259. {
  3260. temp = temp.Mid(3);
  3261. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3262. if (pData->port < 0 || pData->port > 65535)
  3263. {
  3264. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3265. nReplyError = FZ_REPLY_ERROR;
  3266. break;
  3267. }
  3268. pData->host = m_CurrentServer.host;
  3269. }
  3270. else
  3271. {
  3272. nReplyError = FZ_REPLY_ERROR;
  3273. break;
  3274. }
  3275. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  3276. #ifndef MPEXT_NO_ZLIB
  3277. if (m_useZlib)
  3278. {
  3279. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3280. {
  3281. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3282. ResetOperation(FZ_REPLY_ERROR);
  3283. return;
  3284. }
  3285. }
  3286. #endif
  3287. #ifndef MPEXT_NO_GSS
  3288. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3289. m_pTransferSocket->UseGSS(m_pGssLayer);
  3290. #endif
  3291. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3292. m_pTransferSocket->SetFamily(GetFamily());
  3293. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3294. {
  3295. nReplyError = FZ_REPLY_ERROR;
  3296. break;
  3297. }
  3298. DebugCheck(m_pTransferSocket->AsyncSelect());
  3299. }
  3300. if (pData->transferdata.bResume)
  3301. m_Operation.nOpState = FILETRANSFER_REST;
  3302. else
  3303. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3304. BOOL res = FALSE;
  3305. if (!m_pDataFile)
  3306. m_pDataFile = new CFile;
  3307. if (pData->transferfile.get)
  3308. {
  3309. if (pData->transferdata.bResume)
  3310. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
  3311. else
  3312. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
  3313. }
  3314. else
  3315. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyNone);
  3316. if (!res)
  3317. {
  3318. wchar_t * Error = m_pTools->LastSysErrorMessage();
  3319. //Error opening the file
  3320. CString str;
  3321. str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
  3322. str += L"\n";
  3323. str += Error;
  3324. free(Error);
  3325. ShowStatus(str,FZ_LOG_ERROR);
  3326. nReplyError = FZ_REPLY_ERROR;
  3327. break;
  3328. }
  3329. if (!m_pTransferSocket)
  3330. {
  3331. nReplyError=FZ_REPLY_ERROR;
  3332. break;
  3333. }
  3334. m_pTransferSocket->m_pFile = m_pDataFile;
  3335. if (!pData->transferfile.get)
  3336. {
  3337. // See comment in !get branch below
  3338. pData->transferdata.transfersize=GetLength64(*m_pDataFile);
  3339. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3340. if (pData->transferdata.bResume)
  3341. {
  3342. CString remotefile=pData->transferfile.remotefile;
  3343. if (m_pDirectoryListing)
  3344. for (int i = 0; i < m_pDirectoryListing->num; i++)
  3345. {
  3346. if (m_pDirectoryListing->direntry[i].name == remotefile)
  3347. {
  3348. pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
  3349. break;
  3350. }
  3351. }
  3352. _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
  3353. LONG low = static_cast<LONG>(size&0xFFFFFFFF);
  3354. LONG high = static_cast<LONG>(size>>32);
  3355. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3356. {
  3357. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3358. nReplyError = FZ_REPLY_ERROR;
  3359. }
  3360. }
  3361. }
  3362. else
  3363. {
  3364. // Resetting transfersize here is pointless as we
  3365. // always provide valid size in call to FileTransfer.
  3366. // We unnecessary reply on the file being in the directory listing.
  3367. pData->transferdata.transfersize=-1;
  3368. CString remotefile=pData->transferfile.remotefile;
  3369. if (m_pDirectoryListing)
  3370. for (int i=0; i<m_pDirectoryListing->num; i++)
  3371. {
  3372. if (m_pDirectoryListing->direntry[i].name==remotefile)
  3373. {
  3374. pData->hasRemoteDate = true;
  3375. pData->remoteDate = m_pDirectoryListing->direntry[i].date;
  3376. pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
  3377. }
  3378. }
  3379. else if (pData->pFileSize)
  3380. pData->transferdata.transfersize=*pData->pFileSize;
  3381. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3382. }
  3383. }
  3384. else
  3385. if (!pData->bTriedPortPasvOnce)
  3386. {
  3387. pData->bTriedPortPasvOnce = TRUE;
  3388. pData->bPasv = !pData->bPasv;
  3389. }
  3390. else
  3391. nReplyError = FZ_REPLY_ERROR;
  3392. break;
  3393. case FILETRANSFER_REST:
  3394. { //Resume
  3395. if (code==3 || code==2)
  3396. {
  3397. LONG high = 0;
  3398. if (pData->transferfile.get)
  3399. {
  3400. pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
  3401. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3402. {
  3403. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3404. nReplyError = FZ_REPLY_ERROR;
  3405. }
  3406. else
  3407. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3408. }
  3409. else
  3410. {
  3411. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3412. }
  3413. }
  3414. else
  3415. {
  3416. if (code==5 && GetReply()[1]==L'0')
  3417. {
  3418. if (pData->transferfile.get)
  3419. {
  3420. if (pData->transferdata.transfersize!=-1)
  3421. {
  3422. DebugAssert(m_pDataFile);
  3423. if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
  3424. {
  3425. ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, FZ_LOG_STATUS);
  3426. ResetOperation(FZ_REPLY_OK);
  3427. return;
  3428. }
  3429. }
  3430. ShowStatus(IDS_ERRORMSG_CANTRESUME, FZ_LOG_ERROR);
  3431. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3432. pData->transferdata.bResume=FALSE;
  3433. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3434. }
  3435. else
  3436. {
  3437. ShowStatus(L"Resume command not supported by server, trying append.", FZ_LOG_PROGRESS);
  3438. pData->transferdata.bResumeAppend=TRUE;
  3439. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3440. }
  3441. }
  3442. else
  3443. nReplyError=FZ_REPLY_ERROR;
  3444. }
  3445. }
  3446. break;
  3447. case FILETRANSFER_RETRSTOR:
  3448. // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
  3449. // is successful.
  3450. // On failure, it's a 4xy or 5xy reply.
  3451. // However, some servers send a 2xy transfer complete reply without opening a data
  3452. // connection if there's no data to send.
  3453. if (code==2)
  3454. {
  3455. //Transfer successful, however server did not open data connection
  3456. ResetOperation(FZ_REPLY_OK);
  3457. return;
  3458. }
  3459. else if (code!=1)
  3460. {
  3461. if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
  3462. {
  3463. pData->askOnResumeFail = false;
  3464. delete m_pTransferSocket;
  3465. m_pTransferSocket = 0;
  3466. delete m_pDataFile;
  3467. m_pDataFile = 0;
  3468. pData->nGotTransferEndReply = 0;
  3469. nReplyError = CheckOverwriteFile();
  3470. }
  3471. else
  3472. {
  3473. nReplyError = FZ_REPLY_ERROR;
  3474. if (code == 5)
  3475. nReplyError |= FZ_REPLY_CRITICALERROR;
  3476. }
  3477. }
  3478. else
  3479. {
  3480. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  3481. //Look if we can find any information about the resume offset
  3482. if (!pData->transferfile.get && pData->transferdata.bResumeAppend)
  3483. {
  3484. _int64 nOffset = -1;
  3485. CString reply = GetReply();
  3486. reply.MakeLower();
  3487. int pos = reply.Find(L"restarting at offset ");
  3488. if (pos != -1)
  3489. pos += _tcslen(L"restarting at offset ");
  3490. reply = reply.Mid(pos);
  3491. int i;
  3492. for (i=0; i<reply.GetLength(); i++)
  3493. {
  3494. if (reply[i] < L'0' || reply[i] > L'9')
  3495. break;
  3496. }
  3497. if (i == reply.GetLength())
  3498. nOffset = _ttoi64(reply);
  3499. if (nOffset != -1 && m_pDataFile)
  3500. {
  3501. LONG low = 0;
  3502. LONG high = 0;
  3503. if (nOffset >= GetLength64(*m_pDataFile))
  3504. {
  3505. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3506. {
  3507. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3508. nReplyError = FZ_REPLY_ERROR;
  3509. }
  3510. }
  3511. else
  3512. {
  3513. low=static_cast<LONG>(nOffset&0xFFFFFFFF);
  3514. high=static_cast<LONG>(nOffset>>32);
  3515. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3516. {
  3517. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3518. nReplyError = FZ_REPLY_ERROR;
  3519. }
  3520. }
  3521. }
  3522. if (!nReplyError && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3523. {
  3524. m_pTransferSocket->SetActive();
  3525. }
  3526. }
  3527. else if (pData->bPasv && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3528. {
  3529. m_pTransferSocket->SetActive();
  3530. }
  3531. }
  3532. break;
  3533. case FILETRANSFER_WAITFINISH:
  3534. if (!bFinish)
  3535. {
  3536. if (code == 1)
  3537. {
  3538. /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
  3539. * Just ignore the additional ones.
  3540. */
  3541. LogMessage(FZ_LOG_WARNING, L"Server sent more than one code 1yz reply, ignoring additional reply");
  3542. break;
  3543. }
  3544. else if (code!=2 && code!=3)
  3545. nReplyError = FZ_REPLY_ERROR;
  3546. else
  3547. {
  3548. pData->nGotTransferEndReply |= 1;
  3549. }
  3550. }
  3551. if (pData->nGotTransferEndReply==3)
  3552. {
  3553. // Not really sure about a reason for the m_pDataFile condition here
  3554. TransferFinished(m_pDataFile != NULL);
  3555. return;
  3556. }
  3557. break;
  3558. case FILETRANSFER_MFMT:
  3559. //Transfer successful
  3560. ResetOperation(FZ_REPLY_OK);
  3561. break;
  3562. }
  3563. if (nReplyError)
  3564. { //Error transferring the file
  3565. ResetOperation(nReplyError);
  3566. return;
  3567. }
  3568. }
  3569. /////////////////
  3570. //Send commands//
  3571. /////////////////
  3572. BOOL bError=FALSE;
  3573. switch(m_Operation.nOpState)
  3574. {
  3575. case FILETRANSFER_PWD:
  3576. if (!Send(L"PWD"))
  3577. bError = TRUE;
  3578. break;
  3579. case FILETRANSFER_CWD:
  3580. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPath()))
  3581. bError=TRUE;
  3582. break;
  3583. case FILETRANSFER_MKD:
  3584. if (pData->nMKDOpState==MKD_INIT)
  3585. {
  3586. if (!pData->transferfile.remotepath.HasParent())
  3587. {
  3588. LogMessage(FZ_LOG_WARNING, L"Can't create root dir");
  3589. ResetOperation(FZ_REPLY_CRITICALERROR);
  3590. return;
  3591. }
  3592. if (!Send(L"CWD "+pData->transferfile.remotepath.GetParent().GetPath()))
  3593. bError=TRUE;
  3594. pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
  3595. pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
  3596. pData->nMKDOpState=MKD_FINDPARENT;
  3597. }
  3598. break;
  3599. case FILETRANSFER_CWD2:
  3600. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPath()))
  3601. bError=TRUE;
  3602. break;
  3603. case FILETRANSFER_PWD2:
  3604. if (!Send(L"PWD"))
  3605. bError=TRUE;
  3606. break;
  3607. case FILETRANSFER_LIST_MODE:
  3608. #ifdef MPEXT_NO_ZLIB
  3609. DebugFail();
  3610. #else
  3611. if (m_useZlib)
  3612. {
  3613. if (!Send(L"MODE S"))
  3614. bError = TRUE;
  3615. }
  3616. else
  3617. if (!Send(L"MODE Z"))
  3618. bError = TRUE;
  3619. #endif
  3620. break;
  3621. case FILETRANSFER_LIST_OPTS:
  3622. #ifdef MPEXT_NO_ZLIB
  3623. DebugFail();
  3624. #else
  3625. {
  3626. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3627. CString str;
  3628. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3629. if (!Send(str))
  3630. bError = TRUE;
  3631. }
  3632. #endif
  3633. break;
  3634. case FILETRANSFER_LIST_PORTPASV:
  3635. delete m_pDirectoryListing;
  3636. m_pDirectoryListing=0;
  3637. if (pData->bPasv)
  3638. {
  3639. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3640. bError=TRUE;
  3641. }
  3642. else
  3643. {
  3644. if (m_pTransferSocket)
  3645. {
  3646. delete m_pTransferSocket;
  3647. }
  3648. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3649. #ifndef MPEXT_NO_ZLIB
  3650. if (m_useZlib)
  3651. {
  3652. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3653. {
  3654. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3655. ResetOperation(FZ_REPLY_ERROR);
  3656. return;
  3657. }
  3658. }
  3659. #endif
  3660. #ifndef MPEXT_NO_GSS
  3661. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3662. m_pTransferSocket->UseGSS(m_pGssLayer);
  3663. #endif
  3664. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3665. m_pTransferSocket->m_bListening = TRUE;
  3666. m_pTransferSocket->SetFamily(GetFamily());
  3667. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3668. bError=TRUE;
  3669. else if (m_pProxyLayer)
  3670. {
  3671. SOCKADDR_IN addr;
  3672. int len=sizeof(addr);
  3673. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3674. {
  3675. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3676. bError=TRUE;
  3677. }
  3678. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3679. {
  3680. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3681. bError=TRUE;
  3682. }
  3683. //Don't send PORT command yet, params are unknown.
  3684. //will be sent in TransfersocketListenFinished
  3685. }
  3686. else
  3687. {
  3688. //Set up an active file transfer
  3689. CString temp;
  3690. UINT nPort;
  3691. if (//create listen socket (let Windows choose the port) & start listening
  3692. !m_pTransferSocket->Listen() ||
  3693. !m_pTransferSocket->GetSockName(temp, nPort))
  3694. {
  3695. bError = TRUE;
  3696. break;
  3697. }
  3698. CString host;
  3699. if (GetFamily() == AF_INET)
  3700. {
  3701. host = GetOption(OPTION_TRANSFERIP);
  3702. if (host != L"")
  3703. {
  3704. DWORD ip = inet_addr(T2CA(host));
  3705. if (ip != INADDR_NONE)
  3706. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3707. else
  3708. {
  3709. hostent *fullname = gethostbyname(T2CA(host));
  3710. if (!fullname)
  3711. host = L"";
  3712. else
  3713. {
  3714. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3715. if (ip != INADDR_NONE)
  3716. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3717. else
  3718. host = L"";
  3719. }
  3720. }
  3721. }
  3722. if (host == L"")
  3723. {
  3724. UINT temp;
  3725. if (!GetSockName(host, temp))
  3726. {
  3727. bError = true;
  3728. break;
  3729. }
  3730. host.Replace(L'.', L',');
  3731. }
  3732. if (!bError)
  3733. {
  3734. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3735. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3736. bError = TRUE;
  3737. }
  3738. }
  3739. else if (GetFamily() == AF_INET6)
  3740. {
  3741. host = GetOption(OPTION_TRANSFERIP6);
  3742. if (host != L"")
  3743. {
  3744. USES_CONVERSION;
  3745. addrinfo hints, *res;
  3746. memset(&hints, 0, sizeof(addrinfo));
  3747. hints.ai_family = AF_INET6;
  3748. hints.ai_socktype = SOCK_STREAM;
  3749. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3750. {
  3751. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3752. freeaddrinfo(res);
  3753. }
  3754. else
  3755. host = L"";
  3756. }
  3757. if (host == L"")
  3758. {
  3759. UINT temp;
  3760. if(!GetSockName(host, temp))
  3761. bError = true;
  3762. }
  3763. if (!bError)
  3764. {
  3765. // assamble EPRT command
  3766. CString cmd;
  3767. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3768. if (!Send(cmd))
  3769. bError = TRUE;
  3770. }
  3771. }
  3772. else
  3773. {
  3774. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3775. bError = true;
  3776. }
  3777. }
  3778. }
  3779. break;
  3780. case FILETRANSFER_LIST_TYPE:
  3781. if (!Send(L"TYPE A"))
  3782. bError=TRUE;
  3783. break;
  3784. case FILETRANSFER_LIST_LIST:
  3785. {
  3786. if (!m_pTransferSocket)
  3787. {
  3788. ResetOperation(FZ_REPLY_ERROR);
  3789. return;
  3790. }
  3791. m_pTransferSocket->SetActive();
  3792. CString cmd = GetListingCmd();
  3793. if(!Send(cmd))
  3794. bError=TRUE;
  3795. else if(pData->bPasv)
  3796. {
  3797. if (!ConnectTransferSocket(pData->host, pData->port))
  3798. {
  3799. bError=TRUE;
  3800. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3801. }
  3802. }
  3803. }
  3804. break;
  3805. case FILETRANSFER_NOLIST_SIZE:
  3806. {
  3807. CString command = L"SIZE ";
  3808. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3809. if (!Send(command))
  3810. bError=TRUE;
  3811. }
  3812. break;
  3813. case FILETRANSFER_NOLIST_MDTM:
  3814. {
  3815. CString command = L"MDTM ";
  3816. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3817. if (!Send(command))
  3818. bError=TRUE;
  3819. }
  3820. break;
  3821. case FILETRANSFER_TYPE:
  3822. if (pData->transferfile.nType==1)
  3823. {
  3824. if (!Send(L"TYPE A"))
  3825. bError=TRUE;
  3826. }
  3827. else
  3828. if (!Send(L"TYPE I"))
  3829. bError=TRUE;
  3830. break;
  3831. case FILETRANSFER_MODE:
  3832. #ifdef MPEXT_NO_ZLIB
  3833. DebugFail();
  3834. #else
  3835. if (m_useZlib)
  3836. {
  3837. if (!Send(L"MODE S"))
  3838. bError = TRUE;
  3839. }
  3840. else
  3841. if (!Send(L"MODE Z"))
  3842. bError = TRUE;
  3843. #endif
  3844. break;
  3845. case FILETRANSFER_OPTS:
  3846. #ifdef MPEXT_NO_ZLIB
  3847. DebugFail();
  3848. #else
  3849. {
  3850. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3851. CString str;
  3852. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3853. if (!Send(str))
  3854. bError = TRUE;
  3855. }
  3856. #endif
  3857. break;
  3858. case FILETRANSFER_PORTPASV:
  3859. if (pData->bPasv)
  3860. {
  3861. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3862. bError=TRUE;
  3863. }
  3864. else
  3865. {
  3866. if (m_pTransferSocket)
  3867. {
  3868. delete m_pTransferSocket;
  3869. }
  3870. m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
  3871. #ifndef MPEXT_NO_ZLIB
  3872. if (m_useZlib)
  3873. {
  3874. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3875. {
  3876. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3877. ResetOperation(FZ_REPLY_ERROR);
  3878. return;
  3879. }
  3880. }
  3881. #endif
  3882. #ifndef MPEXT_NO_GSS
  3883. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3884. m_pTransferSocket->UseGSS(m_pGssLayer);
  3885. #endif
  3886. m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
  3887. m_pTransferSocket->m_bListening = TRUE;
  3888. m_pTransferSocket->SetFamily(GetFamily());
  3889. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3890. bError = TRUE;
  3891. else if (m_pProxyLayer)
  3892. {
  3893. SOCKADDR_IN addr;
  3894. int len=sizeof(addr);
  3895. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3896. {
  3897. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3898. bError=TRUE;
  3899. }
  3900. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3901. {
  3902. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3903. bError=TRUE;
  3904. }
  3905. //Don't send PORT command yet, params are unknown.
  3906. //will be sent in TransfersocketListenFinished
  3907. }
  3908. else
  3909. {
  3910. //Set up an active file transfer
  3911. CString temp;
  3912. UINT nPort;
  3913. if (//create listen socket (let Windows choose the port) & start listening
  3914. !m_pTransferSocket->Listen() ||
  3915. !m_pTransferSocket->GetSockName(temp, nPort))
  3916. {
  3917. bError = TRUE;
  3918. break;
  3919. }
  3920. CString host;
  3921. if (GetFamily() == AF_INET)
  3922. {
  3923. host = GetOption(OPTION_TRANSFERIP);
  3924. if (host != L"")
  3925. {
  3926. DWORD ip = inet_addr(T2CA(host));
  3927. if (ip != INADDR_NONE)
  3928. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3929. else
  3930. {
  3931. hostent *fullname = gethostbyname(T2CA(host));
  3932. if (!fullname)
  3933. host = L"";
  3934. else
  3935. {
  3936. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3937. if (ip != INADDR_NONE)
  3938. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3939. else
  3940. host = L"";
  3941. }
  3942. }
  3943. }
  3944. if (host == L"")
  3945. {
  3946. UINT temp;
  3947. if (!GetSockName(host, temp))
  3948. bError = true;
  3949. host.Replace(L'.', L',');
  3950. }
  3951. if (!bError)
  3952. {
  3953. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3954. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3955. bError = TRUE;
  3956. }
  3957. }
  3958. else if (GetFamily() == AF_INET6)
  3959. {
  3960. host = GetOption(OPTION_TRANSFERIP6);
  3961. if (host != L"")
  3962. {
  3963. USES_CONVERSION;
  3964. addrinfo hints, *res;
  3965. memset(&hints, 0, sizeof(addrinfo));
  3966. hints.ai_family = AF_INET6;
  3967. hints.ai_socktype = SOCK_STREAM;
  3968. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3969. {
  3970. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3971. freeaddrinfo(res);
  3972. }
  3973. else
  3974. host = L"";
  3975. }
  3976. if (host == L"")
  3977. {
  3978. UINT temp;
  3979. if(!GetSockName(host, temp))
  3980. bError = true;
  3981. }
  3982. if (!bError)
  3983. {
  3984. // assamble EPRT command
  3985. CString cmd;
  3986. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3987. if (!Send(cmd))
  3988. bError = TRUE;
  3989. }
  3990. }
  3991. else
  3992. {
  3993. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3994. bError = true;
  3995. }
  3996. if (bError)
  3997. {
  3998. ResetOperation(FZ_REPLY_ERROR);
  3999. return;
  4000. }
  4001. }
  4002. }
  4003. break;
  4004. case FILETRANSFER_REST:
  4005. DebugAssert(m_pDataFile);
  4006. {
  4007. CString command;
  4008. __int64 transferoffset =
  4009. pData->transferfile.get ?
  4010. GetLength64(*m_pDataFile) :
  4011. pData->transferdata.transfersize-pData->transferdata.transferleft;
  4012. command.Format(L"REST %I64d", transferoffset);
  4013. if (!Send(command))
  4014. bError=TRUE;
  4015. }
  4016. break;
  4017. case FILETRANSFER_RETRSTOR:
  4018. // send RETR/STOR command to server
  4019. if (!m_pTransferSocket)
  4020. {
  4021. ResetOperation(FZ_REPLY_ERROR);
  4022. return;
  4023. }
  4024. m_pTransferSocket->m_transferdata=pData->transferdata;
  4025. // not sure what happens when we active transfer socket immediately while resuming
  4026. // it can possibly make transfer socket start reading from a file before a file pointer is advanced
  4027. if (GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY) ||
  4028. ((pData->transferfile.get || !pData->transferdata.bResume) && !pData->bPasv))
  4029. {
  4030. m_pTransferSocket->SetActive();
  4031. }
  4032. CString filename;
  4033. filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4034. if(!Send((pData->transferfile.get?L"RETR ":(pData->transferdata.bResumeAppend)?L"APPE ":L"STOR ")+ filename))
  4035. bError = TRUE;
  4036. else
  4037. {
  4038. if (pData->bPasv)
  4039. {
  4040. // if PASV create the socket & initiate outbound data channel connection
  4041. if (!ConnectTransferSocket(pData->host, pData->port))
  4042. {
  4043. bError=TRUE;
  4044. }
  4045. }
  4046. }
  4047. break;
  4048. }
  4049. if (bError)
  4050. { //Error transferring the file
  4051. ResetOperation(FZ_REPLY_ERROR);
  4052. return;
  4053. }
  4054. }
  4055. void CFtpControlSocket::TransferHandleListError()
  4056. {
  4057. if (m_pTransferSocket)
  4058. delete m_pTransferSocket;
  4059. m_pTransferSocket=0;
  4060. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  4061. }
  4062. static int atoui(const wchar_t * s)
  4063. {
  4064. wchar_t * endptr;
  4065. int result = wcstol(s, &endptr, 10);
  4066. if ((*s == L'\0') || (*endptr != L'\0'))
  4067. {
  4068. result = -1;
  4069. }
  4070. return result;
  4071. }
  4072. bool CFtpControlSocket::HandleMdtm(int code, t_directory::t_direntry::t_date & date)
  4073. {
  4074. bool result = false;
  4075. if (code==2)
  4076. {
  4077. CString line = GetReply();
  4078. if ( line.GetLength()>4 && line.Left(4) == L"213 " )
  4079. {
  4080. int y=0, M=0, d=0, h=0, m=0, s=0;
  4081. bool hasseconds = false;
  4082. line=line.Mid(4);
  4083. y=atoui(line.Left(4));
  4084. if ((y >= 0) && (line.GetLength() > 4))
  4085. {
  4086. line=line.Mid(4);
  4087. M=atoui(line.Left(2));
  4088. if ((M >= 0) && (line.GetLength() > 2))
  4089. {
  4090. line=line.Mid(2);
  4091. d=atoui(line.Left(2));
  4092. if ((d >= 0) && (line.GetLength() > 2))
  4093. {
  4094. line=line.Mid(2);
  4095. h=atoui(line.Left(2));
  4096. if ((h >= 0) && (line.GetLength() > 2))
  4097. {
  4098. line=line.Mid(2);
  4099. m=atoui(line.Left(2));
  4100. if ((m >= 0) && (line.GetLength() > 2))
  4101. {
  4102. line=line.Mid(2);
  4103. s=_ttoi(line.Left(2));
  4104. hasseconds = true;
  4105. }
  4106. }
  4107. }
  4108. if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60 && s>=0 && s<60)
  4109. {
  4110. result = true;
  4111. date.year = y;
  4112. date.month = M;
  4113. date.day = d;
  4114. date.hour = h;
  4115. date.minute = m;
  4116. date.second = s;
  4117. date.hastime = true;
  4118. date.hasseconds = hasseconds;
  4119. date.hasdate = true;
  4120. date.utc = true;
  4121. }
  4122. }
  4123. }
  4124. }
  4125. }
  4126. return result;
  4127. }
  4128. bool CFtpControlSocket::HandleSize(int code, __int64 & size)
  4129. {
  4130. bool result = false;
  4131. if (code == 2)
  4132. {
  4133. CString line = GetReply();
  4134. if ((line.GetLength() > 4) && (line.Left(4) == L"213 "))
  4135. {
  4136. size = _ttoi64(line.Mid(4));
  4137. result = true;
  4138. }
  4139. }
  4140. return result;
  4141. }
  4142. void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads)
  4143. {
  4144. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  4145. if (GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile &&
  4146. pData->transferfile.get)
  4147. {
  4148. m_pTools->PreserveDownloadFileTime(
  4149. (HANDLE)m_pDataFile->m_hFile, reinterpret_cast<void *>(pData->transferfile.nUserData));
  4150. }
  4151. if (!pData->transferfile.get &&
  4152. GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && preserveFileTimeForUploads &&
  4153. ((m_serverCapabilities.GetCapability(mfmt_command) == yes) ||
  4154. (m_serverCapabilities.GetCapability(mdtm_command) == yes)))
  4155. {
  4156. CString filename =
  4157. pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4158. struct tm tm;
  4159. if (m_pTools->GetFileModificationTimeInUtc((LPCTSTR)pData->transferfile.localfile, tm))
  4160. {
  4161. CString timestr;
  4162. timestr.Format(L"%02d%02d%02d%02d%02d%02d",
  4163. 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  4164. CString command;
  4165. if (m_serverCapabilities.GetCapability(mfmt_command) == yes)
  4166. {
  4167. command = L"MFMT";
  4168. }
  4169. else
  4170. {
  4171. // Support for MDTM does not necessarily mean
  4172. // that the server supports non-standard hack
  4173. // of setting timestamp using
  4174. // MFMT-like (two argument) call to MDTM.
  4175. // IIS definitelly does.
  4176. command = L"MDTM";
  4177. }
  4178. if (Send( command + L" " + timestr + L" " + filename))
  4179. {
  4180. m_Operation.nOpState = FILETRANSFER_MFMT;
  4181. return;
  4182. }
  4183. }
  4184. }
  4185. //Transfer successful
  4186. ResetOperation(FZ_REPLY_OK);
  4187. }
  4188. void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
  4189. {
  4190. const int nOpMode = m_Operation.nOpMode;
  4191. if (nOpMode==CSMODE_CONNECT)
  4192. DoClose(FZ_REPLY_CANCEL);
  4193. else if (nOpMode & CSMODE_LIST)
  4194. {
  4195. if (m_Operation.nOpState == LIST_WAITFINISH)
  4196. m_skipReply = true;
  4197. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4198. }
  4199. else if (nOpMode & CSMODE_TRANSFER)
  4200. {
  4201. if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
  4202. m_skipReply = true;
  4203. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
  4204. }
  4205. else if (nOpMode != CSMODE_NONE)
  4206. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4207. if (nOpMode != CSMODE_NONE && !bQuit)
  4208. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  4209. if (m_awaitsReply)
  4210. m_skipReply = true;
  4211. }
  4212. void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
  4213. {
  4214. if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
  4215. {
  4216. CString host;
  4217. host.Format(L"%d,%d,%d,%d,%d,%d",ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
  4218. Send(L"PORT "+host);
  4219. }
  4220. }
  4221. void CFtpControlSocket::ResumeTransfer()
  4222. {
  4223. if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
  4224. {
  4225. m_pTransferSocket->OnSend(0);
  4226. m_pTransferSocket->OnReceive(0);
  4227. }
  4228. }
  4229. BOOL CFtpControlSocket::Create()
  4230. {
  4231. if (!GetOptionVal(OPTION_LIMITPORTRANGE))
  4232. 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);
  4233. else
  4234. {
  4235. int min=GetOptionVal(OPTION_PORTRANGELOW);
  4236. int max=GetOptionVal(OPTION_PORTRANGEHIGH);
  4237. if (min>=max)
  4238. {
  4239. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4240. return FALSE;
  4241. }
  4242. int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  4243. int port = startport;
  4244. 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))
  4245. {
  4246. port++;
  4247. if (port>max)
  4248. port=min;
  4249. if (port==startport)
  4250. {
  4251. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4252. return FALSE;
  4253. }
  4254. if (!InitConnect())
  4255. return FALSE;
  4256. }
  4257. }
  4258. return TRUE;
  4259. }
  4260. void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
  4261. {
  4262. if (nSuccessful & FZ_REPLY_CRITICALERROR)
  4263. nSuccessful |= FZ_REPLY_ERROR;
  4264. if (m_pTransferSocket)
  4265. delete m_pTransferSocket;
  4266. m_pTransferSocket=0;
  4267. if (m_pDataFile)
  4268. delete m_pDataFile;
  4269. m_pDataFile=0;
  4270. if (m_Operation.nOpMode)
  4271. {
  4272. //Unset busy attribute so that new commands can be executed
  4273. m_pOwner->SetBusy(FALSE);
  4274. if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
  4275. {
  4276. nSuccessful|=FZ_REPLY_DISCONNECTED;
  4277. ShowStatus(IDS_ERRORMSG_CANTCONNECT, FZ_LOG_ERROR);
  4278. }
  4279. if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_LISTFILE|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
  4280. m_LastSendTime=CTime::GetCurrentTime();
  4281. //Update remote file entry
  4282. if (m_Operation.pData &&
  4283. m_Operation.nOpMode&CSMODE_TRANSFER &&
  4284. (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
  4285. m_pDirectoryListing &&
  4286. m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
  4287. {
  4288. CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
  4289. CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
  4290. t_directory dir;
  4291. BOOL res=FALSE;
  4292. if (m_pDirectoryListing)
  4293. {
  4294. if (m_pDirectoryListing->path==path)
  4295. {
  4296. dir=*m_pDirectoryListing;
  4297. res=TRUE;
  4298. }
  4299. }
  4300. t_directory WorkingDir;
  4301. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4302. if (!res && bFound)
  4303. if (WorkingDir.path==path)
  4304. {
  4305. dir=WorkingDir;
  4306. res=TRUE;
  4307. }
  4308. if (res)
  4309. {
  4310. int i;
  4311. for (i=0; i<dir.num; i++)
  4312. if (dir.direntry[i].name==filename)
  4313. {
  4314. dir.direntry[i].bUnsure = TRUE;
  4315. if (nSuccessful & FZ_REPLY_ERROR)
  4316. {
  4317. dir.direntry[i].bUnsure = TRUE;
  4318. if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
  4319. dir.direntry[i].size = -1;
  4320. if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
  4321. dir.direntry[i].size = -1;
  4322. }
  4323. dir.direntry[i].date.hasdate = false;
  4324. break;
  4325. }
  4326. if (i==dir.num)
  4327. {
  4328. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4329. int i;
  4330. for (i=0; i<dir.num; i++)
  4331. entries[i]=dir.direntry[i];
  4332. entries[i].name=filename;
  4333. entries[i].dir=FALSE;
  4334. entries[i].date.hasdate=FALSE;
  4335. entries[i].size=-1;
  4336. if (nSuccessful&FZ_REPLY_OK)
  4337. entries[i].bUnsure=FALSE;
  4338. else
  4339. entries[i].bUnsure=TRUE;
  4340. delete [] dir.direntry;
  4341. dir.direntry=entries;
  4342. dir.num++;
  4343. }
  4344. BOOL updated=FALSE;
  4345. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  4346. {
  4347. updated=TRUE;
  4348. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4349. }
  4350. if (!updated)
  4351. if (bFound && WorkingDir.path==dir.path)
  4352. {
  4353. updated = TRUE;
  4354. m_pOwner->SetWorkingDir(&dir);
  4355. }
  4356. }
  4357. }
  4358. if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
  4359. {
  4360. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  4361. if (nSuccessful&FZ_REPLY_ABORTED)
  4362. //Transfer aborted by user
  4363. ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,FZ_LOG_ERROR);
  4364. else
  4365. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR);
  4366. else if (m_Operation.nOpMode&CSMODE_LIST)
  4367. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  4368. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  4369. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4370. }
  4371. else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
  4372. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS);
  4373. }
  4374. else
  4375. {
  4376. // When control socket is waiting for reply
  4377. // to keepalive (!IsReady), while new command comes,
  4378. // its execution is postponed
  4379. // (CMainThread::m_pPostKeepAliveCommand),
  4380. // but the main thread
  4381. // is set to busy state already (CMainThread::Command).
  4382. // if connection is closed before without receiving reply,
  4383. // main thread would stay busy forever.
  4384. m_pOwner->SetBusy(FALSE);
  4385. //No operation in progress
  4386. nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
  4387. if (!nSuccessful)
  4388. DebugFail();
  4389. }
  4390. if (nSuccessful&FZ_REPLY_DISCONNECTED)
  4391. m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
  4392. if (m_Operation.nOpMode)
  4393. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
  4394. else
  4395. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
  4396. m_Operation.nOpMode=0;
  4397. m_Operation.nOpState=-1;
  4398. if (m_Operation.pData)
  4399. delete m_Operation.pData;
  4400. m_Operation.pData=0;
  4401. }
  4402. void CFtpControlSocket::Delete(CString filename, const CServerPath &path)
  4403. {
  4404. class CDeleteData : public CFtpControlSocket::t_operation::COpData
  4405. {
  4406. public:
  4407. CDeleteData() {}
  4408. virtual ~CDeleteData() {}
  4409. CString m_FileName;
  4410. CServerPath path;
  4411. };
  4412. if (filename!=L"")
  4413. {
  4414. DebugAssert(!path.IsEmpty());
  4415. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4416. DebugAssert(m_Operation.nOpState==-1);
  4417. DebugAssert(!m_Operation.pData);
  4418. m_Operation.nOpMode=CSMODE_DELETE;
  4419. if (!Send(L"DELE " + path.FormatFilename(filename)))
  4420. return;
  4421. CDeleteData *data=new CDeleteData;
  4422. data->m_FileName=filename;
  4423. data->path=path;
  4424. m_Operation.pData=data;
  4425. }
  4426. else
  4427. {
  4428. DebugAssert(path.IsEmpty());
  4429. DebugAssert(m_Operation.nOpMode==CSMODE_DELETE);
  4430. DebugAssert(m_Operation.nOpState==-1);
  4431. DebugAssert(m_Operation.pData);
  4432. int res=GetReplyCode();
  4433. if (res==2 || res==3)
  4434. { //Remove file from cached dirs
  4435. CDeleteData *pData=(CDeleteData *)m_Operation.pData;
  4436. t_directory dir;
  4437. BOOL res=FALSE;
  4438. if (m_pDirectoryListing)
  4439. {
  4440. if (m_pDirectoryListing->path==pData->path)
  4441. {
  4442. dir=*m_pDirectoryListing;
  4443. res=TRUE;
  4444. }
  4445. }
  4446. t_directory WorkingDir;
  4447. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4448. if (!res && bFound)
  4449. if (WorkingDir.path==pData->path)
  4450. {
  4451. dir=WorkingDir;
  4452. res=TRUE;
  4453. }
  4454. if (res)
  4455. {
  4456. BOOL found=FALSE;
  4457. for (int i=0;i<dir.num;i++)
  4458. {
  4459. if (dir.direntry[i].name==pData->m_FileName)
  4460. {
  4461. DebugAssert(!dir.direntry[i].dir || dir.direntry[i].bLink);
  4462. found=TRUE;
  4463. break;
  4464. }
  4465. }
  4466. if (found)
  4467. {
  4468. t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
  4469. int j=0;
  4470. int i;
  4471. for (i=0; i<dir.num; i++)
  4472. {
  4473. if (dir.direntry[i].name==pData->m_FileName)
  4474. continue;
  4475. direntry[j]=dir.direntry[i];
  4476. j++;
  4477. }
  4478. delete [] dir.direntry;
  4479. dir.direntry=direntry;
  4480. dir.num--;
  4481. BOOL updated=FALSE;
  4482. if (m_pDirectoryListing)
  4483. if (m_pDirectoryListing->path==dir.path)
  4484. {
  4485. updated=TRUE;
  4486. SetDirectoryListing(&dir);
  4487. }
  4488. if (!updated)
  4489. if (WorkingDir.path==dir.path)
  4490. {
  4491. updated=TRUE;
  4492. m_pOwner->SetWorkingDir(&dir);
  4493. }
  4494. }
  4495. }
  4496. }
  4497. ResetOperation(FZ_REPLY_OK);
  4498. }
  4499. }
  4500. void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
  4501. {
  4502. class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
  4503. {
  4504. public:
  4505. CRemoveDirData() {}
  4506. virtual ~CRemoveDirData() {}
  4507. CString m_DirName;
  4508. CServerPath path;
  4509. };
  4510. if (dirname != L"")
  4511. {
  4512. DebugAssert(!path.IsEmpty());
  4513. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4514. DebugAssert(m_Operation.nOpState == -1);
  4515. DebugAssert(!m_Operation.pData);
  4516. m_Operation.nOpMode = CSMODE_RMDIR;
  4517. CServerPath newPath = path;
  4518. if (!newPath.AddSubdir(dirname))
  4519. {
  4520. ShowStatus(L"Unable to concatenate path", FZ_LOG_ERROR);
  4521. return;
  4522. }
  4523. if (!Send(L"RMD "+ newPath.GetPath()))
  4524. return;
  4525. CRemoveDirData *data = new CRemoveDirData;
  4526. data->m_DirName = dirname;
  4527. data->path = path;
  4528. m_Operation.pData = data;
  4529. }
  4530. else
  4531. {
  4532. DebugAssert(path.IsEmpty());
  4533. DebugAssert(m_Operation.nOpMode == CSMODE_RMDIR);
  4534. DebugAssert(m_Operation.nOpState == -1);
  4535. DebugAssert(m_Operation.pData);
  4536. int res = GetReplyCode();
  4537. if (res == 2 || res == 3)
  4538. { //Remove dir from cached dirs
  4539. CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData;
  4540. t_directory dir;
  4541. BOOL res = FALSE;
  4542. if (m_pDirectoryListing)
  4543. {
  4544. if (m_pDirectoryListing->path == pData->path)
  4545. {
  4546. dir = *m_pDirectoryListing;
  4547. res = TRUE;
  4548. }
  4549. }
  4550. t_directory WorkingDir;
  4551. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4552. if (!res && bFound)
  4553. if (WorkingDir.path == pData->path)
  4554. {
  4555. dir = WorkingDir;
  4556. res = TRUE;
  4557. }
  4558. if (res)
  4559. {
  4560. BOOL found = FALSE;
  4561. for (int i = 0; i < dir.num; i++)
  4562. {
  4563. if (dir.direntry[i].name == pData->m_DirName)
  4564. {
  4565. DebugAssert(dir.direntry[i].dir);
  4566. found = TRUE;
  4567. break;
  4568. }
  4569. }
  4570. if (found)
  4571. {
  4572. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
  4573. int j = 0;
  4574. int i;
  4575. for (i = 0; i < dir.num; i++)
  4576. {
  4577. if (dir.direntry[i].name == pData->m_DirName)
  4578. continue;
  4579. direntry[j] = dir.direntry[i];
  4580. j++;
  4581. }
  4582. delete [] dir.direntry;
  4583. dir.direntry = direntry;
  4584. dir.num--;
  4585. BOOL updated = FALSE;
  4586. if (m_pDirectoryListing)
  4587. if (m_pDirectoryListing->path == dir.path)
  4588. {
  4589. updated = TRUE;
  4590. SetDirectoryListing(&dir);
  4591. }
  4592. if (!updated)
  4593. if (WorkingDir.path == dir.path)
  4594. {
  4595. updated = TRUE;
  4596. m_pOwner->SetWorkingDir(&dir);
  4597. }
  4598. }
  4599. }
  4600. ResetOperation(FZ_REPLY_OK);
  4601. }
  4602. else
  4603. ResetOperation(FZ_REPLY_ERROR);
  4604. }
  4605. }
  4606. int CFtpControlSocket::CheckOverwriteFile()
  4607. {
  4608. if (!m_Operation.pData)
  4609. {
  4610. return FZ_REPLY_ERROR;
  4611. }
  4612. CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
  4613. int nReplyError = 0;
  4614. CFileStatus64 status;
  4615. BOOL res = GetStatus64(pData->transferfile.localfile, status);
  4616. if (!res)
  4617. {
  4618. if (!pData->transferfile.get)
  4619. {
  4620. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4621. nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
  4622. }
  4623. else
  4624. {
  4625. m_Operation.nOpState = FILETRANSFER_TYPE;
  4626. }
  4627. }
  4628. else
  4629. {
  4630. if (status.m_attribute & 0x10)
  4631. {
  4632. nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
  4633. }
  4634. else
  4635. {
  4636. _int64 localsize;
  4637. if (!GetLength64(pData->transferfile.localfile, localsize))
  4638. if (!pData->transferfile.get)
  4639. nReplyError = FZ_REPLY_CRITICALERROR;
  4640. else
  4641. m_Operation.nOpState = FILETRANSFER_TYPE;
  4642. CTime *localtime = NULL;
  4643. TRY
  4644. {
  4645. if (status.m_has_mtime && status.m_mtime != -1)
  4646. localtime = new CTime(status.m_mtime);
  4647. }
  4648. CATCH_ALL(e)
  4649. {
  4650. TCHAR buffer[1024];
  4651. CString str =L"Exception creating CTime object: ";
  4652. if (e->GetErrorMessage(buffer, 1024, NULL))
  4653. str += buffer;
  4654. else
  4655. str += L"Unknown exception";
  4656. LogMessageRaw(FZ_LOG_WARNING, str);
  4657. localtime = NULL;
  4658. }
  4659. END_CATCH_ALL;
  4660. BOOL bRemoteFileExists = FALSE;
  4661. __int64 remotesize = -1;
  4662. t_directory::t_direntry::t_date remotetime;
  4663. if (m_pDirectoryListing)
  4664. {
  4665. for (int i=0; i<m_pDirectoryListing->num; i++)
  4666. {
  4667. CString remotefile = pData->transferfile.remotefile;
  4668. if (m_pDirectoryListing->direntry[i].name == remotefile)
  4669. {
  4670. remotesize = m_pDirectoryListing->direntry[i].size;
  4671. remotetime = m_pDirectoryListing->direntry[i].date;
  4672. bRemoteFileExists = TRUE;
  4673. break;
  4674. }
  4675. }
  4676. }
  4677. if (!bRemoteFileExists && pData->hasRemoteDate)
  4678. {
  4679. remotetime = pData->remoteDate;
  4680. bRemoteFileExists = TRUE;
  4681. }
  4682. if (remotesize == -1 && pData->pFileSize)
  4683. {
  4684. remotesize = *pData->pFileSize;
  4685. bRemoteFileExists = TRUE;
  4686. }
  4687. if (bRemoteFileExists || pData->transferfile.get )
  4688. {
  4689. COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
  4690. t_transferfile *pTransferFile = new t_transferfile;
  4691. *pTransferFile = pData->transferfile;
  4692. pOverwriteData->pTransferFile = pTransferFile;
  4693. if (pData->transferfile.get)
  4694. {
  4695. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4696. // pos can be -1 here, e.g. in scripting, the code below still works then
  4697. pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
  4698. pOverwriteData->FileName2 = pData->transferfile.remotefile;
  4699. pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
  4700. pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
  4701. pOverwriteData->size1 = localsize;
  4702. pOverwriteData->size2 = remotesize;
  4703. }
  4704. else
  4705. {
  4706. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4707. // pos can be -1 here, e.g. in scripting, the code below still works then
  4708. pOverwriteData->FileName1 = pData->transferfile.remotefile;
  4709. pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
  4710. pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
  4711. pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
  4712. pOverwriteData->size1 = remotesize;
  4713. pOverwriteData->size2 = localsize;
  4714. }
  4715. pOverwriteData->localtime = localtime;
  4716. pOverwriteData->remotetime = remotetime;
  4717. pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  4718. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
  4719. {
  4720. delete pOverwriteData;
  4721. nReplyError = FZ_REPLY_ERROR;
  4722. }
  4723. else
  4724. {
  4725. m_bCheckForTimeout = FALSE;
  4726. m_Operation.nOpState = FILETRANSFER_WAIT;
  4727. }
  4728. }
  4729. else
  4730. {
  4731. m_Operation.nOpState = FILETRANSFER_TYPE;
  4732. delete localtime;
  4733. }
  4734. }
  4735. }
  4736. return nReplyError;
  4737. }
  4738. void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
  4739. {
  4740. if (!pData)
  4741. return;
  4742. if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
  4743. return;
  4744. if (m_Operation.nOpState != FILETRANSFER_WAIT)
  4745. return;
  4746. CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
  4747. if (!pTransferData)
  4748. return;
  4749. pTransferData->transferdata.bResume = false;
  4750. m_bCheckForTimeout = TRUE;
  4751. int nReplyError = 0;
  4752. switch (nAction)
  4753. {
  4754. case FILEEXISTS_SKIP:
  4755. nReplyError = FZ_REPLY_OK;
  4756. break;
  4757. case FILEEXISTS_OVERWRITE:
  4758. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4759. break;
  4760. case FILEEXISTS_RENAME:
  4761. if (pTransferData->transferfile.get)
  4762. {
  4763. CFileStatus64 status;
  4764. if (GetStatus64(pData->FileName1, status))
  4765. {
  4766. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4767. nReplyError= FZ_REPLY_CRITICALERROR;
  4768. }
  4769. else
  4770. {
  4771. pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
  4772. //Replace invalid characters in the local filename
  4773. int pos = pTransferData->transferfile.localfile.ReverseFind(L'\\');
  4774. for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
  4775. if (pTransferData->transferfile.localfile[i] == L':')
  4776. pTransferData->transferfile.localfile.SetAt(i, L'_');
  4777. pTransferData->nWaitNextOpState= FILETRANSFER_TYPE;
  4778. }
  4779. }
  4780. else
  4781. {
  4782. DebugAssert(m_pDirectoryListing);
  4783. int i;
  4784. for (i = 0; i < m_pDirectoryListing->num; i++)
  4785. {
  4786. if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
  4787. {
  4788. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4789. nReplyError = FZ_REPLY_CRITICALERROR;
  4790. break;
  4791. }
  4792. }
  4793. if (i==m_pDirectoryListing->num)
  4794. {
  4795. pTransferData->transferfile.remotefile = pData->FileName1;
  4796. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4797. }
  4798. }
  4799. break;
  4800. case FILEEXISTS_RESUME:
  4801. if (pData->size1 >= 0)
  4802. {
  4803. pTransferData->transferdata.bResume = TRUE;
  4804. }
  4805. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4806. break;
  4807. case FILEEXISTS_COMPLETE:
  4808. // Simulating transfer finish
  4809. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  4810. TransferFinished(true);
  4811. return; // Avoid call to FileTransfer below
  4812. }
  4813. if (nReplyError == FZ_REPLY_OK)
  4814. ResetOperation(FZ_REPLY_OK);
  4815. else if (nReplyError)
  4816. ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
  4817. else
  4818. FileTransfer();
  4819. }
  4820. void CFtpControlSocket::SendKeepAliveCommand()
  4821. {
  4822. ShowStatus(L"Sending dummy command to keep session alive.", FZ_LOG_PROGRESS);
  4823. m_bKeepAliveActive=TRUE;
  4824. //Choose a random command from the list
  4825. TCHAR commands[4][7]={L"PWD",L"REST 0",L"TYPE A",L"TYPE I"};
  4826. int choice=(rand()*4)/(RAND_MAX+1);
  4827. Send(commands[choice]);
  4828. }
  4829. void CFtpControlSocket::MakeDir(const CServerPath &path)
  4830. {
  4831. //Directory creation works like this:
  4832. //Find existing parent and create subdirs one by one
  4833. if (m_Operation.nOpState == MKD_INIT)
  4834. {
  4835. DebugAssert(!path.IsEmpty());
  4836. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4837. DebugAssert(!m_Operation.pData);
  4838. m_Operation.nOpMode = CSMODE_MKDIR;
  4839. if (!Send(L"CWD "+path.GetParent().GetPath()))
  4840. return;
  4841. CMakeDirData *data = new CMakeDirData;
  4842. data->path = path;
  4843. data->Current = path.GetParent();
  4844. data->Segments.push_front(path.GetLastSegment());
  4845. m_Operation.pData = data;
  4846. m_Operation.nOpState = MKD_FINDPARENT;
  4847. }
  4848. else if (m_Operation.nOpState==MKD_FINDPARENT)
  4849. {
  4850. DebugAssert(m_Operation.nOpMode==CSMODE_MKDIR);
  4851. DebugAssert(path.IsEmpty());
  4852. DebugAssert(m_Operation.pData);
  4853. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4854. int res=GetReplyCode();
  4855. if (res==2 || res==3)
  4856. {
  4857. m_pOwner->SetCurrentPath(pData->Current);
  4858. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4859. pData->Current.AddSubdir(pData->Segments.front());
  4860. CString Segment=pData->Segments.front();
  4861. pData->Segments.pop_front();
  4862. if (Send( L"MKD " + Segment))
  4863. m_Operation.nOpState = MKD_CHANGETOSUBDIR;
  4864. else
  4865. return;
  4866. }
  4867. else
  4868. {
  4869. if (!pData->Current.HasParent())
  4870. ResetOperation(FZ_REPLY_ERROR);
  4871. else
  4872. {
  4873. pData->Segments.push_front(pData->Current.GetLastSegment());
  4874. pData->Current=pData->Current.GetParent();
  4875. if (!Send(L"CWD "+pData->Current.GetPath()))
  4876. return;
  4877. }
  4878. }
  4879. }
  4880. else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
  4881. {
  4882. int res=GetReplyCode();
  4883. if (res==2 || res==3)
  4884. { //Create dir entry in parent dir
  4885. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4886. DebugAssert(!pData->Segments.empty());
  4887. m_pOwner->SetCurrentPath(pData->Current);
  4888. pData->Current.AddSubdir(pData->Segments.front());
  4889. CString Segment=pData->Segments.front();
  4890. pData->Segments.pop_front();
  4891. if (Send( L"MKD " + Segment))
  4892. m_Operation.nOpState=MKD_CHANGETOSUBDIR;
  4893. else
  4894. return;
  4895. }
  4896. else
  4897. ResetOperation(FZ_REPLY_ERROR);
  4898. }
  4899. else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
  4900. {
  4901. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4902. int res=GetReplyCode();
  4903. if (res==2 || res==3 || //Creation successful
  4904. GetReply() == L"550 Directory already exists")//Creation was successful, although someone else did the work for us
  4905. { //Create dir entry in parent dir
  4906. CServerPath path2=pData->Current;
  4907. if (path2.HasParent())
  4908. {
  4909. CString name=path2.GetLastSegment();
  4910. path2=path2.GetParent();
  4911. t_directory dir;
  4912. BOOL res = FALSE;
  4913. if (m_pDirectoryListing)
  4914. {
  4915. if (m_pDirectoryListing->path == path2)
  4916. {
  4917. dir = *m_pDirectoryListing;
  4918. res = TRUE;
  4919. }
  4920. }
  4921. t_directory WorkingDir;
  4922. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4923. if (!res && bFound)
  4924. if (WorkingDir.path == path2)
  4925. {
  4926. dir = WorkingDir;
  4927. res = TRUE;
  4928. }
  4929. if (!res)
  4930. {
  4931. dir.path = path2;
  4932. dir.server = m_CurrentServer;
  4933. }
  4934. int i;
  4935. for (i=0; i<dir.num; i++)
  4936. if (dir.direntry[i].name==name)
  4937. {
  4938. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  4939. break;
  4940. }
  4941. if (i==dir.num)
  4942. {
  4943. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4944. for (i=0;i<dir.num;i++)
  4945. entries[i]=dir.direntry[i];
  4946. entries[i].name=name;
  4947. entries[i].dir=TRUE;
  4948. entries[i].date.hasdate=FALSE;
  4949. entries[i].size=-1;
  4950. entries[i].bUnsure=FALSE;
  4951. delete [] dir.direntry;
  4952. dir.direntry=entries;
  4953. dir.num++;
  4954. BOOL updated = FALSE;
  4955. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4956. {
  4957. updated = TRUE;
  4958. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4959. }
  4960. if (!updated)
  4961. if (bFound && WorkingDir.path == dir.path)
  4962. {
  4963. updated = TRUE;
  4964. m_pOwner->SetWorkingDir(&dir);
  4965. }
  4966. }
  4967. }
  4968. }
  4969. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  4970. if (pData->Segments.empty())
  4971. ResetOperation(FZ_REPLY_OK);
  4972. else
  4973. {
  4974. if (Send( L"CWD " + pData->Current.GetPath()))
  4975. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4976. else
  4977. return;
  4978. }
  4979. }
  4980. else
  4981. DebugFail();
  4982. }
  4983. void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
  4984. {
  4985. class CRenameData : public CFtpControlSocket::t_operation::COpData
  4986. {
  4987. public:
  4988. CRenameData() {}
  4989. virtual ~CRenameData() {}
  4990. CString oldName, newName;
  4991. CServerPath path;
  4992. CServerPath newPath;
  4993. };
  4994. if (oldName != L"")
  4995. {
  4996. DebugAssert(newName != L"");
  4997. DebugAssert(!path.IsEmpty());
  4998. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4999. DebugAssert(m_Operation.nOpState == -1);
  5000. DebugAssert(!m_Operation.pData);
  5001. m_Operation.nOpMode = CSMODE_RENAME;
  5002. if (!Send(L"RNFR " + path.FormatFilename(oldName)))
  5003. return;
  5004. CRenameData *data = new CRenameData;
  5005. data->oldName = oldName;
  5006. data->newName = newName;
  5007. data->path = path;
  5008. data->newPath = newPath;
  5009. m_Operation.pData = data;
  5010. }
  5011. else
  5012. {
  5013. DebugAssert(oldName == L"");
  5014. DebugAssert(path.IsEmpty());
  5015. DebugAssert(m_Operation.nOpMode == CSMODE_RENAME);
  5016. DebugAssert(m_Operation.pData);
  5017. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5018. if (m_Operation.nOpState == -1)
  5019. {
  5020. int res = GetReplyCode();
  5021. if (res == 2 || res == 3)
  5022. {
  5023. m_Operation.nOpState++;
  5024. if (pData->newPath.IsEmpty())
  5025. {
  5026. if (!Send(L"RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5027. return;
  5028. }
  5029. else
  5030. if (!Send(L"RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5031. return;
  5032. }
  5033. else
  5034. ResetOperation(FZ_REPLY_ERROR);
  5035. }
  5036. else
  5037. {
  5038. int res = GetReplyCode();
  5039. if (res == 2 || res == 3)
  5040. { //Rename entry in cached directory
  5041. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5042. t_directory dir;
  5043. BOOL res = FALSE;
  5044. if (m_pDirectoryListing)
  5045. {
  5046. if (m_pDirectoryListing->path == pData->path)
  5047. {
  5048. dir = *m_pDirectoryListing;
  5049. res = TRUE;
  5050. }
  5051. }
  5052. t_directory WorkingDir;
  5053. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5054. if (!res && bFound)
  5055. if (WorkingDir.path == pData->path)
  5056. {
  5057. dir = WorkingDir;
  5058. res = TRUE;
  5059. }
  5060. if (res)
  5061. {
  5062. for (int i=0; i<dir.num; i++)
  5063. if (dir.direntry[i].name == pData->oldName)
  5064. {
  5065. if (pData->newPath.IsEmpty())
  5066. {
  5067. dir.direntry[i].name = pData->newName;
  5068. BOOL updated = FALSE;
  5069. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5070. {
  5071. updated = TRUE;
  5072. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5073. }
  5074. if (!updated)
  5075. if (WorkingDir.path == dir.path)
  5076. {
  5077. updated = TRUE;
  5078. m_pOwner->SetWorkingDir(&dir);
  5079. }
  5080. }
  5081. else
  5082. {
  5083. t_directory::t_direntry oldentry = dir.direntry[i];
  5084. for (int j = i+1; j < dir.num; j++)
  5085. {
  5086. dir.direntry[j-1] = dir.direntry[j];
  5087. }
  5088. dir.num--;
  5089. BOOL updated = FALSE;
  5090. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5091. {
  5092. updated = TRUE;
  5093. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5094. }
  5095. if (!updated)
  5096. if (WorkingDir.path == dir.path)
  5097. {
  5098. updated = TRUE;
  5099. m_pOwner->SetWorkingDir(&dir);
  5100. }
  5101. BOOL res = FALSE;
  5102. if (m_pDirectoryListing)
  5103. {
  5104. if (m_pDirectoryListing->path == pData->newPath)
  5105. {
  5106. dir = *m_pDirectoryListing;
  5107. res = TRUE;
  5108. }
  5109. }
  5110. t_directory WorkingDir;
  5111. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5112. if (!res && bFound)
  5113. if (WorkingDir.path == pData->newPath)
  5114. {
  5115. dir = WorkingDir;
  5116. res = TRUE;
  5117. }
  5118. if (res)
  5119. {
  5120. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
  5121. for (int i = 0; i < dir.num; i++)
  5122. direntry[i] = dir.direntry[i];
  5123. direntry[dir.num] = oldentry;
  5124. direntry[dir.num].name = pData->newName;
  5125. dir.num++;
  5126. delete [] dir.direntry;
  5127. dir.direntry = direntry;
  5128. BOOL updated = FALSE;
  5129. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5130. {
  5131. updated = TRUE;
  5132. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5133. }
  5134. if (!updated)
  5135. if (bFound && WorkingDir.path == dir.path)
  5136. {
  5137. updated = TRUE;
  5138. m_pOwner->SetWorkingDir(&dir);
  5139. }
  5140. }
  5141. }
  5142. break;
  5143. }
  5144. }
  5145. ResetOperation(FZ_REPLY_OK);
  5146. }
  5147. else
  5148. ResetOperation(FZ_REPLY_ERROR);
  5149. }
  5150. }
  5151. }
  5152. void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
  5153. {
  5154. DebugAssert(pData);
  5155. if (!m_pSslLayer)
  5156. return;
  5157. if (!m_Operation.nOpMode == CSMODE_CONNECT)
  5158. return;
  5159. m_bCheckForTimeout = TRUE;
  5160. m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
  5161. m_LastRecvTime = CTime::GetCurrentTime();
  5162. }
  5163. void CFtpControlSocket::OnTimer()
  5164. {
  5165. CheckForTimeout();
  5166. ResumeTransfer();
  5167. if (GetOptionVal(OPTION_KEEPALIVE))
  5168. {
  5169. if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
  5170. {
  5171. //Getting intervals for the Keep Alive feature
  5172. int low=GetOptionVal(OPTION_INTERVALLOW);
  5173. int diff=GetOptionVal(OPTION_INTERVALHIGH)-low;
  5174. //Choose a new delay
  5175. int delay=low+(rand()*diff)/RAND_MAX;
  5176. CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
  5177. if (span.GetTotalSeconds()>=delay)
  5178. SendKeepAliveCommand();
  5179. }
  5180. }
  5181. }
  5182. BOOL CFtpControlSocket::IsReady()
  5183. {
  5184. return !m_bKeepAliveActive;
  5185. }
  5186. void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
  5187. {
  5188. m_Operation.nOpMode=CSMODE_CHMOD;
  5189. CString str;
  5190. str.Format( L"SITE CHMOD %03d %s", nValue, path.FormatFilename(filename));
  5191. Send(str);
  5192. }
  5193. void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
  5194. {
  5195. switch (pData->nRequestType)
  5196. {
  5197. case FZ_ASYNCREQUEST_OVERWRITE:
  5198. SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
  5199. break;
  5200. case FZ_ASYNCREQUEST_VERIFYCERT:
  5201. SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
  5202. break;
  5203. case FZ_ASYNCREQUEST_NEEDPASS:
  5204. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5205. m_Operation.nOpState != CONNECT_NEEDPASS)
  5206. break;
  5207. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5208. {
  5209. DoClose();
  5210. break;
  5211. }
  5212. if (!nAction)
  5213. {
  5214. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5215. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5216. break;
  5217. }
  5218. else
  5219. {
  5220. m_bCheckForTimeout = TRUE;
  5221. m_CurrentServer.pass=((CNeedPassRequestData *)pData)->Password;
  5222. m_Operation.nOpState=((CNeedPassRequestData *)pData)->nOldOpState;
  5223. CLogonData *pLogonData = static_cast<CLogonData *>(m_Operation.pData);
  5224. pLogonData->waitForAsyncRequest = false;
  5225. pLogonData->gotPassword = true;
  5226. LogOnToServer(TRUE);
  5227. }
  5228. break;
  5229. #ifndef MPEXT_NO_GSS
  5230. case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
  5231. if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
  5232. break;
  5233. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5234. {
  5235. DoClose();
  5236. break;
  5237. }
  5238. if (!nAction)
  5239. {
  5240. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5241. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5242. break;
  5243. }
  5244. m_bCheckForTimeout = TRUE;
  5245. m_Operation.nOpState=-1;
  5246. LogOnToServer(TRUE);
  5247. break;
  5248. case FZ_ASYNCREQUEST_GSS_NEEDPASS:
  5249. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5250. m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
  5251. break;
  5252. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5253. {
  5254. DoClose();
  5255. break;
  5256. }
  5257. if (!nAction)
  5258. {
  5259. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5260. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5261. break;
  5262. }
  5263. else
  5264. {
  5265. m_bCheckForTimeout = TRUE;
  5266. m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
  5267. m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
  5268. LogOnToServer(TRUE);
  5269. }
  5270. break;
  5271. case FZ_ASYNCREQUEST_GSS_NEEDUSER:
  5272. if (m_Operation.nOpMode != CSMODE_CONNECT ||
  5273. m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
  5274. break;
  5275. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5276. {
  5277. DoClose();
  5278. break;
  5279. }
  5280. if (!nAction)
  5281. {
  5282. DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
  5283. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  5284. break;
  5285. }
  5286. else
  5287. {
  5288. m_bCheckForTimeout = TRUE;
  5289. m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
  5290. m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
  5291. LogOnToServer(TRUE);
  5292. }
  5293. break;
  5294. #endif
  5295. default:
  5296. LogMessage(FZ_LOG_WARNING, L"Unknown request reply %d", pData->nRequestType);
  5297. break;
  5298. }
  5299. }
  5300. int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  5301. {
  5302. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  5303. {
  5304. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  5305. {
  5306. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  5307. {
  5308. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  5309. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  5310. if (iter->pLayer == m_pProxyLayer)
  5311. LogMessage(FZ_LOG_INFO, L"Proxy layer changed state from %s to %s", state2Desc, state1Desc);
  5312. #ifndef MPEXT_NO_GSS
  5313. else if (iter->pLayer == m_pGssLayer)
  5314. LogMessage(FZ_LOG_INFO, L"m_pGssLayer changed state from %s to %s", state2Desc, state1Desc);
  5315. #endif
  5316. else if (iter->pLayer == m_pSslLayer)
  5317. {
  5318. delete [] iter->str;
  5319. LogMessage(FZ_LOG_INFO, L"TLS layer changed state from %s to %s", state2Desc, state1Desc);
  5320. }
  5321. else
  5322. LogMessage(FZ_LOG_INFO, L"Layer @ %d changed state from %s to %s", iter->pLayer, state2Desc, state1Desc);
  5323. }
  5324. }
  5325. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  5326. {
  5327. USES_CONVERSION;
  5328. if (iter->pLayer == m_pProxyLayer)
  5329. {
  5330. switch (iter->nParam1)
  5331. {
  5332. case PROXYERROR_NOERROR:
  5333. ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  5334. break;
  5335. case PROXYERROR_NOCONN:
  5336. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  5337. break;
  5338. case PROXYERROR_REQUESTFAILED:
  5339. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  5340. if (iter->str)
  5341. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  5342. break;
  5343. case PROXYERROR_AUTHTYPEUNKNOWN:
  5344. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  5345. break;
  5346. case PROXYERROR_AUTHFAILED:
  5347. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  5348. break;
  5349. case PROXYERROR_AUTHNOLOGON:
  5350. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  5351. break;
  5352. case PROXYERROR_CANTRESOLVEHOST:
  5353. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  5354. break;
  5355. default:
  5356. LogMessage(FZ_LOG_WARNING, L"Unknown proxy error" );
  5357. }
  5358. }
  5359. #ifndef MPEXT_NO_GSS
  5360. else if (iter->pLayer == m_pGssLayer)
  5361. {
  5362. switch (iter->nParam1)
  5363. {
  5364. case GSS_INFO:
  5365. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  5366. break;
  5367. case GSS_ERROR:
  5368. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  5369. break;
  5370. case GSS_COMMAND:
  5371. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  5372. break;
  5373. case GSS_REPLY:
  5374. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  5375. break;
  5376. }
  5377. }
  5378. #endif
  5379. else if (iter->pLayer == m_pSslLayer)
  5380. {
  5381. USES_CONVERSION;
  5382. switch (iter->nParam1)
  5383. {
  5384. case SSL_INFO:
  5385. switch (iter->nParam2)
  5386. {
  5387. case SSL_INFO_ESTABLISHED:
  5388. ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, FZ_LOG_STATUS);
  5389. if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  5390. {
  5391. LogOnToServer();
  5392. }
  5393. break;
  5394. }
  5395. break;
  5396. case SSL_FAILURE:
  5397. switch (iter->nParam2)
  5398. {
  5399. case SSL_FAILURE_UNKNOWN:
  5400. ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, FZ_LOG_ERROR);
  5401. break;
  5402. case SSL_FAILURE_ESTABLISH:
  5403. ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  5404. break;
  5405. case SSL_FAILURE_INITSSL:
  5406. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  5407. break;
  5408. case SSL_FAILURE_VERIFYCERT:
  5409. ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, FZ_LOG_ERROR);
  5410. break;
  5411. case SSL_FAILURE_CERTREJECTED:
  5412. ShowStatus(IDS_ERRORMSG_CERTREJECTED, FZ_LOG_ERROR);
  5413. m_bDidRejectCertificate = TRUE;
  5414. break;
  5415. }
  5416. TriggerEvent(FD_CLOSE);
  5417. break;
  5418. case SSL_VERIFY_CERT:
  5419. t_SslCertData *pData = new t_SslCertData;
  5420. LPTSTR CertError = NULL;
  5421. if (m_pSslLayer->GetPeerCertificateData(*pData, CertError))
  5422. {
  5423. CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
  5424. pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  5425. pRequestData->pCertData = pData;
  5426. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
  5427. {
  5428. delete pRequestData->pCertData;
  5429. delete pRequestData;
  5430. ResetOperation(FZ_REPLY_ERROR);
  5431. }
  5432. else
  5433. {
  5434. m_bCheckForTimeout = FALSE;
  5435. }
  5436. delete [] iter->str;
  5437. continue;
  5438. }
  5439. else
  5440. {
  5441. delete pData;
  5442. delete [] iter->str;
  5443. CString str;
  5444. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  5445. ShowStatus(str, FZ_LOG_ERROR);
  5446. ResetOperation(FZ_REPLY_ERROR);
  5447. continue;
  5448. }
  5449. break;
  5450. }
  5451. delete [] iter->str;
  5452. continue;
  5453. }
  5454. #ifndef MPEXT_NO_GSS
  5455. else
  5456. if (iter->pLayer == m_pGssLayer)
  5457. {
  5458. if (iter->nParam1 == GSS_AUTHCOMPLETE ||
  5459. iter->nParam1 == GSS_AUTHFAILED)
  5460. {
  5461. LogOnToServer(TRUE);
  5462. delete [] iter->str;
  5463. continue;
  5464. }
  5465. }
  5466. #endif
  5467. }
  5468. delete [] iter->str;
  5469. }
  5470. return 0;
  5471. }
  5472. _int64 CFtpControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  5473. {
  5474. int type = GetOptionVal(valType);
  5475. if ( type == 1)
  5476. return ( _int64)GetOptionVal(valValue) * 1024;
  5477. return ( _int64)1000000000000; // I hope that when there will be something with 1000GB/s then I'll change it :)
  5478. }
  5479. _int64 CFtpControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  5480. {
  5481. if (direction == download)
  5482. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  5483. else
  5484. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  5485. return ( _int64)1000000000000;
  5486. }
  5487. _int64 CFtpControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CFtpControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  5488. {
  5489. beenWaiting = false;
  5490. CTime nowTime = CTime::GetCurrentTime();
  5491. _int64 ableToRead = BUFSIZE;
  5492. if ( nowTime == curTime)
  5493. {
  5494. ableToRead = iter->nBytesAvailable;
  5495. if (ableToRead <= 0)
  5496. {
  5497. // we should wait till next second
  5498. nowTime = CTime::GetCurrentTime();
  5499. while (nowTime == curTime && !iter->nBytesAvailable)
  5500. {
  5501. if (beenWaiting)
  5502. {
  5503. //Check if there are other commands in the command queue.
  5504. MSG msg;
  5505. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  5506. {
  5507. LogMessage(FZ_LOG_INFO, L"Message waiting in queue, resuming later");
  5508. return 0;
  5509. }
  5510. }
  5511. m_SpeedLimitSync.Unlock();
  5512. Sleep(100);
  5513. m_SpeedLimitSync.Lock();
  5514. nowTime = CTime::GetCurrentTime();
  5515. beenWaiting = true;
  5516. // Since we didn't hold the critical section for some time, we have to renew the iterator
  5517. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5518. if (iter->pOwner == this)
  5519. break;
  5520. if (iter == m_InstanceList[direction].end())
  5521. return 0;
  5522. }
  5523. }
  5524. ableToRead = iter->nBytesAvailable;
  5525. }
  5526. if (nowTime != curTime)
  5527. {
  5528. if (ableToRead > 0)
  5529. ableToRead = 0;
  5530. curLimit = GetSpeedLimit(direction, curTime);
  5531. __int64 nMax = curLimit / m_InstanceList[direction].size();
  5532. _int64 nLeft = 0;
  5533. int nCount = 0;
  5534. std::list<t_ActiveList>::iterator iter2;
  5535. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5536. {
  5537. if (iter2->nBytesAvailable>0)
  5538. {
  5539. nLeft += iter2->nBytesAvailable;
  5540. iter2->nBytesTransferred = 1;
  5541. }
  5542. else
  5543. {
  5544. nCount++;
  5545. iter2->nBytesTransferred = 0;
  5546. }
  5547. iter2->nBytesAvailable = nMax;
  5548. }
  5549. if (nLeft && nCount)
  5550. {
  5551. nMax = nLeft / nCount;
  5552. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5553. {
  5554. if (!iter2->nBytesTransferred)
  5555. iter2->nBytesAvailable += nMax;
  5556. else
  5557. iter2->nBytesTransferred = 0;
  5558. }
  5559. }
  5560. ableToRead = iter->nBytesAvailable;
  5561. }
  5562. curTime = nowTime;
  5563. if (!nBufSize)
  5564. nBufSize = BUFSIZE;
  5565. if (ableToRead > nBufSize)
  5566. ableToRead = nBufSize;
  5567. return ableToRead;
  5568. }
  5569. _int64 CFtpControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  5570. {
  5571. m_SpeedLimitSync.Lock();
  5572. std::list<t_ActiveList>::iterator iter;
  5573. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5574. if (iter->pOwner == this)
  5575. break;
  5576. if (iter == m_InstanceList[direction].end())
  5577. {
  5578. t_ActiveList item;
  5579. CTime time = CTime::GetCurrentTime();
  5580. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  5581. item.nBytesTransferred = 0;
  5582. item.pOwner = this;
  5583. m_InstanceList[direction].push_back(item);
  5584. iter = m_InstanceList[direction].end();
  5585. iter--;
  5586. }
  5587. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  5588. m_SpeedLimitSync.Unlock();
  5589. return limit;
  5590. }
  5591. BOOL CFtpControlSocket::RemoveActiveTransfer()
  5592. {
  5593. BOOL bFound = FALSE;
  5594. m_SpeedLimitSync.Lock();
  5595. std::list<t_ActiveList>::iterator iter;
  5596. for (int i = 0; i < 2; i++)
  5597. {
  5598. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  5599. if (iter->pOwner == this)
  5600. {
  5601. m_InstanceList[i].erase(iter);
  5602. bFound = TRUE;
  5603. break;
  5604. }
  5605. }
  5606. m_SpeedLimitSync.Unlock();
  5607. return bFound;
  5608. }
  5609. BOOL CFtpControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  5610. {
  5611. m_SpeedLimitSync.Lock();
  5612. std::list<t_ActiveList>::iterator iter;
  5613. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5614. if (iter->pOwner == this)
  5615. {
  5616. if (iter->nBytesAvailable > nBytesTransferred)
  5617. iter->nBytesAvailable -= nBytesTransferred;
  5618. else
  5619. iter->nBytesAvailable = 0;
  5620. iter->nBytesTransferred += nBytesTransferred;
  5621. m_SpeedLimitSync.Unlock();
  5622. return TRUE;
  5623. }
  5624. m_SpeedLimitSync.Unlock();
  5625. return FALSE;
  5626. }
  5627. CString CFtpControlSocket::ConvertDomainName(CString domain)
  5628. {
  5629. USES_CONVERSION;
  5630. LPCWSTR buffer = T2CW(domain);
  5631. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  5632. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  5633. {
  5634. delete [] utf8;
  5635. LogMessage(FZ_LOG_WARNING, L"Could not convert domain name");
  5636. return domain;
  5637. }
  5638. char *output = 0;
  5639. output = strdup(utf8);
  5640. delete [] utf8;
  5641. CString result = A2T(output);
  5642. free(output);
  5643. return result;
  5644. }
  5645. void CFtpControlSocket::LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg)
  5646. {
  5647. LogMessageRaw(nMessageType, pMsg);
  5648. }
  5649. bool CFtpControlSocket::LoggingSocketMessage(int nMessageType)
  5650. {
  5651. return LoggingMessageType(nMessageType);
  5652. }
  5653. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
  5654. {
  5655. CServerPath realPath;
  5656. BOOL Result = ParsePwdReply(rawpwd, realPath);
  5657. if (Result)
  5658. {
  5659. m_pOwner->SetCurrentPath(realPath);
  5660. }
  5661. return Result;
  5662. }
  5663. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd, CServerPath & realPath)
  5664. {
  5665. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  5666. DebugAssert(pData);
  5667. int pos1 = rawpwd.Find(L'"');
  5668. int pos2 = rawpwd.ReverseFind(L'"');
  5669. if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
  5670. {
  5671. LogMessage(FZ_LOG_WARNING, L"No quoted path found, try using first token as path");
  5672. pos1 = rawpwd.Find(L' ');
  5673. if (pos1 != -1)
  5674. {
  5675. pos2 = rawpwd.Find(L' ', pos1 + 1);
  5676. if (pos2 == -1)
  5677. pos2 = rawpwd.GetLength();
  5678. }
  5679. if (pos1 == -1)
  5680. {
  5681. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5682. ResetOperation(FZ_REPLY_ERROR);
  5683. return FALSE;
  5684. }
  5685. }
  5686. rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
  5687. realPath = m_pOwner->GetCurrentPath();
  5688. realPath.SetServer(m_CurrentServer);
  5689. if (!realPath.SetPath(rawpwd))
  5690. {
  5691. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5692. ResetOperation(FZ_REPLY_ERROR);
  5693. return FALSE;
  5694. }
  5695. return TRUE;
  5696. }
  5697. void CFtpControlSocket::DiscardLine(CStringA line)
  5698. {
  5699. if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
  5700. {
  5701. line.MakeUpper();
  5702. while (line.Left(1) == " ")
  5703. {
  5704. line = line.Mid(1, line.GetLength() - 1);
  5705. }
  5706. #ifndef MPEXT_NO_ZLIB
  5707. if (line == "MODE Z" || line.Left(7) == "MODE Z ")
  5708. m_zlibSupported = true;
  5709. else
  5710. #endif
  5711. if (line == "UTF8" && m_CurrentServer.nUTF8 != 2)
  5712. m_bAnnouncesUTF8 = true;
  5713. else if (line == "CLNT" || line.Left(5) == "CLNT ")
  5714. m_hasClntCmd = true;
  5715. else if (line == "MLSD")
  5716. {
  5717. m_serverCapabilities.SetCapability(mlsd_command, yes);
  5718. }
  5719. else if (line == "MDTM")
  5720. {
  5721. m_serverCapabilities.SetCapability(mdtm_command, yes);
  5722. }
  5723. else if (line == "SIZE")
  5724. {
  5725. m_serverCapabilities.SetCapability(size_command, yes);
  5726. }
  5727. else if (line.Left(4) == "MLST")
  5728. {
  5729. USES_CONVERSION;
  5730. std::string facts;
  5731. if (line.GetLength() > 5)
  5732. {
  5733. facts = (LPCSTR)line.Mid(5, line.GetLength() - 5);
  5734. }
  5735. m_serverCapabilities.SetCapability(mlsd_command, yes, facts);
  5736. }
  5737. else if (line == "MFMT")
  5738. {
  5739. m_serverCapabilities.SetCapability(mfmt_command, yes);
  5740. }
  5741. }
  5742. else if (m_Operation.nOpMode == CSMODE_LISTFILE)
  5743. {
  5744. m_ListFile = line;
  5745. }
  5746. }
  5747. int CFtpControlSocket::FileTransferListState(bool get)
  5748. {
  5749. int Result;
  5750. if (GetOptionVal(OPTION_MPEXT_NOLIST) && !get)
  5751. {
  5752. Result = FILETRANSFER_TYPE;
  5753. }
  5754. else
  5755. {
  5756. Result = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  5757. }
  5758. return Result;
  5759. }
  5760. bool CFtpControlSocket::NeedModeCommand()
  5761. {
  5762. #ifdef MPEXT_NO_ZLIB
  5763. return false;
  5764. #else
  5765. bool useZlib;
  5766. if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
  5767. useZlib = GetOptionVal(OPTION_MODEZ_USE) != 0;
  5768. else
  5769. useZlib = GetOptionVal(OPTION_MODEZ_USE) > 1;
  5770. if (!m_useZlib && !m_zlibSupported)
  5771. return false;
  5772. return m_useZlib != useZlib;
  5773. #endif
  5774. }
  5775. bool CFtpControlSocket::NeedOptsCommand()
  5776. {
  5777. #ifndef MPEXT_NO_ZLIB
  5778. if (!m_useZlib)
  5779. #endif
  5780. return false;
  5781. #ifndef MPEXT_NO_ZLIB
  5782. return m_zlibLevel != GetOptionVal(OPTION_MODEZ_LEVEL);
  5783. #endif
  5784. }
  5785. CString CFtpControlSocket::GetReply()
  5786. {
  5787. if (m_RecvBuffer.empty())
  5788. return L"";
  5789. USES_CONVERSION;
  5790. LPCSTR line;
  5791. if ((m_Operation.nOpMode&CSMODE_LISTFILE) && (m_Operation.nOpState==LISTFILE_MLST) &&
  5792. (GetReplyCode() == 2))
  5793. {
  5794. // this is probably never used anyway
  5795. line = (LPCSTR)m_ListFile;
  5796. }
  5797. else
  5798. {
  5799. line = (LPCSTR)m_RecvBuffer.front();
  5800. }
  5801. if (m_bUTF8)
  5802. {
  5803. // convert from UTF-8 to ANSI
  5804. if (DetectUTF8Encoding(RawByteString(line)) == etANSI)
  5805. {
  5806. if (m_CurrentServer.nUTF8 != 1)
  5807. {
  5808. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  5809. m_bUTF8 = false;
  5810. }
  5811. return A2CT(line);
  5812. }
  5813. // convert from UTF-8 to ANSI
  5814. int len = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
  5815. if (!len)
  5816. {
  5817. m_RecvBuffer.pop_front();
  5818. if (m_RecvBuffer.empty())
  5819. m_RecvBuffer.push_back("");
  5820. return L"";
  5821. }
  5822. else
  5823. {
  5824. LPWSTR p1 = new WCHAR[len + 1];
  5825. MultiByteToWideChar(CP_UTF8, 0, line, -1 , (LPWSTR)p1, len + 1);
  5826. CString reply = W2CT(p1);
  5827. delete [] p1;
  5828. return reply;
  5829. }
  5830. }
  5831. else
  5832. return A2CT(line);
  5833. }
  5834. void CFtpControlSocket::OnSend(int nErrorCode)
  5835. {
  5836. if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
  5837. return;
  5838. int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
  5839. if (res == -1)
  5840. {
  5841. if (GetLastError() != WSAEWOULDBLOCK)
  5842. {
  5843. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5844. DoClose();
  5845. }
  5846. return;
  5847. }
  5848. if (!res)
  5849. {
  5850. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5851. DoClose();
  5852. }
  5853. m_awaitsReply = true;
  5854. m_LastSendTime = CTime::GetCurrentTime();
  5855. if (res == m_sendBufferLen)
  5856. {
  5857. delete [] m_sendBuffer;
  5858. m_sendBuffer = 0;
  5859. m_sendBufferLen = 0;
  5860. }
  5861. else
  5862. {
  5863. char* tmp = new char[m_sendBufferLen - res];
  5864. memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
  5865. delete [] m_sendBuffer;
  5866. m_sendBuffer = tmp;
  5867. m_sendBufferLen -= res;
  5868. }
  5869. }
  5870. bool CFtpControlSocket::IsMisleadingListResponse()
  5871. {
  5872. // Some servers are broken. Instead of an empty listing, some MVS servers
  5873. // for example they return something "550 no members found"
  5874. // Other servers return "550 No files found."
  5875. CString retmsg = GetReply();
  5876. if (!retmsg.CompareNoCase(L"550 No members found."))
  5877. return true;
  5878. if (!retmsg.CompareNoCase(L"550 No data sets found."))
  5879. return true;
  5880. if (!retmsg.CompareNoCase(L"550 No files found."))
  5881. return true;
  5882. return false;
  5883. }
  5884. bool CFtpControlSocket::IsRoutableAddress(const CString & host)
  5885. {
  5886. USES_CONVERSION;
  5887. if (host.Left(3) == L"127" ||
  5888. host.Left(3) == L"10." ||
  5889. host.Left(7) == L"192.168" ||
  5890. host.Left(7) == L"169.254")
  5891. {
  5892. return false;
  5893. }
  5894. else if (host.Left(3) == L"172")
  5895. {
  5896. CString middle = host.Mid(4);
  5897. int pos = middle.Find(L".");
  5898. long part = atol(T2CA(middle.Left(pos)));
  5899. if ((part >= 16) && (part <= 31))
  5900. {
  5901. return false;
  5902. }
  5903. }
  5904. return true;
  5905. }
  5906. bool CFtpControlSocket::CheckForcePasvIp(CString & host)
  5907. {
  5908. bool result = true;
  5909. unsigned int tmpPort;
  5910. CString ahost;
  5911. switch (m_CurrentServer.iForcePasvIp)
  5912. {
  5913. case 0: // on
  5914. if (!GetPeerName(ahost, tmpPort))
  5915. {
  5916. // this should happen with proxy server only
  5917. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  5918. // do not know what to do, if there's FTP proxy
  5919. if (!logontype)
  5920. {
  5921. // this is a host name, not an IP, but it should not be a problem
  5922. ahost = m_CurrentServer.host;
  5923. }
  5924. }
  5925. if (ahost != host)
  5926. {
  5927. LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", ahost, host);
  5928. host = ahost;
  5929. }
  5930. break;
  5931. case 1: // off
  5932. // noop
  5933. break;
  5934. default: // auto
  5935. if (!GetPeerName(ahost, tmpPort))
  5936. {
  5937. LogMessage(FZ_LOG_PROGRESS, L"Error retrieving server address, cannot test if address is routable");
  5938. }
  5939. else if (!IsRoutableAddress(host) && IsRoutableAddress(ahost))
  5940. {
  5941. LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", host, ahost);
  5942. host = ahost;
  5943. }
  5944. break;
  5945. }
  5946. return result;
  5947. }
  5948. //---------------------------------------------------------------------------
  5949. ftp_capabilities_t TFTPServerCapabilities::GetCapability(ftp_capability_names_t Name)
  5950. {
  5951. t_cap tcap = FCapabilityMap[Name];
  5952. return tcap.cap;
  5953. }
  5954. ftp_capabilities_t TFTPServerCapabilities::GetCapabilityString(ftp_capability_names_t Name, std::string * Option)
  5955. {
  5956. t_cap tcap = FCapabilityMap[Name];
  5957. if (Option)
  5958. *Option = tcap.option;
  5959. return tcap.cap;
  5960. }
  5961. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap)
  5962. {
  5963. t_cap tcap = FCapabilityMap[Name];
  5964. tcap.cap = Cap;
  5965. tcap.number = 1;
  5966. FCapabilityMap[Name] = tcap;
  5967. }
  5968. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap, const std::string & Option)
  5969. {
  5970. t_cap tcap = FCapabilityMap[Name];
  5971. tcap.cap = Cap;
  5972. tcap.option = Option;
  5973. tcap.number = 0;
  5974. FCapabilityMap[Name] = tcap;
  5975. }