FtpControlSocket.cpp 183 KB

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