1
0

FtpControlSocket.cpp 183 KB

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