FtpControlSocket.cpp 182 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377
  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. m_pTools);
  452. if (res == SSL_FAILURE_INITSSL)
  453. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  454. if (res)
  455. {
  456. DoClose();
  457. return;
  458. }
  459. }
  460. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  461. int port;
  462. CString buf,temp;
  463. // are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0)
  464. CString fwhost;
  465. int fwport;
  466. if(!logontype)
  467. {
  468. temp=server.host;
  469. port=server.port;
  470. }
  471. else
  472. {
  473. fwhost=GetOption(OPTION_FWHOST);
  474. fwport=GetOptionVal(OPTION_FWPORT);
  475. temp=fwhost;
  476. port=fwport;
  477. if(fwport!=21)
  478. fwhost.Format( L"%s:%d", fwhost, fwport); // add port to fwhost (only if port is not 21)
  479. }
  480. CString hostname = server.host;
  481. if(server.port!=21)
  482. hostname.Format( L"%s:%d", hostname, server.port); // add port to hostname (only if port is not 21)
  483. CString str;
  484. str.Format(IDS_STATUSMSG_CONNECTING, hostname);
  485. ShowStatus(str, FZ_LOG_STATUS);
  486. if (!Connect(temp, port))
  487. {
  488. if (WSAGetLastError() != WSAEWOULDBLOCK)
  489. {
  490. DoClose();
  491. return;
  492. }
  493. }
  494. m_ServerName = logontype?fwhost:hostname;
  495. m_LastRecvTime = m_LastSendTime = CTime::GetCurrentTime();
  496. m_Operation.pData = new CLogonData();
  497. }
  498. static CString NormalizePass(const CString & pass)
  499. {
  500. return CString(NormalizeString(UnicodeString(T2CW(pass))).c_str());
  501. }
  502. void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/)
  503. {
  504. int logontype =
  505. #ifndef MPEXT_NO_GSS
  506. m_pGssLayer ? 0 :
  507. #endif
  508. GetOptionVal(OPTION_LOGONTYPE);
  509. const int LO = -2, ER = -1;
  510. CString buf, temp;
  511. const int NUMLOGIN = 9; // currently supports 9 different login sequences
  512. int logonseq[NUMLOGIN][20] = {
  513. // this array stores all of the logon sequences for the various firewalls
  514. // in blocks of 3 nums. 1st num is command to send, 2nd num is next point in logon sequence array
  515. // if 200 series response is rec'd from server as the result of the command, 3rd num is next
  516. // point in logon sequence if 300 series rec'd
  517. {0,LO,3, 1,LO,6, 12,LO,ER}, // no firewall
  518. {3,6,3, 4,6,ER, 5,9,9, 0,LO,12, 1,LO,15, 12,LO,ER}, // SITE hostname
  519. {3,6,3, 4,6,ER, 6,LO,9, 1,LO,12, 12,LO,ER}, // USER after logon
  520. {7,3,3, 0,LO,6, 1,LO,9, 12,LO,ER}, //proxy OPEN
  521. {3,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, // Transparent
  522. {6,LO,3, 1,LO,6, 12,LO,ER}, // USER remoteID@remotehost
  523. {8,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, //USER fireID@remotehost
  524. {9,ER,3, 1,LO,6, 2,LO,ER}, //USER remoteID@remotehost fireID
  525. {10,LO,3,11,LO,6,2,LO,ER} // USER remoteID@fireID@remotehost
  526. };
  527. if (m_Operation.nOpState == CONNECT_SSL_INIT)
  528. {
  529. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT)
  530. {
  531. if (!SendAuthSsl())
  532. {
  533. return;
  534. }
  535. }
  536. else
  537. {
  538. if (!Send("AUTH TLS"))
  539. return;
  540. m_Operation.nOpState = CONNECT_TLS_NEGOTIATE;
  541. }
  542. return;
  543. }
  544. else if ((m_Operation.nOpState == CONNECT_SSL_NEGOTIATE) ||
  545. (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE))
  546. {
  547. int res = GetReplyCode();
  548. if (res!=2 && res!=3)
  549. {
  550. if (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE)
  551. {
  552. // Try to fall back to AUTH SSL
  553. if (!SendAuthSsl())
  554. {
  555. return;
  556. }
  557. }
  558. else
  559. {
  560. DoClose();
  561. }
  562. return;
  563. }
  564. else
  565. {
  566. if (!m_pSslLayer)
  567. {
  568. ShowStatus(L"Internal error: m_pSslLayer not initialized", FZ_LOG_ERROR);
  569. DoClose(FZ_REPLY_CRITICALERROR);
  570. return;
  571. }
  572. int res = m_pSslLayer->InitSSLConnection(true, NULL,
  573. GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  574. m_pTools);
  575. if (res == SSL_FAILURE_INITSSL)
  576. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  577. if (res)
  578. {
  579. DoClose();
  580. return;
  581. }
  582. }
  583. m_Operation.nOpState = CONNECT_SSL_WAITDONE;
  584. return;
  585. }
  586. else if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  587. {
  588. m_Operation.nOpState = CONNECT_INIT;
  589. }
  590. else if (m_Operation.nOpState == CONNECT_SSL_PBSZ)
  591. {
  592. if (!Send(L"PROT P"))
  593. return;
  594. m_Operation.nOpState = CONNECT_SSL_PROT;
  595. return;
  596. }
  597. else if (m_Operation.nOpState == CONNECT_SSL_PROT)
  598. {
  599. int code = GetReplyCode();
  600. if (code == 2 || code == 3)
  601. m_bProtP = true;
  602. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  603. m_pOwner->SetConnected(TRUE);
  604. ResetOperation(FZ_REPLY_OK);
  605. return;
  606. }
  607. #ifndef MPEXT_NO_GSS
  608. else
  609. if (m_Operation.nOpState==CONNECT_GSS_FAILED ||
  610. m_Operation.nOpState == CONNECT_GSS_NEEDPASS ||
  611. m_Operation.nOpState == CONNECT_GSS_NEEDUSER)
  612. {
  613. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  614. {
  615. //Incoming reply from server during async is not allowed
  616. DoClose();
  617. return;
  618. }
  619. }
  620. #endif
  621. else if (m_Operation.nOpState == CONNECT_HOST)
  622. {
  623. if (Send(L"HOST " + m_CurrentServer.host))
  624. {
  625. m_Operation.nOpState = InitConnectState();
  626. return;
  627. }
  628. }
  629. else if (m_Operation.nOpState == CONNECT_OPTSMLST)
  630. {
  631. int code = GetReplyCode();
  632. if (code != 2 && code != 3)
  633. m_serverCapabilities.SetCapability(mlsd_command, no);
  634. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  635. m_pOwner->SetConnected(TRUE);
  636. ResetOperation(FZ_REPLY_OK);
  637. return;
  638. }
  639. else if (m_Operation.nOpState == CONNECT_FEAT)
  640. {
  641. std::string facts;
  642. if (m_serverCapabilities.GetCapabilityString(mlsd_command, &facts) == yes)
  643. {
  644. ftp_capabilities_t cap = m_serverCapabilities.GetCapabilityString(opts_mlst_command);
  645. if (cap == unknown)
  646. {
  647. std::transform(facts.begin(), facts.end(), facts.begin(), ::tolower);
  648. bool had_unset = false;
  649. std::string opts_facts;
  650. // Create a list of all facts understood by both FZ and the server.
  651. // Check if there's any supported fact not enabled by default, should that
  652. // be the case we need to send OPTS MLST
  653. while (!facts.empty())
  654. {
  655. size_t delim = facts.find_first_of(';');
  656. if (delim == -1)
  657. break;
  658. if (!delim)
  659. {
  660. facts = facts.substr(1, std::string::npos);
  661. continue;
  662. }
  663. bool enabled = false;
  664. std::string fact;
  665. if (facts[delim - 1] == '*')
  666. {
  667. if (delim == 1)
  668. {
  669. facts = facts.substr(delim + 1, std::string::npos);
  670. continue;
  671. }
  672. enabled = true;
  673. fact = facts.substr(0, delim - 1);
  674. }
  675. else
  676. {
  677. enabled = false;
  678. fact = facts.substr(0, delim);
  679. }
  680. facts = facts.substr(delim + 1, std::string::npos);
  681. if (!strcmp(fact.c_str(), "type") ||
  682. !strcmp(fact.c_str(), "size") ||
  683. !strcmp(fact.c_str(), "modify") ||
  684. !strcmp(fact.c_str(), "create") ||
  685. !strcmp(fact.c_str(), "perm") ||
  686. !strcmp(fact.c_str(), "unix.mode") ||
  687. !strcmp(fact.c_str(), "unix.owner") ||
  688. !strcmp(fact.c_str(), "unix.user") ||
  689. !strcmp(fact.c_str(), "unix.group") ||
  690. !strcmp(fact.c_str(), "unix.uid") ||
  691. !strcmp(fact.c_str(), "unix.gid"))
  692. {
  693. had_unset |= !enabled;
  694. opts_facts += fact.c_str();
  695. opts_facts += ";";
  696. }
  697. }
  698. if (had_unset)
  699. {
  700. m_serverCapabilities.SetCapability(opts_mlst_command, yes, opts_facts);
  701. }
  702. else
  703. {
  704. m_serverCapabilities.SetCapability(opts_mlst_command, no);
  705. }
  706. }
  707. }
  708. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_CAPABILITIES, 0), (LPARAM)&m_serverCapabilities);
  709. if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8)
  710. m_bUTF8 = false;
  711. if (m_hasClntCmd)
  712. {
  713. // Some servers refuse to enable UTF8 if client does not send CLNT command
  714. // to fix compatibility with Internet Explorer, but in the process breaking
  715. // compatibility with other clients.
  716. // Rather than forcing MS to fix Internet Explorer, letting other clients
  717. // suffer is a questionable decision in my opinion.
  718. if (Send(CString(L"CLNT ") + m_pTools->GetClientString().c_str()))
  719. m_Operation.nOpState = CONNECT_CLNT;
  720. return;
  721. }
  722. if (m_bUTF8 && !m_isFileZilla)
  723. {
  724. // Handle servers that disobey RFC 2640 that have UTF8 in the FEAT
  725. // response but do not use UTF8 unless OPTS UTF8 ON gets send.
  726. // However these servers obey a conflicting ietf draft:
  727. // https://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
  728. // servers are, amongst others, G6 FTP Server and RaidenFTPd.
  729. if (Send(L"OPTS UTF8 ON"))
  730. m_Operation.nOpState = CONNECT_OPTSUTF8;
  731. return;
  732. }
  733. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  734. {
  735. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  736. Send(L"PBSZ 0");
  737. return;
  738. }
  739. if (m_serverCapabilities.GetCapability(mlsd_command) == yes)
  740. {
  741. std::string args;
  742. // this is never true, see comment is DiscardLine
  743. if (m_serverCapabilities.GetCapabilityString(opts_mlst_command, &args) == yes &&
  744. !args.empty())
  745. {
  746. m_Operation.nOpState = CONNECT_OPTSMLST;
  747. Send("OPTS MLST " + CString(args.c_str()));
  748. return;
  749. }
  750. }
  751. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  752. m_pOwner->SetConnected(TRUE);
  753. ResetOperation(FZ_REPLY_OK);
  754. return;
  755. }
  756. else if (m_Operation.nOpState == CONNECT_CLNT)
  757. {
  758. // See above why we send this command
  759. if (Send(L"OPTS UTF8 ON"))
  760. m_Operation.nOpState = CONNECT_OPTSUTF8;
  761. return;
  762. }
  763. else if (m_Operation.nOpState == CONNECT_OPTSUTF8)
  764. {
  765. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  766. {
  767. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  768. Send(L"PBSZ 0");
  769. return;
  770. }
  771. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  772. m_pOwner->SetConnected(TRUE);
  773. ResetOperation(FZ_REPLY_OK);
  774. return;
  775. }
  776. else if (m_Operation.nOpState == CONNECT_SYST)
  777. {
  778. if (GetReplyCode() == 2)
  779. {
  780. const CStringA reply = m_RecvBuffer.front();
  781. if (reply.GetLength() > 7 && reply.Mid(3, 4) == " MVS")
  782. m_mayBeMvsFilesystem = true;
  783. else if (reply.GetLength() >= 11 && reply.Mid(3, 8) == " BS-2000")
  784. m_mayBeBS2000Filesystem = true;
  785. if (reply.Find("FileZilla") != -1)
  786. m_isFileZilla = true;
  787. }
  788. if (Send(L"FEAT"))
  789. m_Operation.nOpState = CONNECT_FEAT;
  790. return;
  791. }
  792. else if (!bSkipReply)
  793. {
  794. int res = GetReplyCode();
  795. if (res != 2 && res != 3 && m_Operation.nOpState >= 0) // get initial connect msg off server
  796. {
  797. int nError = 0;
  798. if (m_bUTF8 && m_CurrentServer.nUTF8 != 1)
  799. {
  800. // Fall back to local charset for the case that the server might not
  801. // support UTF8 and the login data contains non-ascii characters.
  802. bool asciiOnly = true;
  803. for (int i = 0; i < m_CurrentServer.user.GetLength(); i++)
  804. if (m_CurrentServer.user.GetAt(i) > 127)
  805. asciiOnly = false;
  806. CString pass = NormalizePass(m_CurrentServer.pass);
  807. for (int i = 0; i < pass.GetLength(); i++)
  808. if (pass.GetAt(i) > 127)
  809. asciiOnly = false;
  810. for (int i = 0; i < m_CurrentServer.account.GetLength(); i++)
  811. if (m_CurrentServer.account.GetAt(i) > 127)
  812. asciiOnly = false;
  813. if (!asciiOnly)
  814. {
  815. ShowStatus(L"Login data contains non-ascii characters and server might not be UTF-8 aware. Trying local charset.", FZ_LOG_STATUS);
  816. m_bUTF8 = false;
  817. m_Operation.nOpState = CONNECT_INIT;
  818. }
  819. else
  820. nError = FZ_REPLY_ERROR;
  821. }
  822. else
  823. nError = FZ_REPLY_ERROR;
  824. if (nError)
  825. {
  826. if (res==5 && logonseq[logontype][m_Operation.nOpState]==1)
  827. nError|=FZ_REPLY_CRITICALERROR;
  828. DoClose(nError);
  829. return;
  830. }
  831. }
  832. }
  833. CString hostname = m_CurrentServer.host;
  834. if (m_CurrentServer.port != 21)
  835. hostname.Format(hostname+ L":%d", m_CurrentServer.port); // add port to hostname (only if port is not 21)
  836. USES_CONVERSION;
  837. #ifndef MPEXT_NO_GSS
  838. //**** GSS Authentication ****
  839. if (m_Operation.nOpState==CONNECT_GSS_INIT) //authenticate
  840. {
  841. int i = m_pGssLayer->GetClientAuth(T2CA(m_CurrentServer.host));
  842. if (i==-1)
  843. m_Operation.nOpState = CONNECT_GSS_AUTHDONE;
  844. else if (i != GSSAPI_AUTHENTICATION_SUCCEEDED)
  845. {
  846. m_Operation.nOpState = CONNECT_GSS_FAILED;
  847. CAsyncRequestData *pData=new CAsyncRequestData;
  848. pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  849. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  850. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  851. {
  852. delete pData;
  853. }
  854. else
  855. {
  856. m_bCheckForTimeout = FALSE;
  857. }
  858. }
  859. else
  860. {
  861. // we got authentication, we need to check whether we have forwardable tickets
  862. if (Send(L"CWD ."))
  863. m_Operation.nOpState = CONNECT_GSS_CWD;
  864. }
  865. return;
  866. }
  867. else if (m_Operation.nOpState == CONNECT_GSS_AUTHDONE)
  868. {
  869. if (!m_pGssLayer->AuthSuccessful())
  870. {
  871. m_Operation.nOpState = CONNECT_GSS_FAILED;
  872. CAsyncRequestData *pData=new CAsyncRequestData;
  873. pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  874. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  875. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  876. {
  877. delete pData;
  878. }
  879. else
  880. {
  881. m_bCheckForTimeout = FALSE;
  882. }
  883. return;
  884. }
  885. else
  886. {
  887. // we got authentication, we need to check whether we have forwardable tickets
  888. if (Send(L"CWD ."))
  889. m_Operation.nOpState = CONNECT_GSS_CWD;
  890. return;
  891. }
  892. }
  893. else if (m_Operation.nOpState == CONNECT_GSS_CWD)
  894. { // authentication succeeded, we're now get the response to the CWD command
  895. if (GetReplyCode() == 2) // we're logged on
  896. {
  897. if (Send(L"SYST"))
  898. m_Operation.nOpState = CONNECT_SYST;
  899. return;
  900. }
  901. else
  902. {
  903. //GSS authentication complete but we still have to go through the standard logon procedure
  904. m_Operation.nOpState = CONNECT_INIT;
  905. }
  906. }
  907. #endif
  908. if (m_Operation.nOpState==CONNECT_INIT)
  909. {
  910. if (logontype)
  911. {
  912. CString str;
  913. str.Format(IDS_STATUSMSG_FWCONNECT,hostname);
  914. ShowStatus(str,FZ_LOG_STATUS);
  915. }
  916. m_Operation.nOpState++;
  917. }
  918. else if (m_Operation.nOpState >= 0 && !bSkipReply)
  919. {
  920. m_Operation.nOpState=logonseq[logontype][m_Operation.nOpState+GetReplyCode()-1]; //get next command from array
  921. switch(m_Operation.nOpState)
  922. {
  923. case ER: // ER means summat has gone wrong
  924. DoClose();
  925. return;
  926. case LO: //LO means we are logged on
  927. if (Send(L"SYST"))
  928. m_Operation.nOpState = CONNECT_SYST;
  929. return;
  930. }
  931. }
  932. // go through appropriate logon procedure
  933. #ifndef MPEXT_NO_GSS
  934. int i = logonseq[logontype][m_Operation.nOpState];
  935. if (m_pGssLayer)
  936. {
  937. if ((i == 0 || i == 6 || i == 9 || i == 10) &&
  938. (m_CurrentServer.user == L"anonymous" || m_CurrentServer.user == L""))
  939. {
  940. //Extract user from kerberos ticket
  941. char str[256];
  942. if (m_pGssLayer->GetUserFromKrbTicket(str))
  943. m_CurrentServer.user = str;
  944. if (m_CurrentServer.user == L"")
  945. {
  946. CGssNeedUserRequestData *pData = new CGssNeedUserRequestData;
  947. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  948. pData->nOldOpState = m_Operation.nOpState;
  949. m_Operation.nOpState = CONNECT_GSS_NEEDUSER;
  950. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData))
  951. {
  952. delete pData;
  953. }
  954. else
  955. {
  956. m_bCheckForTimeout = FALSE;
  957. }
  958. return;
  959. }
  960. }
  961. else if ((i == 1 || i == 11) && (m_CurrentServer.pass == GetOption(OPTION_ANONPWD) || m_CurrentServer.pass == ""))
  962. {
  963. CGssNeedPassRequestData *pData=new CGssNeedPassRequestData;
  964. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  965. pData->nOldOpState = m_Operation.nOpState;
  966. m_Operation.nOpState = CONNECT_GSS_NEEDPASS;
  967. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData))
  968. {
  969. delete pData;
  970. }
  971. else
  972. {
  973. m_bCheckForTimeout = FALSE;
  974. }
  975. return;
  976. }
  977. }
  978. #endif
  979. CLogonData *pData = static_cast<CLogonData *>(m_Operation.pData);
  980. bool needpass = (m_CurrentServer.pass == GetOption(OPTION_ANONPWD)) || (m_CurrentServer.pass == L"");
  981. switch(logonseq[logontype][m_Operation.nOpState])
  982. {
  983. case 0:
  984. temp=L"USER "+m_CurrentServer.user;
  985. break;
  986. case 1:
  987. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  988. {
  989. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  990. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  991. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  992. m_Operation.nOpState = CONNECT_NEEDPASS;
  993. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  994. {
  995. delete pNeedPassRequestData;
  996. ResetOperation(FZ_REPLY_ERROR);
  997. }
  998. else
  999. {
  1000. m_bCheckForTimeout = FALSE;
  1001. }
  1002. pData->waitForAsyncRequest = true;
  1003. return;
  1004. }
  1005. else if (!needpass || pData->gotPassword)
  1006. {
  1007. temp=L"PASS "+NormalizePass(m_CurrentServer.pass);
  1008. }
  1009. else
  1010. {
  1011. return;
  1012. }
  1013. break;
  1014. case 2:
  1015. temp=L"ACCT "+GetOption(OPTION_FWPASS);
  1016. break;
  1017. case 3:
  1018. temp=L"USER "+GetOption(OPTION_FWUSER);
  1019. break;
  1020. case 4:
  1021. temp=L"PASS "+GetOption(OPTION_FWPASS);
  1022. break;
  1023. case 5:
  1024. temp=L"SITE "+hostname;
  1025. break;
  1026. case 6:
  1027. temp=L"USER "+m_CurrentServer.user+L"@"+hostname;
  1028. break;
  1029. case 7:
  1030. temp=L"OPEN "+hostname;
  1031. break;
  1032. case 8:
  1033. temp=L"USER "+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1034. break;
  1035. case 9:
  1036. temp=L"USER "+m_CurrentServer.user+L"@"+hostname+L" "+GetOption(OPTION_FWUSER);
  1037. break;
  1038. case 10:
  1039. temp=L"USER "+m_CurrentServer.user+L"@"+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1040. break;
  1041. case 11:
  1042. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  1043. {
  1044. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  1045. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  1046. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  1047. m_Operation.nOpState = CONNECT_NEEDPASS;
  1048. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  1049. {
  1050. delete pNeedPassRequestData;
  1051. ResetOperation(FZ_REPLY_ERROR);
  1052. }
  1053. else
  1054. {
  1055. m_bCheckForTimeout = FALSE;
  1056. }
  1057. pData->waitForAsyncRequest = true;
  1058. return;
  1059. }
  1060. else if (!needpass || pData->gotPassword)
  1061. {
  1062. temp=L"PASS "+NormalizePass(m_CurrentServer.pass)+L"@"+GetOption(OPTION_FWPASS);
  1063. }
  1064. else
  1065. {
  1066. return;
  1067. }
  1068. break;
  1069. case 12:
  1070. if (m_CurrentServer.account == L"")
  1071. temp = L"ACCT default";
  1072. else
  1073. temp = L"ACCT " + m_CurrentServer.account;
  1074. break;
  1075. }
  1076. // send command, get response
  1077. if(!Send(temp))
  1078. return;
  1079. }
  1080. BOOL CFtpControlSocket::SendAuthSsl()
  1081. {
  1082. if (!Send("AUTH SSL"))
  1083. return false;
  1084. m_Operation.nOpState = CONNECT_SSL_NEGOTIATE;
  1085. return true;
  1086. }
  1087. #define BUFFERSIZE 4096
  1088. void CFtpControlSocket::OnReceive(int nErrorCode)
  1089. {
  1090. m_LastRecvTime = CTime::GetCurrentTime();
  1091. if (!m_pOwner->IsConnected())
  1092. {
  1093. if (!m_Operation.nOpMode)
  1094. {
  1095. LogMessage(FZ_LOG_INFO, L"Socket has been closed, don't process receive" );
  1096. return;
  1097. }
  1098. m_MultiLine = "";
  1099. CString str;
  1100. str.Format(IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
  1101. ShowStatus(str, FZ_LOG_PROGRESS);
  1102. m_pOwner->SetConnected(TRUE);
  1103. }
  1104. char *buffer = new char[BUFFERSIZE];
  1105. int numread = Receive(buffer, BUFFERSIZE);
  1106. if (numread == SOCKET_ERROR)
  1107. {
  1108. delete [] buffer;
  1109. buffer = NULL;
  1110. int Error = GetLastError();
  1111. if (Error != WSAEWOULDBLOCK)
  1112. {
  1113. LogError(Error);
  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. if (nError)
  2605. {
  2606. LogMessage(FZ_LOG_INFO, L"Destroying data socket on error");
  2607. }
  2608. else
  2609. {
  2610. LogMessage(FZ_LOG_INFO, L"Destroying data socket after transfer completed");
  2611. }
  2612. delete m_pTransferSocket;
  2613. m_pTransferSocket=0;
  2614. }
  2615. }
  2616. }
  2617. //////////////////
  2618. //Initialization//
  2619. //////////////////
  2620. int nReplyError = 0;
  2621. if (m_Operation.nOpState == FILETRANSFER_INIT)
  2622. {
  2623. DebugAssert(transferfile);
  2624. DebugAssert(!m_Operation.nOpMode);
  2625. DebugAssert(!m_Operation.pData);
  2626. CString str;
  2627. str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
  2628. transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
  2629. ShowStatus(str,FZ_LOG_STATUS);
  2630. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2631. m_Operation.pData=new CFileTransferData;
  2632. pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2633. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  2634. pData->bPasv = TRUE;
  2635. else if (m_CurrentServer.nPasv == 1)
  2636. pData->bPasv = TRUE;
  2637. else if (m_CurrentServer.nPasv == 2)
  2638. pData->bPasv = FALSE;
  2639. else
  2640. pData->bPasv = GetOptionVal(OPTION_PASV);
  2641. //Replace invalid characters in the local filename
  2642. int pos=transferfile->localfile.ReverseFind(L'\\');
  2643. for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
  2644. if (transferfile->localfile[i]==L':')
  2645. transferfile->localfile.SetAt(i, L'_');
  2646. pData->transferfile=*transferfile;
  2647. pData->transferdata.transfersize=pData->transferfile.size;
  2648. pData->transferdata.transferleft=pData->transferfile.size;
  2649. pData->transferdata.bResume = FALSE;
  2650. pData->transferdata.bResumeAppend = FALSE;
  2651. pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
  2652. CServerPath path;
  2653. DebugCheck(m_pOwner->GetCurrentPath(path));
  2654. if (path == pData->transferfile.remotepath)
  2655. {
  2656. if (m_pDirectoryListing)
  2657. {
  2658. m_Operation.nOpState=FILETRANSFER_TYPE;
  2659. CString remotefile=pData->transferfile.remotefile;
  2660. int i;
  2661. for (i=0; i<m_pDirectoryListing->num; i++)
  2662. {
  2663. if (m_pDirectoryListing->direntry[i].name==remotefile &&
  2664. ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
  2665. {
  2666. delete m_pDirectoryListing;
  2667. m_pDirectoryListing=0;
  2668. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2669. break;
  2670. }
  2671. }
  2672. if (m_pDirectoryListing && i==m_pDirectoryListing->num)
  2673. {
  2674. nReplyError = CheckOverwriteFile();
  2675. if (!nReplyError)
  2676. {
  2677. if (pData->transferfile.get)
  2678. {
  2679. CString path=pData->transferfile.localfile;
  2680. if (path.ReverseFind(L'\\')!=-1)
  2681. {
  2682. path=path.Left(path.ReverseFind(L'\\')+1);
  2683. CString path2;
  2684. while (path!=L"")
  2685. {
  2686. path2+=path.Left(path.Find( L"\\" )+1);
  2687. path=path.Mid(path.Find( L"\\" )+1);
  2688. CreateDirectory(path2, 0);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. }
  2694. }
  2695. else
  2696. {
  2697. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2698. }
  2699. }
  2700. else
  2701. {
  2702. if (path.IsEmpty())
  2703. m_Operation.nOpState = FILETRANSFER_PWD;
  2704. else
  2705. m_Operation.nOpState = FILETRANSFER_CWD;
  2706. }
  2707. }
  2708. else
  2709. {
  2710. ///////////
  2711. //Replies//
  2712. ///////////
  2713. int code = GetReplyCode();
  2714. switch(m_Operation.nOpState)
  2715. {
  2716. case FILETRANSFER_PWD:
  2717. if (code != 2 && code != 3)
  2718. {
  2719. nReplyError = FZ_REPLY_ERROR;
  2720. break;
  2721. }
  2722. pData->rawpwd = GetReply();
  2723. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  2724. pData->rawpwd[0] != L'/')
  2725. {
  2726. m_mayBeMvsFilesystem = false;
  2727. m_mayBeBS2000Filesystem = false;
  2728. if (m_mayBeBS2000Filesystem)
  2729. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  2730. else
  2731. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  2732. pData->transferfile.remotepath.SetServer(m_CurrentServer);
  2733. }
  2734. if (!ParsePwdReply(pData->rawpwd))
  2735. return;
  2736. if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
  2737. {
  2738. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2739. }
  2740. else
  2741. m_Operation.nOpState = LIST_CWD;
  2742. break;
  2743. case FILETRANSFER_CWD:
  2744. if (code != 2 && code != 3)
  2745. if (pData->transferfile.get)
  2746. {
  2747. pData->bUseAbsolutePaths = TRUE;
  2748. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2749. }
  2750. else
  2751. m_Operation.nOpState = FILETRANSFER_MKD;
  2752. else
  2753. m_Operation.nOpState = FILETRANSFER_PWD2;
  2754. break;
  2755. case FILETRANSFER_MKD:
  2756. switch(pData->nMKDOpState)
  2757. {
  2758. case MKD_FINDPARENT:
  2759. {
  2760. if (code == 2 || code == 3)
  2761. {
  2762. m_pOwner->SetCurrentPath(pData->MKDCurrent);
  2763. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2764. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2765. CString Segment=pData->MKDSegments.front();
  2766. pData->MKDSegments.pop_front();
  2767. if (!Send( L"MKD " + Segment))
  2768. return;
  2769. }
  2770. else
  2771. {
  2772. if (!pData->MKDCurrent.HasParent())
  2773. nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
  2774. else
  2775. {
  2776. pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
  2777. pData->MKDCurrent=pData->MKDCurrent.GetParent();
  2778. if (!Send(L"CWD "+pData->MKDCurrent.GetPathUnterminated()))
  2779. return;
  2780. }
  2781. }
  2782. }
  2783. break;
  2784. case MKD_MAKESUBDIRS:
  2785. {
  2786. if (code == 2 || code == 3)
  2787. { //Create dir entry in parent dir
  2788. DebugAssert(!pData->MKDSegments.empty());
  2789. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2790. CString Segment=pData->MKDSegments.front();
  2791. pData->MKDSegments.pop_front();
  2792. if (Send( L"MKD " + Segment))
  2793. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2794. else
  2795. return;
  2796. }
  2797. else
  2798. nReplyError=FZ_REPLY_ERROR;
  2799. }
  2800. break;
  2801. case MKD_CHANGETOSUBDIR:
  2802. {
  2803. if (code == 2 || code == 3 || //Creation successful
  2804. m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
  2805. {
  2806. CServerPath path2 = pData->MKDCurrent;
  2807. if (path2.HasParent())
  2808. {
  2809. CString name=path2.GetLastSegment();
  2810. path2=path2.GetParent();
  2811. t_directory dir;
  2812. BOOL res=FALSE;
  2813. if (m_pDirectoryListing)
  2814. {
  2815. if (m_pDirectoryListing->path==path2)
  2816. {
  2817. dir=*m_pDirectoryListing;
  2818. res=TRUE;
  2819. }
  2820. }
  2821. t_directory WorkingDir;
  2822. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  2823. if (!res && bFound)
  2824. if (WorkingDir.path==path2)
  2825. {
  2826. dir=WorkingDir;
  2827. res=TRUE;
  2828. }
  2829. if (!res)
  2830. {
  2831. dir.path=path2;
  2832. dir.server=m_CurrentServer;
  2833. }
  2834. int i;
  2835. for (i=0; i<dir.num; i++)
  2836. if (dir.direntry[i].name == name)
  2837. {
  2838. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  2839. break;
  2840. }
  2841. if (i==dir.num)
  2842. {
  2843. t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
  2844. for (i=0;i<dir.num;i++)
  2845. entries[i]=dir.direntry[i];
  2846. entries[i].name=name;
  2847. entries[i].dir=TRUE;
  2848. entries[i].date.hasdate=FALSE;
  2849. entries[i].size=-1;
  2850. entries[i].bUnsure=FALSE;
  2851. delete [] dir.direntry;
  2852. dir.direntry=entries;
  2853. dir.num++;
  2854. BOOL updated=FALSE;
  2855. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  2856. {
  2857. updated=TRUE;
  2858. SetDirectoryListing(&dir);
  2859. }
  2860. if (!updated)
  2861. if (WorkingDir.path==dir.path)
  2862. {
  2863. updated=TRUE;
  2864. m_pOwner->SetWorkingDir(&dir);
  2865. }
  2866. }
  2867. }
  2868. }
  2869. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  2870. if (pData->MKDSegments.empty())
  2871. m_Operation.nOpState=FILETRANSFER_CWD2;
  2872. else
  2873. {
  2874. if (Send( L"CWD " + pData->MKDCurrent.GetPathUnterminated()))
  2875. pData->nMKDOpState=MKD_MAKESUBDIRS;
  2876. else
  2877. return;
  2878. }
  2879. }
  2880. break;
  2881. default:
  2882. DebugFail();
  2883. }
  2884. break;
  2885. case FILETRANSFER_CWD2:
  2886. if (code != 2 && code != 3)
  2887. if (code == 4)
  2888. nReplyError=FZ_REPLY_ERROR;
  2889. else
  2890. nReplyError=FZ_REPLY_CRITICALERROR;
  2891. else
  2892. m_Operation.nOpState=FILETRANSFER_PWD2;
  2893. break;
  2894. case FILETRANSFER_PWD2:
  2895. if (code != 2 && code != 3)
  2896. nReplyError = FZ_REPLY_ERROR;
  2897. else
  2898. {
  2899. pData->rawpwd = GetReply();
  2900. if (!ParsePwdReply(pData->rawpwd))
  2901. return;
  2902. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2903. }
  2904. break;
  2905. case FILETRANSFER_LIST_MODE:
  2906. #ifdef MPEXT_NO_ZLIB
  2907. DebugFail();
  2908. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2909. #else
  2910. if (code == 2 || code == 3)
  2911. m_useZlib = !m_useZlib;
  2912. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
  2913. #endif
  2914. break;
  2915. case FILETRANSFER_LIST_OPTS:
  2916. #ifdef MPEXT_NO_ZLIB
  2917. DebugFail();
  2918. #else
  2919. if (code == 2 || code == 3)
  2920. m_zlibLevel = pData->newZlibLevel;
  2921. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2922. #endif
  2923. break;
  2924. case FILETRANSFER_LIST_TYPE:
  2925. if (code != 2 && code != 3)
  2926. nReplyError = FZ_REPLY_ERROR;
  2927. else
  2928. m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
  2929. break;
  2930. case FILETRANSFER_LIST_PORTPASV:
  2931. if (code!=3 && code!=2)
  2932. {
  2933. if (!pData->bTriedPortPasvOnce)
  2934. {
  2935. pData->bTriedPortPasvOnce = TRUE;
  2936. pData->bPasv = !pData->bPasv;
  2937. }
  2938. else
  2939. nReplyError=FZ_REPLY_ERROR;
  2940. break;
  2941. }
  2942. if (pData->bPasv)
  2943. {
  2944. CString reply = GetReply();
  2945. int i,j;
  2946. // MP EXT
  2947. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  2948. {
  2949. i++;
  2950. j--;
  2951. }
  2952. else
  2953. {
  2954. // MP EXT
  2955. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  2956. {
  2957. i += 4;
  2958. j = reply.GetLength() - 1;
  2959. }
  2960. else
  2961. {
  2962. if (!pData->bTriedPortPasvOnce)
  2963. {
  2964. pData->bTriedPortPasvOnce = TRUE;
  2965. pData->bPasv = !pData->bPasv;
  2966. }
  2967. else
  2968. nReplyError = FZ_REPLY_ERROR;
  2969. break;
  2970. }
  2971. }
  2972. CString temp = reply.Mid(i,(j-i)+1);
  2973. if (GetFamily() == AF_INET)
  2974. {
  2975. int count=0;
  2976. int pos=0;
  2977. //Convert commas to dots
  2978. temp.Replace( L",", L"." );
  2979. while(1)
  2980. {
  2981. pos=temp.Find(L".",pos);
  2982. if (pos!=-1)
  2983. count++;
  2984. else
  2985. break;
  2986. pos++;
  2987. }
  2988. if (count!=5)
  2989. {
  2990. if (!pData->bTriedPortPasvOnce)
  2991. {
  2992. pData->bTriedPortPasvOnce = TRUE;
  2993. pData->bPasv = !pData->bPasv;
  2994. }
  2995. else
  2996. nReplyError = FZ_REPLY_ERROR;
  2997. break;
  2998. }
  2999. i=temp.ReverseFind(L'.');
  3000. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3001. temp=temp.Left(i);
  3002. i=temp.ReverseFind(L'.');
  3003. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3004. pData->host=temp.Left(i);
  3005. if (!CheckForcePasvIp(pData->host))
  3006. {
  3007. nReplyError = FZ_REPLY_ERROR;
  3008. break;
  3009. }
  3010. }
  3011. else if (GetFamily() == AF_INET6)
  3012. {
  3013. temp = temp.Mid(3);
  3014. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3015. if (pData->port < 0 || pData->port > 65535)
  3016. {
  3017. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3018. nReplyError = FZ_REPLY_ERROR;
  3019. break;
  3020. }
  3021. pData->host = m_CurrentServer.host;
  3022. }
  3023. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3024. #ifndef MPEXT_NO_ZLIB
  3025. if (m_useZlib)
  3026. {
  3027. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3028. {
  3029. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3030. ResetOperation(FZ_REPLY_ERROR);
  3031. return;
  3032. }
  3033. }
  3034. #endif
  3035. #ifndef MPEXT_NO_GSS
  3036. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3037. m_pTransferSocket->UseGSS(m_pGssLayer);
  3038. #endif
  3039. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3040. m_pTransferSocket->SetFamily(GetFamily());
  3041. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3042. {
  3043. nReplyError = FZ_REPLY_ERROR;
  3044. break;
  3045. }
  3046. DebugCheck(m_pTransferSocket->AsyncSelect());
  3047. }
  3048. m_Operation.nOpState=FILETRANSFER_LIST_LIST;
  3049. break;
  3050. case FILETRANSFER_LIST_LIST:
  3051. if (IsMisleadingListResponse())
  3052. {
  3053. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  3054. t_directory listing;
  3055. listing.server = m_CurrentServer;
  3056. listing.path.SetServer(m_CurrentServer);
  3057. if (pData->rawpwd != L"")
  3058. {
  3059. if (!listing.path.SetPath(pData->rawpwd))
  3060. {
  3061. delete m_pDirectoryListing;
  3062. m_pDirectoryListing = 0;
  3063. delete m_pTransferSocket;
  3064. m_pTransferSocket = 0;
  3065. ResetOperation(FZ_REPLY_ERROR);
  3066. return;
  3067. }
  3068. }
  3069. else
  3070. listing.path = pData->transferfile.remotepath;
  3071. SetDirectoryListing(&listing);
  3072. m_Operation.nOpState = FILETRANSFER_TYPE;
  3073. delete m_pTransferSocket;
  3074. m_pTransferSocket = 0;
  3075. nReplyError = CheckOverwriteFile();
  3076. if (!nReplyError)
  3077. {
  3078. if (pData->transferfile.get)
  3079. {
  3080. CString path=pData->transferfile.localfile;
  3081. if (path.ReverseFind(L'\\')!=-1)
  3082. {
  3083. path=path.Left(path.ReverseFind(L'\\')+1);
  3084. CString path2;
  3085. while (path!=L"")
  3086. {
  3087. path2+=path.Left(path.Find( L"\\" )+1);
  3088. path=path.Mid(path.Find( L"\\" )+1);
  3089. CreateDirectory(path2, 0);
  3090. }
  3091. }
  3092. }
  3093. }
  3094. }
  3095. else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
  3096. {
  3097. TransferHandleListError();
  3098. }
  3099. else if (code!=1)
  3100. nReplyError=FZ_REPLY_ERROR;
  3101. else
  3102. m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
  3103. break;
  3104. case FILETRANSFER_LIST_WAITFINISH:
  3105. if (!bFinish)
  3106. {
  3107. if (code!=2 && code!=3)
  3108. {
  3109. if (code==4 || code==5)
  3110. {
  3111. TransferHandleListError();
  3112. }
  3113. else
  3114. {
  3115. nReplyError=FZ_REPLY_ERROR;
  3116. }
  3117. }
  3118. else
  3119. pData->nGotTransferEndReply = 1;
  3120. }
  3121. if (pData->nGotTransferEndReply && pData->pDirectoryListing)
  3122. {
  3123. SetDirectoryListing(pData->pDirectoryListing);
  3124. delete m_pTransferSocket;
  3125. m_pTransferSocket=0;
  3126. m_Operation.nOpState=FILETRANSFER_TYPE;
  3127. nReplyError = CheckOverwriteFile();
  3128. if (!nReplyError)
  3129. {
  3130. if (pData->transferfile.get)
  3131. {
  3132. CString path=pData->transferfile.localfile;
  3133. if (path.ReverseFind(L'\\')!=-1)
  3134. {
  3135. path=path.Left(path.ReverseFind(L'\\')+1);
  3136. CString path2;
  3137. while (path!=L"")
  3138. {
  3139. path2+=path.Left(path.Find( L"\\" )+1);
  3140. path=path.Mid(path.Find( L"\\" )+1);
  3141. CreateDirectory(path2, 0);
  3142. }
  3143. }
  3144. }
  3145. }
  3146. pData->nGotTransferEndReply=0;
  3147. }
  3148. break;
  3149. case FILETRANSFER_NOLIST_SIZE:
  3150. {
  3151. __int64 size;
  3152. if (HandleSize(code, size))
  3153. {
  3154. DebugAssert(!pData->pFileSize);
  3155. pData->pFileSize=new _int64;
  3156. *pData->pFileSize=size;
  3157. }
  3158. }
  3159. m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
  3160. break;
  3161. case FILETRANSFER_NOLIST_MDTM:
  3162. if (HandleMdtm(code, pData->remoteDate))
  3163. {
  3164. pData->hasRemoteDate = true;
  3165. }
  3166. m_Operation.nOpState=FILETRANSFER_TYPE;
  3167. nReplyError=CheckOverwriteFile();
  3168. break;
  3169. case FILETRANSFER_TYPE:
  3170. if (code!=2 && code!=3)
  3171. nReplyError = FZ_REPLY_ERROR;
  3172. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
  3173. break;
  3174. case FILETRANSFER_WAIT:
  3175. if (!pData->nWaitNextOpState)
  3176. nReplyError=FZ_REPLY_ERROR;
  3177. else
  3178. m_Operation.nOpState=pData->nWaitNextOpState;
  3179. break;
  3180. case FILETRANSFER_MODE:
  3181. #ifdef MPEXT_NO_ZLIB
  3182. DebugFail();
  3183. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3184. #else
  3185. if (code == 2 || code == 3)
  3186. m_useZlib = !m_useZlib;
  3187. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
  3188. #endif
  3189. break;
  3190. case FILETRANSFER_OPTS:
  3191. #ifdef MPEXT_NO_ZLIB
  3192. DebugFail();
  3193. #else
  3194. if (code == 2 || code == 3)
  3195. m_zlibLevel = pData->newZlibLevel;
  3196. #endif
  3197. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3198. break;
  3199. case FILETRANSFER_PORTPASV:
  3200. if (code == 3 || code == 2)
  3201. {
  3202. if (pData->bPasv)
  3203. {
  3204. CString reply = GetReply();
  3205. int i,j;
  3206. // MP EXT
  3207. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  3208. {
  3209. i++;
  3210. j--;
  3211. }
  3212. else
  3213. {
  3214. // MP EXT
  3215. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  3216. {
  3217. i += 4;
  3218. j = reply.GetLength() - 1;
  3219. }
  3220. else
  3221. {
  3222. if (!pData->bTriedPortPasvOnce)
  3223. {
  3224. pData->bTriedPortPasvOnce = TRUE;
  3225. pData->bPasv = !pData->bPasv;
  3226. }
  3227. else
  3228. nReplyError = FZ_REPLY_ERROR;
  3229. break;
  3230. }
  3231. }
  3232. CString temp = reply.Mid(i,(j-i)+1);
  3233. if (GetFamily() == AF_INET)
  3234. {
  3235. int count=0;
  3236. int pos=0;
  3237. //Convert commas to dots
  3238. temp.Replace( L",", L"." );
  3239. while(1)
  3240. {
  3241. pos=temp.Find( L".", pos);
  3242. if (pos!=-1)
  3243. count++;
  3244. else
  3245. break;
  3246. pos++;
  3247. }
  3248. if (count!=5)
  3249. {
  3250. if (!pData->bTriedPortPasvOnce)
  3251. {
  3252. pData->bTriedPortPasvOnce = TRUE;
  3253. pData->bPasv = !pData->bPasv;
  3254. }
  3255. else
  3256. nReplyError = FZ_REPLY_ERROR;
  3257. break;
  3258. }
  3259. i=temp.ReverseFind(L'.');
  3260. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3261. temp=temp.Left(i);
  3262. i=temp.ReverseFind(L'.');
  3263. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3264. pData->host=temp.Left(i);
  3265. if (!CheckForcePasvIp(pData->host))
  3266. {
  3267. nReplyError = FZ_REPLY_ERROR;
  3268. break;
  3269. }
  3270. }
  3271. else if (GetFamily() == AF_INET6)
  3272. {
  3273. temp = temp.Mid(3);
  3274. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3275. if (pData->port < 0 || pData->port > 65535)
  3276. {
  3277. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3278. nReplyError = FZ_REPLY_ERROR;
  3279. break;
  3280. }
  3281. pData->host = m_CurrentServer.host;
  3282. }
  3283. else
  3284. {
  3285. nReplyError = FZ_REPLY_ERROR;
  3286. break;
  3287. }
  3288. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  3289. #ifndef MPEXT_NO_ZLIB
  3290. if (m_useZlib)
  3291. {
  3292. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3293. {
  3294. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3295. ResetOperation(FZ_REPLY_ERROR);
  3296. return;
  3297. }
  3298. }
  3299. #endif
  3300. #ifndef MPEXT_NO_GSS
  3301. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3302. m_pTransferSocket->UseGSS(m_pGssLayer);
  3303. #endif
  3304. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3305. m_pTransferSocket->SetFamily(GetFamily());
  3306. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3307. {
  3308. nReplyError = FZ_REPLY_ERROR;
  3309. break;
  3310. }
  3311. DebugCheck(m_pTransferSocket->AsyncSelect());
  3312. }
  3313. if (pData->transferdata.bResume)
  3314. m_Operation.nOpState = FILETRANSFER_REST;
  3315. else
  3316. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3317. BOOL res = FALSE;
  3318. if (!m_pDataFile)
  3319. m_pDataFile = new CFile;
  3320. if (pData->transferfile.get)
  3321. {
  3322. if (pData->transferdata.bResume)
  3323. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
  3324. else
  3325. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
  3326. }
  3327. else
  3328. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyNone);
  3329. if (!res)
  3330. {
  3331. wchar_t * Error = m_pTools->LastSysErrorMessage();
  3332. //Error opening the file
  3333. CString str;
  3334. str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
  3335. str += L"\n";
  3336. str += Error;
  3337. free(Error);
  3338. ShowStatus(str,FZ_LOG_ERROR);
  3339. nReplyError = FZ_REPLY_ERROR;
  3340. break;
  3341. }
  3342. if (!m_pTransferSocket)
  3343. {
  3344. nReplyError=FZ_REPLY_ERROR;
  3345. break;
  3346. }
  3347. m_pTransferSocket->m_pFile = m_pDataFile;
  3348. if (!pData->transferfile.get)
  3349. {
  3350. // See comment in !get branch below
  3351. pData->transferdata.transfersize=GetLength64(*m_pDataFile);
  3352. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3353. if (pData->transferdata.bResume)
  3354. {
  3355. CString remotefile=pData->transferfile.remotefile;
  3356. if (m_pDirectoryListing)
  3357. for (int i = 0; i < m_pDirectoryListing->num; i++)
  3358. {
  3359. if (m_pDirectoryListing->direntry[i].name == remotefile)
  3360. {
  3361. pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
  3362. break;
  3363. }
  3364. }
  3365. _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
  3366. LONG low = static_cast<LONG>(size&0xFFFFFFFF);
  3367. LONG high = static_cast<LONG>(size>>32);
  3368. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3369. {
  3370. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3371. nReplyError = FZ_REPLY_ERROR;
  3372. }
  3373. }
  3374. }
  3375. else
  3376. {
  3377. // Resetting transfersize here is pointless as we
  3378. // always provide valid size in call to FileTransfer.
  3379. // We unnecessary reply on the file being in the directory listing.
  3380. pData->transferdata.transfersize=-1;
  3381. CString remotefile=pData->transferfile.remotefile;
  3382. if (m_pDirectoryListing)
  3383. for (int i=0; i<m_pDirectoryListing->num; i++)
  3384. {
  3385. if (m_pDirectoryListing->direntry[i].name==remotefile)
  3386. {
  3387. pData->hasRemoteDate = true;
  3388. pData->remoteDate = m_pDirectoryListing->direntry[i].date;
  3389. pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
  3390. }
  3391. }
  3392. else if (pData->pFileSize)
  3393. pData->transferdata.transfersize=*pData->pFileSize;
  3394. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3395. }
  3396. }
  3397. else
  3398. if (!pData->bTriedPortPasvOnce)
  3399. {
  3400. pData->bTriedPortPasvOnce = TRUE;
  3401. pData->bPasv = !pData->bPasv;
  3402. }
  3403. else
  3404. nReplyError = FZ_REPLY_ERROR;
  3405. break;
  3406. case FILETRANSFER_REST:
  3407. { //Resume
  3408. if (code==3 || code==2)
  3409. {
  3410. LONG high = 0;
  3411. if (pData->transferfile.get)
  3412. {
  3413. pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
  3414. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3415. {
  3416. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3417. nReplyError = FZ_REPLY_ERROR;
  3418. }
  3419. else
  3420. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3421. }
  3422. else
  3423. {
  3424. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3425. }
  3426. }
  3427. else
  3428. {
  3429. if (code==5 && GetReply()[1]==L'0')
  3430. {
  3431. if (pData->transferfile.get)
  3432. {
  3433. if (pData->transferdata.transfersize!=-1)
  3434. {
  3435. DebugAssert(m_pDataFile);
  3436. if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
  3437. {
  3438. ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, FZ_LOG_STATUS);
  3439. ResetOperation(FZ_REPLY_OK);
  3440. return;
  3441. }
  3442. }
  3443. ShowStatus(IDS_ERRORMSG_CANTRESUME, FZ_LOG_ERROR);
  3444. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3445. pData->transferdata.bResume=FALSE;
  3446. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3447. }
  3448. else
  3449. {
  3450. ShowStatus(L"Resume command not supported by server, trying append.", FZ_LOG_PROGRESS);
  3451. pData->transferdata.bResumeAppend=TRUE;
  3452. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3453. }
  3454. }
  3455. else
  3456. nReplyError=FZ_REPLY_ERROR;
  3457. }
  3458. }
  3459. break;
  3460. case FILETRANSFER_RETRSTOR:
  3461. // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
  3462. // is successful.
  3463. // On failure, it's a 4xy or 5xy reply.
  3464. // However, some servers send a 2xy transfer complete reply without opening a data
  3465. // connection if there's no data to send.
  3466. if (code==2)
  3467. {
  3468. //Transfer successful, however server did not open data connection
  3469. ResetOperation(FZ_REPLY_OK);
  3470. return;
  3471. }
  3472. else if (code!=1)
  3473. {
  3474. if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
  3475. {
  3476. pData->askOnResumeFail = false;
  3477. delete m_pTransferSocket;
  3478. m_pTransferSocket = 0;
  3479. delete m_pDataFile;
  3480. m_pDataFile = 0;
  3481. pData->nGotTransferEndReply = 0;
  3482. nReplyError = CheckOverwriteFile();
  3483. }
  3484. else
  3485. {
  3486. nReplyError = FZ_REPLY_ERROR;
  3487. if (code == 5)
  3488. nReplyError |= FZ_REPLY_CRITICALERROR;
  3489. }
  3490. }
  3491. else
  3492. {
  3493. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  3494. //Look if we can find any information about the resume offset
  3495. if (!pData->transferfile.get && pData->transferdata.bResumeAppend)
  3496. {
  3497. _int64 nOffset = -1;
  3498. CString reply = GetReply();
  3499. reply.MakeLower();
  3500. int pos = reply.Find(L"restarting at offset ");
  3501. if (pos != -1)
  3502. pos += _tcslen(L"restarting at offset ");
  3503. reply = reply.Mid(pos);
  3504. int i;
  3505. for (i=0; i<reply.GetLength(); i++)
  3506. {
  3507. if (reply[i] < L'0' || reply[i] > L'9')
  3508. break;
  3509. }
  3510. if (i == reply.GetLength())
  3511. nOffset = _ttoi64(reply);
  3512. if (nOffset != -1 && m_pDataFile)
  3513. {
  3514. LONG low = 0;
  3515. LONG high = 0;
  3516. if (nOffset >= GetLength64(*m_pDataFile))
  3517. {
  3518. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3519. {
  3520. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3521. nReplyError = FZ_REPLY_ERROR;
  3522. }
  3523. }
  3524. else
  3525. {
  3526. low=static_cast<LONG>(nOffset&0xFFFFFFFF);
  3527. high=static_cast<LONG>(nOffset>>32);
  3528. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3529. {
  3530. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3531. nReplyError = FZ_REPLY_ERROR;
  3532. }
  3533. }
  3534. }
  3535. if (!nReplyError && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3536. {
  3537. m_pTransferSocket->SetActive();
  3538. }
  3539. }
  3540. else if (pData->bPasv && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3541. {
  3542. m_pTransferSocket->SetActive();
  3543. }
  3544. }
  3545. break;
  3546. case FILETRANSFER_WAITFINISH:
  3547. if (bFinish)
  3548. {
  3549. if (nError)
  3550. {
  3551. LogMessage(FZ_LOG_INFO, L"Transfer completed");
  3552. }
  3553. else
  3554. {
  3555. LogMessage(FZ_LOG_INFO, L"Transfer failed");
  3556. }
  3557. }
  3558. if (!bFinish)
  3559. {
  3560. if (code == 1)
  3561. {
  3562. /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
  3563. * Just ignore the additional ones.
  3564. */
  3565. LogMessage(FZ_LOG_WARNING, L"Server sent more than one code 1yz reply, ignoring additional reply");
  3566. break;
  3567. }
  3568. else if (code!=2 && code!=3)
  3569. nReplyError = FZ_REPLY_ERROR;
  3570. else
  3571. {
  3572. pData->nGotTransferEndReply |= 1;
  3573. }
  3574. }
  3575. if (pData->nGotTransferEndReply==3)
  3576. {
  3577. // Not really sure about a reason for the m_pDataFile condition here
  3578. TransferFinished(m_pDataFile != NULL);
  3579. return;
  3580. }
  3581. break;
  3582. case FILETRANSFER_MFMT:
  3583. //Transfer successful
  3584. ResetOperation(FZ_REPLY_OK);
  3585. break;
  3586. }
  3587. if (nReplyError)
  3588. { //Error transferring the file
  3589. ResetOperation(nReplyError);
  3590. return;
  3591. }
  3592. }
  3593. /////////////////
  3594. //Send commands//
  3595. /////////////////
  3596. BOOL bError=FALSE;
  3597. switch(m_Operation.nOpState)
  3598. {
  3599. case FILETRANSFER_PWD:
  3600. if (!Send(L"PWD"))
  3601. bError = TRUE;
  3602. break;
  3603. case FILETRANSFER_CWD:
  3604. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3605. bError=TRUE;
  3606. break;
  3607. case FILETRANSFER_MKD:
  3608. if (pData->nMKDOpState==MKD_INIT)
  3609. {
  3610. if (!pData->transferfile.remotepath.HasParent())
  3611. {
  3612. LogMessage(FZ_LOG_WARNING, L"Can't create root dir");
  3613. ResetOperation(FZ_REPLY_CRITICALERROR);
  3614. return;
  3615. }
  3616. if (!Send(L"CWD "+pData->transferfile.remotepath.GetParent().GetPathUnterminated()))
  3617. bError=TRUE;
  3618. pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
  3619. pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
  3620. pData->nMKDOpState=MKD_FINDPARENT;
  3621. }
  3622. break;
  3623. case FILETRANSFER_CWD2:
  3624. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3625. bError=TRUE;
  3626. break;
  3627. case FILETRANSFER_PWD2:
  3628. if (!Send(L"PWD"))
  3629. bError=TRUE;
  3630. break;
  3631. case FILETRANSFER_LIST_MODE:
  3632. #ifdef MPEXT_NO_ZLIB
  3633. DebugFail();
  3634. #else
  3635. if (m_useZlib)
  3636. {
  3637. if (!Send(L"MODE S"))
  3638. bError = TRUE;
  3639. }
  3640. else
  3641. if (!Send(L"MODE Z"))
  3642. bError = TRUE;
  3643. #endif
  3644. break;
  3645. case FILETRANSFER_LIST_OPTS:
  3646. #ifdef MPEXT_NO_ZLIB
  3647. DebugFail();
  3648. #else
  3649. {
  3650. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3651. CString str;
  3652. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3653. if (!Send(str))
  3654. bError = TRUE;
  3655. }
  3656. #endif
  3657. break;
  3658. case FILETRANSFER_LIST_PORTPASV:
  3659. delete m_pDirectoryListing;
  3660. m_pDirectoryListing=0;
  3661. if (pData->bPasv)
  3662. {
  3663. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3664. bError=TRUE;
  3665. }
  3666. else
  3667. {
  3668. if (m_pTransferSocket)
  3669. {
  3670. delete m_pTransferSocket;
  3671. }
  3672. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3673. #ifndef MPEXT_NO_ZLIB
  3674. if (m_useZlib)
  3675. {
  3676. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3677. {
  3678. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3679. ResetOperation(FZ_REPLY_ERROR);
  3680. return;
  3681. }
  3682. }
  3683. #endif
  3684. #ifndef MPEXT_NO_GSS
  3685. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3686. m_pTransferSocket->UseGSS(m_pGssLayer);
  3687. #endif
  3688. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3689. m_pTransferSocket->m_bListening = TRUE;
  3690. m_pTransferSocket->SetFamily(GetFamily());
  3691. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3692. bError=TRUE;
  3693. else if (m_pProxyLayer)
  3694. {
  3695. SOCKADDR_IN addr;
  3696. int len=sizeof(addr);
  3697. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3698. {
  3699. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3700. bError=TRUE;
  3701. }
  3702. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3703. {
  3704. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3705. bError=TRUE;
  3706. }
  3707. //Don't send PORT command yet, params are unknown.
  3708. //will be sent in TransfersocketListenFinished
  3709. }
  3710. else
  3711. {
  3712. //Set up an active file transfer
  3713. CString temp;
  3714. UINT nPort;
  3715. if (//create listen socket (let Windows choose the port) & start listening
  3716. !m_pTransferSocket->Listen() ||
  3717. !m_pTransferSocket->GetSockName(temp, nPort))
  3718. {
  3719. bError = TRUE;
  3720. break;
  3721. }
  3722. CString host;
  3723. if (GetFamily() == AF_INET)
  3724. {
  3725. host = GetOption(OPTION_TRANSFERIP);
  3726. if (host != L"")
  3727. {
  3728. DWORD ip = inet_addr(T2CA(host));
  3729. if (ip != INADDR_NONE)
  3730. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3731. else
  3732. {
  3733. hostent *fullname = gethostbyname(T2CA(host));
  3734. if (!fullname)
  3735. host = L"";
  3736. else
  3737. {
  3738. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3739. if (ip != INADDR_NONE)
  3740. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3741. else
  3742. host = L"";
  3743. }
  3744. }
  3745. }
  3746. if (host == L"")
  3747. {
  3748. UINT temp;
  3749. if (!GetSockName(host, temp))
  3750. {
  3751. bError = true;
  3752. break;
  3753. }
  3754. host.Replace(L'.', L',');
  3755. }
  3756. if (!bError)
  3757. {
  3758. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3759. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3760. bError = TRUE;
  3761. }
  3762. }
  3763. else if (GetFamily() == AF_INET6)
  3764. {
  3765. host = GetOption(OPTION_TRANSFERIP6);
  3766. if (host != L"")
  3767. {
  3768. USES_CONVERSION;
  3769. addrinfo hints, *res;
  3770. memset(&hints, 0, sizeof(addrinfo));
  3771. hints.ai_family = AF_INET6;
  3772. hints.ai_socktype = SOCK_STREAM;
  3773. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3774. {
  3775. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3776. freeaddrinfo(res);
  3777. }
  3778. else
  3779. host = L"";
  3780. }
  3781. if (host == L"")
  3782. {
  3783. UINT temp;
  3784. if(!GetSockName(host, temp))
  3785. bError = true;
  3786. }
  3787. if (!bError)
  3788. {
  3789. // assamble EPRT command
  3790. CString cmd;
  3791. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3792. if (!Send(cmd))
  3793. bError = TRUE;
  3794. }
  3795. }
  3796. else
  3797. {
  3798. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3799. bError = true;
  3800. }
  3801. }
  3802. }
  3803. break;
  3804. case FILETRANSFER_LIST_TYPE:
  3805. if (!Send(L"TYPE A"))
  3806. bError=TRUE;
  3807. break;
  3808. case FILETRANSFER_LIST_LIST:
  3809. {
  3810. if (!m_pTransferSocket)
  3811. {
  3812. ResetOperation(FZ_REPLY_ERROR);
  3813. return;
  3814. }
  3815. m_pTransferSocket->SetActive();
  3816. CString cmd = GetListingCmd();
  3817. if(!Send(cmd))
  3818. bError=TRUE;
  3819. else if(pData->bPasv)
  3820. {
  3821. if (!ConnectTransferSocket(pData->host, pData->port))
  3822. {
  3823. bError=TRUE;
  3824. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3825. }
  3826. }
  3827. }
  3828. break;
  3829. case FILETRANSFER_NOLIST_SIZE:
  3830. {
  3831. CString command = L"SIZE ";
  3832. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3833. if (!Send(command))
  3834. bError=TRUE;
  3835. }
  3836. break;
  3837. case FILETRANSFER_NOLIST_MDTM:
  3838. {
  3839. CString command = L"MDTM ";
  3840. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3841. if (!Send(command))
  3842. bError=TRUE;
  3843. }
  3844. break;
  3845. case FILETRANSFER_TYPE:
  3846. if (pData->transferfile.nType==1)
  3847. {
  3848. if (!Send(L"TYPE A"))
  3849. bError=TRUE;
  3850. }
  3851. else
  3852. if (!Send(L"TYPE I"))
  3853. bError=TRUE;
  3854. break;
  3855. case FILETRANSFER_MODE:
  3856. #ifdef MPEXT_NO_ZLIB
  3857. DebugFail();
  3858. #else
  3859. if (m_useZlib)
  3860. {
  3861. if (!Send(L"MODE S"))
  3862. bError = TRUE;
  3863. }
  3864. else
  3865. if (!Send(L"MODE Z"))
  3866. bError = TRUE;
  3867. #endif
  3868. break;
  3869. case FILETRANSFER_OPTS:
  3870. #ifdef MPEXT_NO_ZLIB
  3871. DebugFail();
  3872. #else
  3873. {
  3874. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3875. CString str;
  3876. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3877. if (!Send(str))
  3878. bError = TRUE;
  3879. }
  3880. #endif
  3881. break;
  3882. case FILETRANSFER_PORTPASV:
  3883. if (pData->bPasv)
  3884. {
  3885. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3886. bError=TRUE;
  3887. }
  3888. else
  3889. {
  3890. if (m_pTransferSocket)
  3891. {
  3892. delete m_pTransferSocket;
  3893. }
  3894. m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
  3895. #ifndef MPEXT_NO_ZLIB
  3896. if (m_useZlib)
  3897. {
  3898. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3899. {
  3900. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3901. ResetOperation(FZ_REPLY_ERROR);
  3902. return;
  3903. }
  3904. }
  3905. #endif
  3906. #ifndef MPEXT_NO_GSS
  3907. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3908. m_pTransferSocket->UseGSS(m_pGssLayer);
  3909. #endif
  3910. m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
  3911. m_pTransferSocket->m_bListening = TRUE;
  3912. m_pTransferSocket->SetFamily(GetFamily());
  3913. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3914. bError = TRUE;
  3915. else if (m_pProxyLayer)
  3916. {
  3917. SOCKADDR_IN addr;
  3918. int len=sizeof(addr);
  3919. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3920. {
  3921. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3922. bError=TRUE;
  3923. }
  3924. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3925. {
  3926. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3927. bError=TRUE;
  3928. }
  3929. //Don't send PORT command yet, params are unknown.
  3930. //will be sent in TransfersocketListenFinished
  3931. }
  3932. else
  3933. {
  3934. //Set up an active file transfer
  3935. CString temp;
  3936. UINT nPort;
  3937. if (//create listen socket (let Windows choose the port) & start listening
  3938. !m_pTransferSocket->Listen() ||
  3939. !m_pTransferSocket->GetSockName(temp, nPort))
  3940. {
  3941. bError = TRUE;
  3942. break;
  3943. }
  3944. CString host;
  3945. if (GetFamily() == AF_INET)
  3946. {
  3947. host = GetOption(OPTION_TRANSFERIP);
  3948. if (host != L"")
  3949. {
  3950. DWORD ip = inet_addr(T2CA(host));
  3951. if (ip != INADDR_NONE)
  3952. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3953. else
  3954. {
  3955. hostent *fullname = gethostbyname(T2CA(host));
  3956. if (!fullname)
  3957. host = L"";
  3958. else
  3959. {
  3960. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3961. if (ip != INADDR_NONE)
  3962. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3963. else
  3964. host = L"";
  3965. }
  3966. }
  3967. }
  3968. if (host == L"")
  3969. {
  3970. UINT temp;
  3971. if (!GetSockName(host, temp))
  3972. bError = true;
  3973. host.Replace(L'.', L',');
  3974. }
  3975. if (!bError)
  3976. {
  3977. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3978. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3979. bError = TRUE;
  3980. }
  3981. }
  3982. else if (GetFamily() == AF_INET6)
  3983. {
  3984. host = GetOption(OPTION_TRANSFERIP6);
  3985. if (host != L"")
  3986. {
  3987. USES_CONVERSION;
  3988. addrinfo hints, *res;
  3989. memset(&hints, 0, sizeof(addrinfo));
  3990. hints.ai_family = AF_INET6;
  3991. hints.ai_socktype = SOCK_STREAM;
  3992. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3993. {
  3994. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3995. freeaddrinfo(res);
  3996. }
  3997. else
  3998. host = L"";
  3999. }
  4000. if (host == L"")
  4001. {
  4002. UINT temp;
  4003. if(!GetSockName(host, temp))
  4004. bError = true;
  4005. }
  4006. if (!bError)
  4007. {
  4008. // assamble EPRT command
  4009. CString cmd;
  4010. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  4011. if (!Send(cmd))
  4012. bError = TRUE;
  4013. }
  4014. }
  4015. else
  4016. {
  4017. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  4018. bError = true;
  4019. }
  4020. if (bError)
  4021. {
  4022. ResetOperation(FZ_REPLY_ERROR);
  4023. return;
  4024. }
  4025. }
  4026. }
  4027. break;
  4028. case FILETRANSFER_REST:
  4029. DebugAssert(m_pDataFile);
  4030. {
  4031. CString command;
  4032. __int64 transferoffset =
  4033. pData->transferfile.get ?
  4034. GetLength64(*m_pDataFile) :
  4035. pData->transferdata.transfersize-pData->transferdata.transferleft;
  4036. command.Format(L"REST %I64d", transferoffset);
  4037. if (!Send(command))
  4038. bError=TRUE;
  4039. }
  4040. break;
  4041. case FILETRANSFER_RETRSTOR:
  4042. // send RETR/STOR command to server
  4043. if (!m_pTransferSocket)
  4044. {
  4045. ResetOperation(FZ_REPLY_ERROR);
  4046. return;
  4047. }
  4048. m_pTransferSocket->m_transferdata=pData->transferdata;
  4049. if (GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY) || !pData->bPasv)
  4050. {
  4051. m_pTransferSocket->SetActive();
  4052. }
  4053. CString filename;
  4054. filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4055. if(!Send((pData->transferfile.get?L"RETR ":(pData->transferdata.bResumeAppend)?L"APPE ":L"STOR ")+ filename))
  4056. bError = TRUE;
  4057. else
  4058. {
  4059. if (pData->bPasv)
  4060. {
  4061. // if PASV create the socket & initiate outbound data channel connection
  4062. if (!ConnectTransferSocket(pData->host, pData->port))
  4063. {
  4064. bError=TRUE;
  4065. }
  4066. }
  4067. }
  4068. break;
  4069. }
  4070. if (bError)
  4071. { //Error transferring the file
  4072. ResetOperation(FZ_REPLY_ERROR);
  4073. return;
  4074. }
  4075. }
  4076. void CFtpControlSocket::TransferHandleListError()
  4077. {
  4078. if (m_pTransferSocket)
  4079. delete m_pTransferSocket;
  4080. m_pTransferSocket=0;
  4081. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  4082. }
  4083. static int atoui(const wchar_t * s)
  4084. {
  4085. wchar_t * endptr;
  4086. int result = wcstol(s, &endptr, 10);
  4087. if ((*s == L'\0') || (*endptr != L'\0'))
  4088. {
  4089. result = -1;
  4090. }
  4091. return result;
  4092. }
  4093. bool CFtpControlSocket::HandleMdtm(int code, t_directory::t_direntry::t_date & date)
  4094. {
  4095. bool result = false;
  4096. if (code==2)
  4097. {
  4098. CString line = GetReply();
  4099. if ( line.GetLength()>4 && line.Left(4) == L"213 " )
  4100. {
  4101. int y=0, M=0, d=0, h=0, m=0, s=0;
  4102. bool hasseconds = false;
  4103. line=line.Mid(4);
  4104. y=atoui(line.Left(4));
  4105. if ((y >= 0) && (line.GetLength() > 4))
  4106. {
  4107. line=line.Mid(4);
  4108. M=atoui(line.Left(2));
  4109. if ((M >= 0) && (line.GetLength() > 2))
  4110. {
  4111. line=line.Mid(2);
  4112. d=atoui(line.Left(2));
  4113. if ((d >= 0) && (line.GetLength() > 2))
  4114. {
  4115. line=line.Mid(2);
  4116. h=atoui(line.Left(2));
  4117. if ((h >= 0) && (line.GetLength() > 2))
  4118. {
  4119. line=line.Mid(2);
  4120. m=atoui(line.Left(2));
  4121. if ((m >= 0) && (line.GetLength() > 2))
  4122. {
  4123. line=line.Mid(2);
  4124. s=_ttoi(line.Left(2));
  4125. hasseconds = true;
  4126. }
  4127. }
  4128. }
  4129. if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60 && s>=0 && s<60)
  4130. {
  4131. result = true;
  4132. date.year = y;
  4133. date.month = M;
  4134. date.day = d;
  4135. date.hour = h;
  4136. date.minute = m;
  4137. date.second = s;
  4138. date.hastime = true;
  4139. date.hasseconds = hasseconds;
  4140. date.hasdate = true;
  4141. date.utc = true;
  4142. }
  4143. }
  4144. }
  4145. }
  4146. }
  4147. return result;
  4148. }
  4149. bool CFtpControlSocket::HandleSize(int code, __int64 & size)
  4150. {
  4151. bool result = false;
  4152. if (code == 2)
  4153. {
  4154. CString line = GetReply();
  4155. if ((line.GetLength() > 4) && (line.Left(4) == L"213 "))
  4156. {
  4157. size = _ttoi64(line.Mid(4));
  4158. result = true;
  4159. }
  4160. }
  4161. return result;
  4162. }
  4163. void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads)
  4164. {
  4165. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  4166. if (GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile &&
  4167. pData->transferfile.get)
  4168. {
  4169. m_pTools->PreserveDownloadFileTime(
  4170. (HANDLE)m_pDataFile->m_hFile, reinterpret_cast<void *>(pData->transferfile.nUserData));
  4171. }
  4172. if (!pData->transferfile.get &&
  4173. GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && preserveFileTimeForUploads &&
  4174. ((m_serverCapabilities.GetCapability(mfmt_command) == yes) ||
  4175. (m_serverCapabilities.GetCapability(mdtm_command) == yes)))
  4176. {
  4177. CString filename =
  4178. pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4179. struct tm tm;
  4180. if (m_pTools->GetFileModificationTimeInUtc((LPCTSTR)pData->transferfile.localfile, tm))
  4181. {
  4182. CString timestr;
  4183. timestr.Format(L"%02d%02d%02d%02d%02d%02d",
  4184. 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  4185. CString command;
  4186. if (m_serverCapabilities.GetCapability(mfmt_command) == yes)
  4187. {
  4188. command = L"MFMT";
  4189. }
  4190. else
  4191. {
  4192. // Support for MDTM does not necessarily mean
  4193. // that the server supports non-standard hack
  4194. // of setting timestamp using
  4195. // MFMT-like (two argument) call to MDTM.
  4196. // IIS definitelly does.
  4197. command = L"MDTM";
  4198. }
  4199. if (Send( command + L" " + timestr + L" " + filename))
  4200. {
  4201. m_Operation.nOpState = FILETRANSFER_MFMT;
  4202. return;
  4203. }
  4204. }
  4205. }
  4206. //Transfer successful
  4207. ResetOperation(FZ_REPLY_OK);
  4208. }
  4209. void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
  4210. {
  4211. const int nOpMode = m_Operation.nOpMode;
  4212. if (nOpMode==CSMODE_CONNECT)
  4213. DoClose(FZ_REPLY_CANCEL);
  4214. else if (nOpMode & CSMODE_LIST)
  4215. {
  4216. if (m_Operation.nOpState == LIST_WAITFINISH)
  4217. m_skipReply = true;
  4218. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4219. }
  4220. else if (nOpMode & CSMODE_TRANSFER)
  4221. {
  4222. if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
  4223. m_skipReply = true;
  4224. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
  4225. }
  4226. else if (nOpMode != CSMODE_NONE)
  4227. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4228. if (nOpMode != CSMODE_NONE && !bQuit)
  4229. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  4230. if (m_awaitsReply)
  4231. m_skipReply = true;
  4232. }
  4233. void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
  4234. {
  4235. if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
  4236. {
  4237. CString host;
  4238. host.Format(L"%d,%d,%d,%d,%d,%d",ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
  4239. Send(L"PORT "+host);
  4240. }
  4241. }
  4242. void CFtpControlSocket::ResumeTransfer()
  4243. {
  4244. if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
  4245. {
  4246. m_pTransferSocket->OnSend(0);
  4247. m_pTransferSocket->OnReceive(0);
  4248. }
  4249. }
  4250. BOOL CFtpControlSocket::Create()
  4251. {
  4252. if (!GetOptionVal(OPTION_LIMITPORTRANGE))
  4253. 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);
  4254. else
  4255. {
  4256. int min=GetOptionVal(OPTION_PORTRANGELOW);
  4257. int max=GetOptionVal(OPTION_PORTRANGEHIGH);
  4258. if (min>=max)
  4259. {
  4260. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4261. return FALSE;
  4262. }
  4263. int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  4264. int port = startport;
  4265. 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))
  4266. {
  4267. port++;
  4268. if (port>max)
  4269. port=min;
  4270. if (port==startport)
  4271. {
  4272. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4273. return FALSE;
  4274. }
  4275. if (!InitConnect())
  4276. return FALSE;
  4277. }
  4278. }
  4279. return TRUE;
  4280. }
  4281. void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
  4282. {
  4283. if (nSuccessful & FZ_REPLY_CRITICALERROR)
  4284. nSuccessful |= FZ_REPLY_ERROR;
  4285. if (m_pTransferSocket)
  4286. delete m_pTransferSocket;
  4287. m_pTransferSocket=0;
  4288. if (m_pDataFile)
  4289. delete m_pDataFile;
  4290. m_pDataFile=0;
  4291. if (m_Operation.nOpMode)
  4292. {
  4293. //Unset busy attribute so that new commands can be executed
  4294. m_pOwner->SetBusy(FALSE);
  4295. if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
  4296. {
  4297. nSuccessful|=FZ_REPLY_DISCONNECTED;
  4298. ShowStatus(IDS_ERRORMSG_CANTCONNECT, FZ_LOG_ERROR);
  4299. }
  4300. if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_LISTFILE|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
  4301. m_LastSendTime=CTime::GetCurrentTime();
  4302. //Update remote file entry
  4303. if (m_Operation.pData &&
  4304. m_Operation.nOpMode&CSMODE_TRANSFER &&
  4305. (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
  4306. m_pDirectoryListing &&
  4307. m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
  4308. {
  4309. CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
  4310. CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
  4311. t_directory dir;
  4312. BOOL res=FALSE;
  4313. if (m_pDirectoryListing)
  4314. {
  4315. if (m_pDirectoryListing->path==path)
  4316. {
  4317. dir=*m_pDirectoryListing;
  4318. res=TRUE;
  4319. }
  4320. }
  4321. t_directory WorkingDir;
  4322. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4323. if (!res && bFound)
  4324. if (WorkingDir.path==path)
  4325. {
  4326. dir=WorkingDir;
  4327. res=TRUE;
  4328. }
  4329. if (res)
  4330. {
  4331. int i;
  4332. for (i=0; i<dir.num; i++)
  4333. if (dir.direntry[i].name==filename)
  4334. {
  4335. dir.direntry[i].bUnsure = TRUE;
  4336. if (nSuccessful & FZ_REPLY_ERROR)
  4337. {
  4338. dir.direntry[i].bUnsure = TRUE;
  4339. if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
  4340. dir.direntry[i].size = -1;
  4341. if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
  4342. dir.direntry[i].size = -1;
  4343. }
  4344. dir.direntry[i].date.hasdate = false;
  4345. break;
  4346. }
  4347. if (i==dir.num)
  4348. {
  4349. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4350. int i;
  4351. for (i=0; i<dir.num; i++)
  4352. entries[i]=dir.direntry[i];
  4353. entries[i].name=filename;
  4354. entries[i].dir=FALSE;
  4355. entries[i].date.hasdate=FALSE;
  4356. entries[i].size=-1;
  4357. if (nSuccessful&FZ_REPLY_OK)
  4358. entries[i].bUnsure=FALSE;
  4359. else
  4360. entries[i].bUnsure=TRUE;
  4361. delete [] dir.direntry;
  4362. dir.direntry=entries;
  4363. dir.num++;
  4364. }
  4365. BOOL updated=FALSE;
  4366. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  4367. {
  4368. updated=TRUE;
  4369. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4370. }
  4371. if (!updated)
  4372. if (bFound && WorkingDir.path==dir.path)
  4373. {
  4374. updated = TRUE;
  4375. m_pOwner->SetWorkingDir(&dir);
  4376. }
  4377. }
  4378. }
  4379. if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
  4380. {
  4381. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  4382. if (nSuccessful&FZ_REPLY_ABORTED)
  4383. //Transfer aborted by user
  4384. ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,FZ_LOG_ERROR);
  4385. else
  4386. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR);
  4387. else if (m_Operation.nOpMode&CSMODE_LIST)
  4388. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  4389. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  4390. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4391. }
  4392. else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
  4393. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS);
  4394. }
  4395. else
  4396. {
  4397. // When control socket is waiting for reply
  4398. // to keepalive (!IsReady), while new command comes,
  4399. // its execution is postponed
  4400. // (CMainThread::m_pPostKeepAliveCommand),
  4401. // but the main thread
  4402. // is set to busy state already (CMainThread::Command).
  4403. // if connection is closed before without receiving reply,
  4404. // main thread would stay busy forever.
  4405. m_pOwner->SetBusy(FALSE);
  4406. //No operation in progress
  4407. nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
  4408. if (!nSuccessful)
  4409. DebugFail();
  4410. }
  4411. if (nSuccessful&FZ_REPLY_DISCONNECTED)
  4412. m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
  4413. if (m_Operation.nOpMode)
  4414. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
  4415. else
  4416. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
  4417. m_Operation.nOpMode=0;
  4418. m_Operation.nOpState=-1;
  4419. if (m_Operation.pData)
  4420. delete m_Operation.pData;
  4421. m_Operation.pData=0;
  4422. }
  4423. void CFtpControlSocket::Delete(CString filename, const CServerPath &path, bool filenameOnly)
  4424. {
  4425. class CDeleteData : public CFtpControlSocket::t_operation::COpData
  4426. {
  4427. public:
  4428. CDeleteData() {}
  4429. virtual ~CDeleteData() {}
  4430. CString m_FileName;
  4431. CServerPath path;
  4432. };
  4433. if (filename!=L"")
  4434. {
  4435. DebugAssert(!path.IsEmpty());
  4436. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4437. DebugAssert(m_Operation.nOpState==-1);
  4438. DebugAssert(!m_Operation.pData);
  4439. m_Operation.nOpMode=CSMODE_DELETE;
  4440. CString command = L"DELE ";
  4441. if (!filenameOnly)
  4442. {
  4443. command += path.FormatFilename(filename);
  4444. }
  4445. else
  4446. {
  4447. command += filename;
  4448. }
  4449. if (!Send(command))
  4450. return;
  4451. CDeleteData *data=new CDeleteData;
  4452. data->m_FileName=filename;
  4453. data->path=path;
  4454. m_Operation.pData=data;
  4455. }
  4456. else
  4457. {
  4458. DebugAssert(path.IsEmpty());
  4459. DebugAssert(m_Operation.nOpMode==CSMODE_DELETE);
  4460. DebugAssert(m_Operation.nOpState==-1);
  4461. DebugAssert(m_Operation.pData);
  4462. int res=GetReplyCode();
  4463. if (res==2 || res==3)
  4464. { //Remove file from cached dirs
  4465. CDeleteData *pData=(CDeleteData *)m_Operation.pData;
  4466. t_directory dir;
  4467. BOOL res=FALSE;
  4468. if (m_pDirectoryListing)
  4469. {
  4470. if (m_pDirectoryListing->path==pData->path)
  4471. {
  4472. dir=*m_pDirectoryListing;
  4473. res=TRUE;
  4474. }
  4475. }
  4476. t_directory WorkingDir;
  4477. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4478. if (!res && bFound)
  4479. if (WorkingDir.path==pData->path)
  4480. {
  4481. dir=WorkingDir;
  4482. res=TRUE;
  4483. }
  4484. if (res)
  4485. {
  4486. BOOL found=FALSE;
  4487. for (int i=0;i<dir.num;i++)
  4488. {
  4489. if (dir.direntry[i].name==pData->m_FileName)
  4490. {
  4491. DebugAssert(!dir.direntry[i].dir || dir.direntry[i].bLink);
  4492. found=TRUE;
  4493. break;
  4494. }
  4495. }
  4496. if (found)
  4497. {
  4498. t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
  4499. int j=0;
  4500. int i;
  4501. for (i=0; i<dir.num; i++)
  4502. {
  4503. if (dir.direntry[i].name==pData->m_FileName)
  4504. continue;
  4505. direntry[j]=dir.direntry[i];
  4506. j++;
  4507. }
  4508. delete [] dir.direntry;
  4509. dir.direntry=direntry;
  4510. dir.num--;
  4511. BOOL updated=FALSE;
  4512. if (m_pDirectoryListing)
  4513. if (m_pDirectoryListing->path==dir.path)
  4514. {
  4515. updated=TRUE;
  4516. SetDirectoryListing(&dir);
  4517. }
  4518. if (!updated)
  4519. if (WorkingDir.path==dir.path)
  4520. {
  4521. updated=TRUE;
  4522. m_pOwner->SetWorkingDir(&dir);
  4523. }
  4524. }
  4525. }
  4526. }
  4527. ResetOperation(FZ_REPLY_OK);
  4528. }
  4529. }
  4530. void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
  4531. {
  4532. class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
  4533. {
  4534. public:
  4535. CRemoveDirData() {}
  4536. virtual ~CRemoveDirData() {}
  4537. CString m_DirName;
  4538. CServerPath path;
  4539. };
  4540. if (dirname != L"")
  4541. {
  4542. DebugAssert(!path.IsEmpty());
  4543. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4544. DebugAssert(m_Operation.nOpState == -1);
  4545. DebugAssert(!m_Operation.pData);
  4546. m_Operation.nOpMode = CSMODE_RMDIR;
  4547. CServerPath newPath = path;
  4548. if (!newPath.AddSubdir(dirname))
  4549. {
  4550. ShowStatus(L"Unable to concatenate path", FZ_LOG_ERROR);
  4551. return;
  4552. }
  4553. if (!Send(L"RMD "+ newPath.GetPathUnterminated()))
  4554. return;
  4555. CRemoveDirData *data = new CRemoveDirData;
  4556. data->m_DirName = dirname;
  4557. data->path = path;
  4558. m_Operation.pData = data;
  4559. }
  4560. else
  4561. {
  4562. DebugAssert(path.IsEmpty());
  4563. DebugAssert(m_Operation.nOpMode == CSMODE_RMDIR);
  4564. DebugAssert(m_Operation.nOpState == -1);
  4565. DebugAssert(m_Operation.pData);
  4566. int res = GetReplyCode();
  4567. if (res == 2 || res == 3)
  4568. { //Remove dir from cached dirs
  4569. CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData;
  4570. t_directory dir;
  4571. BOOL res = FALSE;
  4572. if (m_pDirectoryListing)
  4573. {
  4574. if (m_pDirectoryListing->path == pData->path)
  4575. {
  4576. dir = *m_pDirectoryListing;
  4577. res = TRUE;
  4578. }
  4579. }
  4580. t_directory WorkingDir;
  4581. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4582. if (!res && bFound)
  4583. if (WorkingDir.path == pData->path)
  4584. {
  4585. dir = WorkingDir;
  4586. res = TRUE;
  4587. }
  4588. if (res)
  4589. {
  4590. BOOL found = FALSE;
  4591. for (int i = 0; i < dir.num; i++)
  4592. {
  4593. if (dir.direntry[i].name == pData->m_DirName)
  4594. {
  4595. DebugAssert(dir.direntry[i].dir);
  4596. found = TRUE;
  4597. break;
  4598. }
  4599. }
  4600. if (found)
  4601. {
  4602. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
  4603. int j = 0;
  4604. int i;
  4605. for (i = 0; i < dir.num; i++)
  4606. {
  4607. if (dir.direntry[i].name == pData->m_DirName)
  4608. continue;
  4609. direntry[j] = dir.direntry[i];
  4610. j++;
  4611. }
  4612. delete [] dir.direntry;
  4613. dir.direntry = direntry;
  4614. dir.num--;
  4615. BOOL updated = FALSE;
  4616. if (m_pDirectoryListing)
  4617. if (m_pDirectoryListing->path == dir.path)
  4618. {
  4619. updated = TRUE;
  4620. SetDirectoryListing(&dir);
  4621. }
  4622. if (!updated)
  4623. if (WorkingDir.path == dir.path)
  4624. {
  4625. updated = TRUE;
  4626. m_pOwner->SetWorkingDir(&dir);
  4627. }
  4628. }
  4629. }
  4630. ResetOperation(FZ_REPLY_OK);
  4631. }
  4632. else
  4633. ResetOperation(FZ_REPLY_ERROR);
  4634. }
  4635. }
  4636. int CFtpControlSocket::CheckOverwriteFile()
  4637. {
  4638. if (!m_Operation.pData)
  4639. {
  4640. return FZ_REPLY_ERROR;
  4641. }
  4642. CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
  4643. int nReplyError = 0;
  4644. CFileStatus64 status;
  4645. BOOL res = GetStatus64(pData->transferfile.localfile, status);
  4646. if (!res)
  4647. {
  4648. if (!pData->transferfile.get)
  4649. {
  4650. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4651. nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
  4652. }
  4653. else
  4654. {
  4655. m_Operation.nOpState = FILETRANSFER_TYPE;
  4656. }
  4657. }
  4658. else
  4659. {
  4660. if (status.m_attribute & 0x10)
  4661. {
  4662. nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
  4663. }
  4664. else
  4665. {
  4666. _int64 localsize;
  4667. if (!GetLength64(pData->transferfile.localfile, localsize))
  4668. if (!pData->transferfile.get)
  4669. nReplyError = FZ_REPLY_CRITICALERROR;
  4670. else
  4671. m_Operation.nOpState = FILETRANSFER_TYPE;
  4672. CTime *localtime = NULL;
  4673. TRY
  4674. {
  4675. if (status.m_has_mtime && status.m_mtime != -1)
  4676. localtime = new CTime(status.m_mtime);
  4677. }
  4678. CATCH_ALL(e)
  4679. {
  4680. TCHAR buffer[1024];
  4681. CString str =L"Exception creating CTime object: ";
  4682. if (e->GetErrorMessage(buffer, 1024, NULL))
  4683. str += buffer;
  4684. else
  4685. str += L"Unknown exception";
  4686. LogMessageRaw(FZ_LOG_WARNING, str);
  4687. localtime = NULL;
  4688. }
  4689. END_CATCH_ALL;
  4690. BOOL bRemoteFileExists = FALSE;
  4691. __int64 remotesize = -1;
  4692. t_directory::t_direntry::t_date remotetime;
  4693. if (m_pDirectoryListing)
  4694. {
  4695. for (int i=0; i<m_pDirectoryListing->num; i++)
  4696. {
  4697. CString remotefile = pData->transferfile.remotefile;
  4698. if (m_pDirectoryListing->direntry[i].name == remotefile)
  4699. {
  4700. remotesize = m_pDirectoryListing->direntry[i].size;
  4701. remotetime = m_pDirectoryListing->direntry[i].date;
  4702. bRemoteFileExists = TRUE;
  4703. break;
  4704. }
  4705. }
  4706. }
  4707. if (!bRemoteFileExists && pData->hasRemoteDate)
  4708. {
  4709. remotetime = pData->remoteDate;
  4710. bRemoteFileExists = TRUE;
  4711. }
  4712. if (remotesize == -1 && pData->pFileSize)
  4713. {
  4714. remotesize = *pData->pFileSize;
  4715. bRemoteFileExists = TRUE;
  4716. }
  4717. if (bRemoteFileExists || pData->transferfile.get )
  4718. {
  4719. COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
  4720. t_transferfile *pTransferFile = new t_transferfile;
  4721. *pTransferFile = pData->transferfile;
  4722. pOverwriteData->pTransferFile = pTransferFile;
  4723. if (pData->transferfile.get)
  4724. {
  4725. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4726. // pos can be -1 here, e.g. in scripting, the code below still works then
  4727. pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
  4728. pOverwriteData->FileName2 = pData->transferfile.remotefile;
  4729. pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
  4730. pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
  4731. pOverwriteData->size1 = localsize;
  4732. pOverwriteData->size2 = remotesize;
  4733. }
  4734. else
  4735. {
  4736. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4737. // pos can be -1 here, e.g. in scripting, the code below still works then
  4738. pOverwriteData->FileName1 = pData->transferfile.remotefile;
  4739. pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
  4740. pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
  4741. pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
  4742. pOverwriteData->size1 = remotesize;
  4743. pOverwriteData->size2 = localsize;
  4744. }
  4745. pOverwriteData->localtime = localtime;
  4746. pOverwriteData->remotetime = remotetime;
  4747. pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  4748. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
  4749. {
  4750. delete pOverwriteData;
  4751. nReplyError = FZ_REPLY_ERROR;
  4752. }
  4753. else
  4754. {
  4755. m_bCheckForTimeout = FALSE;
  4756. m_Operation.nOpState = FILETRANSFER_WAIT;
  4757. }
  4758. }
  4759. else
  4760. {
  4761. m_Operation.nOpState = FILETRANSFER_TYPE;
  4762. delete localtime;
  4763. }
  4764. }
  4765. }
  4766. return nReplyError;
  4767. }
  4768. void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
  4769. {
  4770. if (!pData)
  4771. return;
  4772. if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
  4773. return;
  4774. if (m_Operation.nOpState != FILETRANSFER_WAIT)
  4775. return;
  4776. CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
  4777. if (!pTransferData)
  4778. return;
  4779. pTransferData->transferdata.bResume = false;
  4780. m_bCheckForTimeout = TRUE;
  4781. int nReplyError = 0;
  4782. switch (nAction)
  4783. {
  4784. case FILEEXISTS_SKIP:
  4785. nReplyError = FZ_REPLY_OK;
  4786. break;
  4787. case FILEEXISTS_OVERWRITE:
  4788. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4789. break;
  4790. case FILEEXISTS_RENAME:
  4791. if (pTransferData->transferfile.get)
  4792. {
  4793. CFileStatus64 status;
  4794. if (GetStatus64(pData->FileName1, status))
  4795. {
  4796. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4797. nReplyError= FZ_REPLY_CRITICALERROR;
  4798. }
  4799. else
  4800. {
  4801. pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
  4802. //Replace invalid characters in the local filename
  4803. int pos = pTransferData->transferfile.localfile.ReverseFind(L'\\');
  4804. for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
  4805. if (pTransferData->transferfile.localfile[i] == L':')
  4806. pTransferData->transferfile.localfile.SetAt(i, L'_');
  4807. pTransferData->nWaitNextOpState= FILETRANSFER_TYPE;
  4808. }
  4809. }
  4810. else
  4811. {
  4812. DebugAssert(m_pDirectoryListing);
  4813. int i;
  4814. for (i = 0; i < m_pDirectoryListing->num; i++)
  4815. {
  4816. if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
  4817. {
  4818. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4819. nReplyError = FZ_REPLY_CRITICALERROR;
  4820. break;
  4821. }
  4822. }
  4823. if (i==m_pDirectoryListing->num)
  4824. {
  4825. pTransferData->transferfile.remotefile = pData->FileName1;
  4826. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4827. }
  4828. }
  4829. break;
  4830. case FILEEXISTS_RESUME:
  4831. if (pData->size1 >= 0)
  4832. {
  4833. pTransferData->transferdata.bResume = TRUE;
  4834. }
  4835. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4836. break;
  4837. case FILEEXISTS_COMPLETE:
  4838. // Simulating transfer finish
  4839. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  4840. TransferFinished(true);
  4841. return; // Avoid call to FileTransfer below
  4842. }
  4843. if (nReplyError == FZ_REPLY_OK)
  4844. ResetOperation(FZ_REPLY_OK);
  4845. else if (nReplyError)
  4846. ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
  4847. else
  4848. FileTransfer();
  4849. }
  4850. void CFtpControlSocket::SendKeepAliveCommand()
  4851. {
  4852. ShowStatus(L"Sending dummy command to keep session alive.", FZ_LOG_PROGRESS);
  4853. m_bKeepAliveActive=TRUE;
  4854. //Choose a random command from the list
  4855. TCHAR commands[4][7]={L"PWD",L"REST 0",L"TYPE A",L"TYPE I"};
  4856. int choice=(rand()*4)/(RAND_MAX+1);
  4857. Send(commands[choice]);
  4858. }
  4859. void CFtpControlSocket::MakeDir(const CServerPath &path)
  4860. {
  4861. //Directory creation works like this:
  4862. //Find existing parent and create subdirs one by one
  4863. if (m_Operation.nOpState == MKD_INIT)
  4864. {
  4865. DebugAssert(!path.IsEmpty());
  4866. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4867. DebugAssert(!m_Operation.pData);
  4868. m_Operation.nOpMode = CSMODE_MKDIR;
  4869. if (!Send(L"CWD "+path.GetParent().GetPathUnterminated()))
  4870. return;
  4871. CMakeDirData *data = new CMakeDirData;
  4872. data->path = path;
  4873. data->Current = path.GetParent();
  4874. data->Segments.push_front(path.GetLastSegment());
  4875. m_Operation.pData = data;
  4876. m_Operation.nOpState = MKD_FINDPARENT;
  4877. }
  4878. else if (m_Operation.nOpState==MKD_FINDPARENT)
  4879. {
  4880. DebugAssert(m_Operation.nOpMode==CSMODE_MKDIR);
  4881. DebugAssert(path.IsEmpty());
  4882. DebugAssert(m_Operation.pData);
  4883. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4884. int res=GetReplyCode();
  4885. if (res==2 || res==3)
  4886. {
  4887. m_pOwner->SetCurrentPath(pData->Current);
  4888. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4889. pData->Current.AddSubdir(pData->Segments.front());
  4890. CString Segment=pData->Segments.front();
  4891. pData->Segments.pop_front();
  4892. if (Send( L"MKD " + Segment))
  4893. m_Operation.nOpState = MKD_CHANGETOSUBDIR;
  4894. else
  4895. return;
  4896. }
  4897. else
  4898. {
  4899. if (!pData->Current.HasParent())
  4900. ResetOperation(FZ_REPLY_ERROR);
  4901. else
  4902. {
  4903. pData->Segments.push_front(pData->Current.GetLastSegment());
  4904. pData->Current=pData->Current.GetParent();
  4905. if (!Send(L"CWD "+pData->Current.GetPathUnterminated()))
  4906. return;
  4907. }
  4908. }
  4909. }
  4910. else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
  4911. {
  4912. int res=GetReplyCode();
  4913. if (res==2 || res==3)
  4914. { //Create dir entry in parent dir
  4915. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4916. DebugAssert(!pData->Segments.empty());
  4917. m_pOwner->SetCurrentPath(pData->Current);
  4918. pData->Current.AddSubdir(pData->Segments.front());
  4919. CString Segment=pData->Segments.front();
  4920. pData->Segments.pop_front();
  4921. if (Send( L"MKD " + Segment))
  4922. m_Operation.nOpState=MKD_CHANGETOSUBDIR;
  4923. else
  4924. return;
  4925. }
  4926. else
  4927. ResetOperation(FZ_REPLY_ERROR);
  4928. }
  4929. else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
  4930. {
  4931. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4932. int res=GetReplyCode();
  4933. if (res==2 || res==3 || //Creation successful
  4934. GetReply() == L"550 Directory already exists")//Creation was successful, although someone else did the work for us
  4935. { //Create dir entry in parent dir
  4936. CServerPath path2=pData->Current;
  4937. if (path2.HasParent())
  4938. {
  4939. CString name=path2.GetLastSegment();
  4940. path2=path2.GetParent();
  4941. t_directory dir;
  4942. BOOL res = FALSE;
  4943. if (m_pDirectoryListing)
  4944. {
  4945. if (m_pDirectoryListing->path == path2)
  4946. {
  4947. dir = *m_pDirectoryListing;
  4948. res = TRUE;
  4949. }
  4950. }
  4951. t_directory WorkingDir;
  4952. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4953. if (!res && bFound)
  4954. if (WorkingDir.path == path2)
  4955. {
  4956. dir = WorkingDir;
  4957. res = TRUE;
  4958. }
  4959. if (!res)
  4960. {
  4961. dir.path = path2;
  4962. dir.server = m_CurrentServer;
  4963. }
  4964. int i;
  4965. for (i=0; i<dir.num; i++)
  4966. if (dir.direntry[i].name==name)
  4967. {
  4968. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  4969. break;
  4970. }
  4971. if (i==dir.num)
  4972. {
  4973. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4974. for (i=0;i<dir.num;i++)
  4975. entries[i]=dir.direntry[i];
  4976. entries[i].name=name;
  4977. entries[i].dir=TRUE;
  4978. entries[i].date.hasdate=FALSE;
  4979. entries[i].size=-1;
  4980. entries[i].bUnsure=FALSE;
  4981. delete [] dir.direntry;
  4982. dir.direntry=entries;
  4983. dir.num++;
  4984. BOOL updated = FALSE;
  4985. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4986. {
  4987. updated = TRUE;
  4988. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4989. }
  4990. if (!updated)
  4991. if (bFound && WorkingDir.path == dir.path)
  4992. {
  4993. updated = TRUE;
  4994. m_pOwner->SetWorkingDir(&dir);
  4995. }
  4996. }
  4997. }
  4998. }
  4999. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  5000. if (pData->Segments.empty())
  5001. ResetOperation(FZ_REPLY_OK);
  5002. else
  5003. {
  5004. if (Send( L"CWD " + pData->Current.GetPathUnterminated()))
  5005. m_Operation.nOpState=MKD_MAKESUBDIRS;
  5006. else
  5007. return;
  5008. }
  5009. }
  5010. else
  5011. DebugFail();
  5012. }
  5013. void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
  5014. {
  5015. class CRenameData : public CFtpControlSocket::t_operation::COpData
  5016. {
  5017. public:
  5018. CRenameData() {}
  5019. virtual ~CRenameData() {}
  5020. CString oldName, newName;
  5021. CServerPath path;
  5022. CServerPath newPath;
  5023. };
  5024. if (oldName != L"")
  5025. {
  5026. DebugAssert(newName != L"");
  5027. DebugAssert(!path.IsEmpty());
  5028. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  5029. DebugAssert(m_Operation.nOpState == -1);
  5030. DebugAssert(!m_Operation.pData);
  5031. m_Operation.nOpMode = CSMODE_RENAME;
  5032. if (!Send(L"RNFR " + path.FormatFilename(oldName)))
  5033. return;
  5034. CRenameData *data = new CRenameData;
  5035. data->oldName = oldName;
  5036. data->newName = newName;
  5037. data->path = path;
  5038. data->newPath = newPath;
  5039. m_Operation.pData = data;
  5040. }
  5041. else
  5042. {
  5043. DebugAssert(oldName == L"");
  5044. DebugAssert(path.IsEmpty());
  5045. DebugAssert(m_Operation.nOpMode == CSMODE_RENAME);
  5046. DebugAssert(m_Operation.pData);
  5047. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5048. if (m_Operation.nOpState == -1)
  5049. {
  5050. int res = GetReplyCode();
  5051. if (res == 2 || res == 3)
  5052. {
  5053. m_Operation.nOpState++;
  5054. if (pData->newPath.IsEmpty())
  5055. {
  5056. if (!Send(L"RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5057. return;
  5058. }
  5059. else
  5060. if (!Send(L"RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5061. return;
  5062. }
  5063. else
  5064. ResetOperation(FZ_REPLY_ERROR);
  5065. }
  5066. else
  5067. {
  5068. int res = GetReplyCode();
  5069. if (res == 2 || res == 3)
  5070. { //Rename entry in cached directory
  5071. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5072. t_directory dir;
  5073. BOOL res = FALSE;
  5074. if (m_pDirectoryListing)
  5075. {
  5076. if (m_pDirectoryListing->path == pData->path)
  5077. {
  5078. dir = *m_pDirectoryListing;
  5079. res = TRUE;
  5080. }
  5081. }
  5082. t_directory WorkingDir;
  5083. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5084. if (!res && bFound)
  5085. if (WorkingDir.path == pData->path)
  5086. {
  5087. dir = WorkingDir;
  5088. res = TRUE;
  5089. }
  5090. if (res)
  5091. {
  5092. for (int i=0; i<dir.num; i++)
  5093. if (dir.direntry[i].name == pData->oldName)
  5094. {
  5095. if (pData->newPath.IsEmpty())
  5096. {
  5097. dir.direntry[i].name = pData->newName;
  5098. BOOL updated = FALSE;
  5099. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5100. {
  5101. updated = TRUE;
  5102. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5103. }
  5104. if (!updated)
  5105. if (WorkingDir.path == dir.path)
  5106. {
  5107. updated = TRUE;
  5108. m_pOwner->SetWorkingDir(&dir);
  5109. }
  5110. }
  5111. else
  5112. {
  5113. t_directory::t_direntry oldentry = dir.direntry[i];
  5114. for (int j = i+1; j < dir.num; j++)
  5115. {
  5116. dir.direntry[j-1] = dir.direntry[j];
  5117. }
  5118. dir.num--;
  5119. BOOL updated = FALSE;
  5120. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5121. {
  5122. updated = TRUE;
  5123. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5124. }
  5125. if (!updated)
  5126. if (WorkingDir.path == dir.path)
  5127. {
  5128. updated = TRUE;
  5129. m_pOwner->SetWorkingDir(&dir);
  5130. }
  5131. BOOL res = FALSE;
  5132. if (m_pDirectoryListing)
  5133. {
  5134. if (m_pDirectoryListing->path == pData->newPath)
  5135. {
  5136. dir = *m_pDirectoryListing;
  5137. res = TRUE;
  5138. }
  5139. }
  5140. t_directory WorkingDir;
  5141. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5142. if (!res && bFound)
  5143. if (WorkingDir.path == pData->newPath)
  5144. {
  5145. dir = WorkingDir;
  5146. res = TRUE;
  5147. }
  5148. if (res)
  5149. {
  5150. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
  5151. for (int i = 0; i < dir.num; i++)
  5152. direntry[i] = dir.direntry[i];
  5153. direntry[dir.num] = oldentry;
  5154. direntry[dir.num].name = pData->newName;
  5155. dir.num++;
  5156. delete [] dir.direntry;
  5157. dir.direntry = direntry;
  5158. BOOL updated = FALSE;
  5159. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5160. {
  5161. updated = TRUE;
  5162. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5163. }
  5164. if (!updated)
  5165. if (bFound && WorkingDir.path == dir.path)
  5166. {
  5167. updated = TRUE;
  5168. m_pOwner->SetWorkingDir(&dir);
  5169. }
  5170. }
  5171. }
  5172. break;
  5173. }
  5174. }
  5175. ResetOperation(FZ_REPLY_OK);
  5176. }
  5177. else
  5178. ResetOperation(FZ_REPLY_ERROR);
  5179. }
  5180. }
  5181. }
  5182. void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
  5183. {
  5184. DebugAssert(pData);
  5185. if (!m_pSslLayer)
  5186. return;
  5187. if (!m_Operation.nOpMode == CSMODE_CONNECT)
  5188. return;
  5189. m_bCheckForTimeout = TRUE;
  5190. m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
  5191. m_LastRecvTime = CTime::GetCurrentTime();
  5192. }
  5193. void CFtpControlSocket::OnTimer()
  5194. {
  5195. CheckForTimeout();
  5196. ResumeTransfer();
  5197. if (GetOptionVal(OPTION_KEEPALIVE))
  5198. {
  5199. if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
  5200. {
  5201. //Getting intervals for the Keep Alive feature
  5202. int low=GetOptionVal(OPTION_INTERVALLOW);
  5203. int diff=GetOptionVal(OPTION_INTERVALHIGH)-low;
  5204. //Choose a new delay
  5205. int delay=low+(rand()*diff)/RAND_MAX;
  5206. CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
  5207. if (span.GetTotalSeconds()>=delay)
  5208. SendKeepAliveCommand();
  5209. }
  5210. }
  5211. }
  5212. BOOL CFtpControlSocket::IsReady()
  5213. {
  5214. return !m_bKeepAliveActive;
  5215. }
  5216. void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
  5217. {
  5218. m_Operation.nOpMode=CSMODE_CHMOD;
  5219. CString str;
  5220. str.Format( L"SITE CHMOD %03d %s", nValue, path.FormatFilename(filename));
  5221. Send(str);
  5222. }
  5223. void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
  5224. {
  5225. switch (pData->nRequestType)
  5226. {
  5227. case FZ_ASYNCREQUEST_OVERWRITE:
  5228. SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
  5229. break;
  5230. case FZ_ASYNCREQUEST_VERIFYCERT:
  5231. SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
  5232. break;
  5233. case FZ_ASYNCREQUEST_NEEDPASS:
  5234. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5235. m_Operation.nOpState != CONNECT_NEEDPASS)
  5236. break;
  5237. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5238. {
  5239. DoClose();
  5240. break;
  5241. }
  5242. if (!nAction)
  5243. {
  5244. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5245. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5246. break;
  5247. }
  5248. else
  5249. {
  5250. m_bCheckForTimeout = TRUE;
  5251. m_CurrentServer.pass=((CNeedPassRequestData *)pData)->Password;
  5252. m_Operation.nOpState=((CNeedPassRequestData *)pData)->nOldOpState;
  5253. CLogonData *pLogonData = static_cast<CLogonData *>(m_Operation.pData);
  5254. pLogonData->waitForAsyncRequest = false;
  5255. pLogonData->gotPassword = true;
  5256. LogOnToServer(TRUE);
  5257. }
  5258. break;
  5259. #ifndef MPEXT_NO_GSS
  5260. case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
  5261. if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
  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. m_bCheckForTimeout = TRUE;
  5275. m_Operation.nOpState=-1;
  5276. LogOnToServer(TRUE);
  5277. break;
  5278. case FZ_ASYNCREQUEST_GSS_NEEDPASS:
  5279. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5280. m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
  5281. break;
  5282. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5283. {
  5284. DoClose();
  5285. break;
  5286. }
  5287. if (!nAction)
  5288. {
  5289. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5290. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5291. break;
  5292. }
  5293. else
  5294. {
  5295. m_bCheckForTimeout = TRUE;
  5296. m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
  5297. m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
  5298. LogOnToServer(TRUE);
  5299. }
  5300. break;
  5301. case FZ_ASYNCREQUEST_GSS_NEEDUSER:
  5302. if (m_Operation.nOpMode != CSMODE_CONNECT ||
  5303. m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
  5304. break;
  5305. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5306. {
  5307. DoClose();
  5308. break;
  5309. }
  5310. if (!nAction)
  5311. {
  5312. DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
  5313. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  5314. break;
  5315. }
  5316. else
  5317. {
  5318. m_bCheckForTimeout = TRUE;
  5319. m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
  5320. m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
  5321. LogOnToServer(TRUE);
  5322. }
  5323. break;
  5324. #endif
  5325. default:
  5326. LogMessage(FZ_LOG_WARNING, L"Unknown request reply %d", pData->nRequestType);
  5327. break;
  5328. }
  5329. }
  5330. int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  5331. {
  5332. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  5333. {
  5334. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  5335. {
  5336. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  5337. {
  5338. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  5339. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  5340. if (iter->pLayer == m_pProxyLayer)
  5341. LogMessage(FZ_LOG_INFO, L"Proxy layer changed state from %s to %s", state2Desc, state1Desc);
  5342. #ifndef MPEXT_NO_GSS
  5343. else if (iter->pLayer == m_pGssLayer)
  5344. LogMessage(FZ_LOG_INFO, L"m_pGssLayer changed state from %s to %s", state2Desc, state1Desc);
  5345. #endif
  5346. else if (iter->pLayer == m_pSslLayer)
  5347. {
  5348. delete [] iter->str;
  5349. LogMessage(FZ_LOG_INFO, L"TLS layer changed state from %s to %s", state2Desc, state1Desc);
  5350. }
  5351. else
  5352. LogMessage(FZ_LOG_INFO, L"Layer @ %d changed state from %s to %s", iter->pLayer, state2Desc, state1Desc);
  5353. }
  5354. }
  5355. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  5356. {
  5357. USES_CONVERSION;
  5358. if (iter->pLayer == m_pProxyLayer)
  5359. {
  5360. switch (iter->nParam1)
  5361. {
  5362. case PROXYERROR_NOERROR:
  5363. ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  5364. break;
  5365. case PROXYERROR_NOCONN:
  5366. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  5367. break;
  5368. case PROXYERROR_REQUESTFAILED:
  5369. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  5370. if (iter->str)
  5371. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  5372. break;
  5373. case PROXYERROR_AUTHTYPEUNKNOWN:
  5374. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  5375. break;
  5376. case PROXYERROR_AUTHFAILED:
  5377. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  5378. break;
  5379. case PROXYERROR_AUTHNOLOGON:
  5380. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  5381. break;
  5382. case PROXYERROR_CANTRESOLVEHOST:
  5383. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  5384. break;
  5385. default:
  5386. LogMessage(FZ_LOG_WARNING, L"Unknown proxy error" );
  5387. }
  5388. }
  5389. #ifndef MPEXT_NO_GSS
  5390. else if (iter->pLayer == m_pGssLayer)
  5391. {
  5392. switch (iter->nParam1)
  5393. {
  5394. case GSS_INFO:
  5395. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  5396. break;
  5397. case GSS_ERROR:
  5398. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  5399. break;
  5400. case GSS_COMMAND:
  5401. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  5402. break;
  5403. case GSS_REPLY:
  5404. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  5405. break;
  5406. }
  5407. }
  5408. #endif
  5409. else if (iter->pLayer == m_pSslLayer)
  5410. {
  5411. USES_CONVERSION;
  5412. switch (iter->nParam1)
  5413. {
  5414. case SSL_INFO:
  5415. switch (iter->nParam2)
  5416. {
  5417. case SSL_INFO_ESTABLISHED:
  5418. ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, FZ_LOG_STATUS);
  5419. if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  5420. {
  5421. LogOnToServer();
  5422. }
  5423. break;
  5424. }
  5425. break;
  5426. case SSL_FAILURE:
  5427. switch (iter->nParam2)
  5428. {
  5429. case SSL_FAILURE_UNKNOWN:
  5430. ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, FZ_LOG_ERROR);
  5431. break;
  5432. case SSL_FAILURE_ESTABLISH:
  5433. ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  5434. break;
  5435. case SSL_FAILURE_INITSSL:
  5436. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  5437. break;
  5438. case SSL_FAILURE_VERIFYCERT:
  5439. ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, FZ_LOG_ERROR);
  5440. break;
  5441. case SSL_FAILURE_CERTREJECTED:
  5442. ShowStatus(IDS_ERRORMSG_CERTREJECTED, FZ_LOG_ERROR);
  5443. m_bDidRejectCertificate = TRUE;
  5444. break;
  5445. }
  5446. TriggerEvent(FD_CLOSE);
  5447. break;
  5448. case SSL_VERIFY_CERT:
  5449. t_SslCertData *pData = new t_SslCertData;
  5450. LPTSTR CertError = NULL;
  5451. if (m_pSslLayer->GetPeerCertificateData(*pData, CertError))
  5452. {
  5453. CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
  5454. pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  5455. pRequestData->pCertData = pData;
  5456. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
  5457. {
  5458. delete pRequestData->pCertData;
  5459. delete pRequestData;
  5460. ResetOperation(FZ_REPLY_ERROR);
  5461. }
  5462. else
  5463. {
  5464. m_bCheckForTimeout = FALSE;
  5465. }
  5466. delete [] iter->str;
  5467. continue;
  5468. }
  5469. else
  5470. {
  5471. delete pData;
  5472. delete [] iter->str;
  5473. CString str;
  5474. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  5475. ShowStatus(str, FZ_LOG_ERROR);
  5476. ResetOperation(FZ_REPLY_ERROR);
  5477. continue;
  5478. }
  5479. break;
  5480. }
  5481. delete [] iter->str;
  5482. continue;
  5483. }
  5484. #ifndef MPEXT_NO_GSS
  5485. else
  5486. if (iter->pLayer == m_pGssLayer)
  5487. {
  5488. if (iter->nParam1 == GSS_AUTHCOMPLETE ||
  5489. iter->nParam1 == GSS_AUTHFAILED)
  5490. {
  5491. LogOnToServer(TRUE);
  5492. delete [] iter->str;
  5493. continue;
  5494. }
  5495. }
  5496. #endif
  5497. }
  5498. delete [] iter->str;
  5499. }
  5500. return 0;
  5501. }
  5502. _int64 CFtpControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  5503. {
  5504. int type = GetOptionVal(valType);
  5505. if ( type == 1)
  5506. return ( _int64)GetOptionVal(valValue) * 1024;
  5507. return ( _int64)1000000000000; // I hope that when there will be something with 1000GB/s then I'll change it :)
  5508. }
  5509. _int64 CFtpControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  5510. {
  5511. if (direction == download)
  5512. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  5513. else
  5514. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  5515. return ( _int64)1000000000000;
  5516. }
  5517. _int64 CFtpControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CFtpControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  5518. {
  5519. beenWaiting = false;
  5520. CTime nowTime = CTime::GetCurrentTime();
  5521. _int64 ableToRead = BUFSIZE;
  5522. if ( nowTime == curTime)
  5523. {
  5524. ableToRead = iter->nBytesAvailable;
  5525. if (ableToRead <= 0)
  5526. {
  5527. // we should wait till next second
  5528. nowTime = CTime::GetCurrentTime();
  5529. while (nowTime == curTime && !iter->nBytesAvailable)
  5530. {
  5531. if (beenWaiting)
  5532. {
  5533. //Check if there are other commands in the command queue.
  5534. MSG msg;
  5535. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  5536. {
  5537. LogMessage(FZ_LOG_INFO, L"Message waiting in queue, resuming later");
  5538. return 0;
  5539. }
  5540. }
  5541. m_SpeedLimitSync.Unlock();
  5542. Sleep(100);
  5543. m_SpeedLimitSync.Lock();
  5544. nowTime = CTime::GetCurrentTime();
  5545. beenWaiting = true;
  5546. // Since we didn't hold the critical section for some time, we have to renew the iterator
  5547. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5548. if (iter->pOwner == this)
  5549. break;
  5550. if (iter == m_InstanceList[direction].end())
  5551. return 0;
  5552. }
  5553. }
  5554. ableToRead = iter->nBytesAvailable;
  5555. }
  5556. if (nowTime != curTime)
  5557. {
  5558. if (ableToRead > 0)
  5559. ableToRead = 0;
  5560. curLimit = GetSpeedLimit(direction, curTime);
  5561. __int64 nMax = curLimit / m_InstanceList[direction].size();
  5562. _int64 nLeft = 0;
  5563. int nCount = 0;
  5564. std::list<t_ActiveList>::iterator iter2;
  5565. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5566. {
  5567. if (iter2->nBytesAvailable>0)
  5568. {
  5569. nLeft += iter2->nBytesAvailable;
  5570. iter2->nBytesTransferred = 1;
  5571. }
  5572. else
  5573. {
  5574. nCount++;
  5575. iter2->nBytesTransferred = 0;
  5576. }
  5577. iter2->nBytesAvailable = nMax;
  5578. }
  5579. if (nLeft && nCount)
  5580. {
  5581. nMax = nLeft / nCount;
  5582. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5583. {
  5584. if (!iter2->nBytesTransferred)
  5585. iter2->nBytesAvailable += nMax;
  5586. else
  5587. iter2->nBytesTransferred = 0;
  5588. }
  5589. }
  5590. ableToRead = iter->nBytesAvailable;
  5591. }
  5592. curTime = nowTime;
  5593. if (!nBufSize)
  5594. nBufSize = BUFSIZE;
  5595. if (ableToRead > nBufSize)
  5596. ableToRead = nBufSize;
  5597. return ableToRead;
  5598. }
  5599. _int64 CFtpControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  5600. {
  5601. m_SpeedLimitSync.Lock();
  5602. std::list<t_ActiveList>::iterator iter;
  5603. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5604. if (iter->pOwner == this)
  5605. break;
  5606. if (iter == m_InstanceList[direction].end())
  5607. {
  5608. t_ActiveList item;
  5609. CTime time = CTime::GetCurrentTime();
  5610. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  5611. item.nBytesTransferred = 0;
  5612. item.pOwner = this;
  5613. m_InstanceList[direction].push_back(item);
  5614. iter = m_InstanceList[direction].end();
  5615. iter--;
  5616. }
  5617. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  5618. m_SpeedLimitSync.Unlock();
  5619. return limit;
  5620. }
  5621. BOOL CFtpControlSocket::RemoveActiveTransfer()
  5622. {
  5623. BOOL bFound = FALSE;
  5624. m_SpeedLimitSync.Lock();
  5625. std::list<t_ActiveList>::iterator iter;
  5626. for (int i = 0; i < 2; i++)
  5627. {
  5628. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  5629. if (iter->pOwner == this)
  5630. {
  5631. m_InstanceList[i].erase(iter);
  5632. bFound = TRUE;
  5633. break;
  5634. }
  5635. }
  5636. m_SpeedLimitSync.Unlock();
  5637. return bFound;
  5638. }
  5639. BOOL CFtpControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  5640. {
  5641. m_SpeedLimitSync.Lock();
  5642. std::list<t_ActiveList>::iterator iter;
  5643. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5644. if (iter->pOwner == this)
  5645. {
  5646. if (iter->nBytesAvailable > nBytesTransferred)
  5647. iter->nBytesAvailable -= nBytesTransferred;
  5648. else
  5649. iter->nBytesAvailable = 0;
  5650. iter->nBytesTransferred += nBytesTransferred;
  5651. m_SpeedLimitSync.Unlock();
  5652. return TRUE;
  5653. }
  5654. m_SpeedLimitSync.Unlock();
  5655. return FALSE;
  5656. }
  5657. CString CFtpControlSocket::ConvertDomainName(CString domain)
  5658. {
  5659. USES_CONVERSION;
  5660. LPCWSTR buffer = T2CW(domain);
  5661. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  5662. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  5663. {
  5664. delete [] utf8;
  5665. LogMessage(FZ_LOG_WARNING, L"Could not convert domain name");
  5666. return domain;
  5667. }
  5668. char *output = 0;
  5669. output = strdup(utf8);
  5670. delete [] utf8;
  5671. CString result = A2T(output);
  5672. free(output);
  5673. return result;
  5674. }
  5675. void CFtpControlSocket::LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg)
  5676. {
  5677. LogMessageRaw(nMessageType, pMsg);
  5678. }
  5679. bool CFtpControlSocket::LoggingSocketMessage(int nMessageType)
  5680. {
  5681. return LoggingMessageType(nMessageType);
  5682. }
  5683. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
  5684. {
  5685. CServerPath realPath;
  5686. BOOL Result = ParsePwdReply(rawpwd, realPath);
  5687. if (Result)
  5688. {
  5689. m_pOwner->SetCurrentPath(realPath);
  5690. }
  5691. return Result;
  5692. }
  5693. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd, CServerPath & realPath)
  5694. {
  5695. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  5696. DebugAssert(pData);
  5697. int pos1 = rawpwd.Find(L'"');
  5698. int pos2 = rawpwd.ReverseFind(L'"');
  5699. if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
  5700. {
  5701. LogMessage(FZ_LOG_WARNING, L"No quoted path found, try using first token as path");
  5702. pos1 = rawpwd.Find(L' ');
  5703. if (pos1 != -1)
  5704. {
  5705. pos2 = rawpwd.Find(L' ', pos1 + 1);
  5706. if (pos2 == -1)
  5707. pos2 = rawpwd.GetLength();
  5708. }
  5709. if (pos1 == -1)
  5710. {
  5711. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5712. ResetOperation(FZ_REPLY_ERROR);
  5713. return FALSE;
  5714. }
  5715. }
  5716. rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
  5717. realPath = m_pOwner->GetCurrentPath();
  5718. realPath.SetServer(m_CurrentServer);
  5719. if (!realPath.SetPath(rawpwd))
  5720. {
  5721. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5722. ResetOperation(FZ_REPLY_ERROR);
  5723. return FALSE;
  5724. }
  5725. return TRUE;
  5726. }
  5727. void CFtpControlSocket::DiscardLine(CStringA line)
  5728. {
  5729. if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
  5730. {
  5731. line.MakeUpper();
  5732. while (line.Left(1) == " ")
  5733. {
  5734. line = line.Mid(1, line.GetLength() - 1);
  5735. }
  5736. #ifndef MPEXT_NO_ZLIB
  5737. if (line == "MODE Z" || line.Left(7) == "MODE Z ")
  5738. m_zlibSupported = true;
  5739. else
  5740. #endif
  5741. if (line == "UTF8" && m_CurrentServer.nUTF8 != 2)
  5742. m_bAnnouncesUTF8 = true;
  5743. else if (line == "CLNT" || line.Left(5) == "CLNT ")
  5744. m_hasClntCmd = true;
  5745. else if (line == "MLSD")
  5746. {
  5747. m_serverCapabilities.SetCapability(mlsd_command, yes);
  5748. }
  5749. else if (line == "MDTM")
  5750. {
  5751. m_serverCapabilities.SetCapability(mdtm_command, yes);
  5752. }
  5753. else if (line == "SIZE")
  5754. {
  5755. m_serverCapabilities.SetCapability(size_command, yes);
  5756. }
  5757. else if (line.Left(4) == "MLST")
  5758. {
  5759. USES_CONVERSION;
  5760. std::string facts;
  5761. if (line.GetLength() > 5)
  5762. {
  5763. facts = (LPCSTR)line.Mid(5, line.GetLength() - 5);
  5764. }
  5765. m_serverCapabilities.SetCapability(mlsd_command, yes, facts);
  5766. }
  5767. else if (line == "MFMT")
  5768. {
  5769. m_serverCapabilities.SetCapability(mfmt_command, yes);
  5770. }
  5771. }
  5772. else if (m_Operation.nOpMode == CSMODE_LISTFILE)
  5773. {
  5774. m_ListFile = line;
  5775. }
  5776. }
  5777. int CFtpControlSocket::FileTransferListState(bool get)
  5778. {
  5779. int Result;
  5780. if (GetOptionVal(OPTION_MPEXT_NOLIST) && !get)
  5781. {
  5782. Result = FILETRANSFER_TYPE;
  5783. }
  5784. else
  5785. {
  5786. Result = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  5787. }
  5788. return Result;
  5789. }
  5790. bool CFtpControlSocket::NeedModeCommand()
  5791. {
  5792. #ifdef MPEXT_NO_ZLIB
  5793. return false;
  5794. #else
  5795. bool useZlib;
  5796. if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
  5797. useZlib = GetOptionVal(OPTION_MODEZ_USE) != 0;
  5798. else
  5799. useZlib = GetOptionVal(OPTION_MODEZ_USE) > 1;
  5800. if (!m_useZlib && !m_zlibSupported)
  5801. return false;
  5802. return m_useZlib != useZlib;
  5803. #endif
  5804. }
  5805. bool CFtpControlSocket::NeedOptsCommand()
  5806. {
  5807. #ifndef MPEXT_NO_ZLIB
  5808. if (!m_useZlib)
  5809. #endif
  5810. return false;
  5811. #ifndef MPEXT_NO_ZLIB
  5812. return m_zlibLevel != GetOptionVal(OPTION_MODEZ_LEVEL);
  5813. #endif
  5814. }
  5815. CString CFtpControlSocket::GetReply()
  5816. {
  5817. if (m_RecvBuffer.empty())
  5818. return L"";
  5819. USES_CONVERSION;
  5820. LPCSTR line;
  5821. if ((m_Operation.nOpMode&CSMODE_LISTFILE) && (m_Operation.nOpState==LISTFILE_MLST) &&
  5822. (GetReplyCode() == 2))
  5823. {
  5824. // this is probably never used anyway
  5825. line = (LPCSTR)m_ListFile;
  5826. }
  5827. else
  5828. {
  5829. line = (LPCSTR)m_RecvBuffer.front();
  5830. }
  5831. if (m_bUTF8)
  5832. {
  5833. // convert from UTF-8 to ANSI
  5834. if (DetectUTF8Encoding(RawByteString(line)) == etANSI)
  5835. {
  5836. if (m_CurrentServer.nUTF8 != 1)
  5837. {
  5838. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  5839. m_bUTF8 = false;
  5840. }
  5841. return A2CT(line);
  5842. }
  5843. // convert from UTF-8 to ANSI
  5844. int len = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
  5845. if (!len)
  5846. {
  5847. m_RecvBuffer.pop_front();
  5848. if (m_RecvBuffer.empty())
  5849. m_RecvBuffer.push_back("");
  5850. return L"";
  5851. }
  5852. else
  5853. {
  5854. LPWSTR p1 = new WCHAR[len + 1];
  5855. MultiByteToWideChar(CP_UTF8, 0, line, -1 , (LPWSTR)p1, len + 1);
  5856. CString reply = W2CT(p1);
  5857. delete [] p1;
  5858. return reply;
  5859. }
  5860. }
  5861. else
  5862. return A2CT(line);
  5863. }
  5864. void CFtpControlSocket::OnSend(int nErrorCode)
  5865. {
  5866. if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
  5867. return;
  5868. int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
  5869. if (res == -1)
  5870. {
  5871. int Error = GetLastError();
  5872. if (Error != WSAEWOULDBLOCK)
  5873. {
  5874. LogError(Error);
  5875. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5876. DoClose();
  5877. }
  5878. return;
  5879. }
  5880. if (!res)
  5881. {
  5882. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5883. DoClose();
  5884. }
  5885. m_awaitsReply = true;
  5886. m_LastSendTime = CTime::GetCurrentTime();
  5887. if (res == m_sendBufferLen)
  5888. {
  5889. delete [] m_sendBuffer;
  5890. m_sendBuffer = 0;
  5891. m_sendBufferLen = 0;
  5892. }
  5893. else
  5894. {
  5895. char* tmp = new char[m_sendBufferLen - res];
  5896. memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
  5897. delete [] m_sendBuffer;
  5898. m_sendBuffer = tmp;
  5899. m_sendBufferLen -= res;
  5900. }
  5901. }
  5902. bool CFtpControlSocket::IsMisleadingListResponse()
  5903. {
  5904. // Some servers are broken. Instead of an empty listing, some MVS servers
  5905. // for example they return something "550 no members found"
  5906. // Other servers return "550 No files found."
  5907. CString retmsg = GetReply();
  5908. if (!retmsg.CompareNoCase(L"550 No members found."))
  5909. return true;
  5910. if (!retmsg.CompareNoCase(L"550 No data sets found."))
  5911. return true;
  5912. if (!retmsg.CompareNoCase(L"550 No files found."))
  5913. return true;
  5914. return false;
  5915. }
  5916. bool CFtpControlSocket::IsRoutableAddress(const CString & host)
  5917. {
  5918. USES_CONVERSION;
  5919. if (host.Left(3) == L"127" ||
  5920. host.Left(3) == L"10." ||
  5921. host.Left(7) == L"192.168" ||
  5922. host.Left(7) == L"169.254")
  5923. {
  5924. return false;
  5925. }
  5926. else if (host.Left(3) == L"172")
  5927. {
  5928. CString middle = host.Mid(4);
  5929. int pos = middle.Find(L".");
  5930. long part = atol(T2CA(middle.Left(pos)));
  5931. if ((part >= 16) && (part <= 31))
  5932. {
  5933. return false;
  5934. }
  5935. }
  5936. return true;
  5937. }
  5938. bool CFtpControlSocket::CheckForcePasvIp(CString & host)
  5939. {
  5940. bool result = true;
  5941. unsigned int tmpPort;
  5942. CString ahost;
  5943. switch (m_CurrentServer.iForcePasvIp)
  5944. {
  5945. case 0: // on
  5946. if (!GetPeerName(ahost, tmpPort))
  5947. {
  5948. // this should happen with proxy server only
  5949. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  5950. // do not know what to do, if there's FTP proxy
  5951. if (!logontype)
  5952. {
  5953. // this is a host name, not an IP, but it should not be a problem
  5954. ahost = m_CurrentServer.host;
  5955. }
  5956. }
  5957. if (ahost != host)
  5958. {
  5959. LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", ahost, host);
  5960. host = ahost;
  5961. }
  5962. break;
  5963. case 1: // off
  5964. // noop
  5965. break;
  5966. default: // auto
  5967. if (!GetPeerName(ahost, tmpPort))
  5968. {
  5969. LogMessage(FZ_LOG_PROGRESS, L"Error retrieving server address, cannot test if address is routable");
  5970. }
  5971. else if (!IsRoutableAddress(host) && IsRoutableAddress(ahost))
  5972. {
  5973. LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", host, ahost);
  5974. host = ahost;
  5975. }
  5976. break;
  5977. }
  5978. return result;
  5979. }
  5980. //---------------------------------------------------------------------------
  5981. ftp_capabilities_t TFTPServerCapabilities::GetCapability(ftp_capability_names_t Name)
  5982. {
  5983. t_cap tcap = FCapabilityMap[Name];
  5984. return tcap.cap;
  5985. }
  5986. ftp_capabilities_t TFTPServerCapabilities::GetCapabilityString(ftp_capability_names_t Name, std::string * Option)
  5987. {
  5988. t_cap tcap = FCapabilityMap[Name];
  5989. if (Option)
  5990. *Option = tcap.option;
  5991. return tcap.cap;
  5992. }
  5993. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap)
  5994. {
  5995. t_cap tcap = FCapabilityMap[Name];
  5996. tcap.cap = Cap;
  5997. tcap.number = 1;
  5998. FCapabilityMap[Name] = tcap;
  5999. }
  6000. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap, const std::string & Option)
  6001. {
  6002. t_cap tcap = FCapabilityMap[Name];
  6003. tcap.cap = Cap;
  6004. tcap.option = Option;
  6005. tcap.number = 0;
  6006. FCapabilityMap[Name] = tcap;
  6007. }