1
0

FtpControlSocket.cpp 185 KB

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