FtpControlSocket.cpp 183 KB

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