1
0

FtpControlSocket.cpp 176 KB

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