FtpControlSocket.cpp 182 KB

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