FtpControlSocket.cpp 157 KB

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