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