ftpserver.pl 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315
  1. #!/usr/bin/env perl
  2. #***************************************************************************
  3. # _ _ ____ _
  4. # Project ___| | | | _ \| |
  5. # / __| | | | |_) | |
  6. # | (__| |_| | _ <| |___
  7. # \___|\___/|_| \_\_____|
  8. #
  9. # Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
  10. #
  11. # This software is licensed as described in the file COPYING, which
  12. # you should have received as part of this distribution. The terms
  13. # are also available at https://curl.se/docs/copyright.html.
  14. #
  15. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. # copies of the Software, and permit persons to whom the Software is
  17. # furnished to do so, under the terms of the COPYING file.
  18. #
  19. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. # KIND, either express or implied.
  21. #
  22. ###########################################################################
  23. # This is a server designed for the curl test suite.
  24. #
  25. # In December 2009 we started remaking the server to support more protocols
  26. # that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP
  27. # it already supported since a long time. Note that it still only supports one
  28. # protocol per invoke. You need to start multiple servers to support multiple
  29. # protocols simultaneously.
  30. #
  31. # It is meant to exercise curl, it is not meant to be a fully working
  32. # or even very standard compliant server.
  33. #
  34. # You may optionally specify port on the command line, otherwise it'll
  35. # default to port 8921.
  36. #
  37. # All socket/network/TCP related stuff is done by the 'sockfilt' program.
  38. #
  39. BEGIN {
  40. push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
  41. push(@INC, ".");
  42. # sub second timestamping needs Time::HiRes
  43. eval {
  44. no warnings "all";
  45. require Time::HiRes;
  46. import Time::HiRes qw( gettimeofday );
  47. }
  48. }
  49. use strict;
  50. use warnings;
  51. use IPC::Open2;
  52. use Digest::MD5;
  53. require "getpart.pm";
  54. require "ftp.pm";
  55. require "directories.pm";
  56. use serverhelp qw(
  57. servername_str
  58. server_pidfilename
  59. server_logfilename
  60. mainsockf_pidfilename
  61. mainsockf_logfilename
  62. datasockf_pidfilename
  63. datasockf_logfilename
  64. );
  65. use sshhelp qw(
  66. exe_ext
  67. );
  68. #**********************************************************************
  69. # global vars...
  70. #
  71. my $verbose = 0; # set to 1 for debugging
  72. my $idstr = ""; # server instance string
  73. my $idnum = 1; # server instance number
  74. my $ipvnum = 4; # server IPv number (4 or 6)
  75. my $proto = 'ftp'; # default server protocol
  76. my $srcdir; # directory where ftpserver.pl is located
  77. my $srvrname; # server name for presentation purposes
  78. my $cwd_testno; # test case numbers extracted from CWD command
  79. my $testno = 0; # test case number (read from ftpserver.cmd)
  80. my $path = '.';
  81. my $logdir = $path .'/log';
  82. #**********************************************************************
  83. # global vars used for server address and primary listener port
  84. #
  85. my $port = 8921; # default primary listener port
  86. my $listenaddr = '127.0.0.1'; # default address for listener port
  87. #**********************************************************************
  88. # global vars used for file names
  89. #
  90. my $pidfile; # server pid file name
  91. my $portfile=".ftpserver.port"; # server port file name
  92. my $logfile; # server log file name
  93. my $mainsockf_pidfile; # pid file for primary connection sockfilt process
  94. my $mainsockf_logfile; # log file for primary connection sockfilt process
  95. my $datasockf_pidfile; # pid file for secondary connection sockfilt process
  96. my $datasockf_logfile; # log file for secondary connection sockfilt process
  97. #**********************************************************************
  98. # global vars used for server logs advisor read lock handling
  99. #
  100. my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
  101. my $serverlogslocked = 0;
  102. #**********************************************************************
  103. # global vars used for child processes PID tracking
  104. #
  105. my $sfpid; # PID for primary connection sockfilt process
  106. my $slavepid; # PID for secondary connection sockfilt process
  107. #**********************************************************************
  108. # global typeglob filehandle vars to read/write from/to sockfilters
  109. #
  110. local *SFREAD; # used to read from primary connection
  111. local *SFWRITE; # used to write to primary connection
  112. local *DREAD; # used to read from secondary connection
  113. local *DWRITE; # used to write to secondary connection
  114. my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
  115. #**********************************************************************
  116. # global vars which depend on server protocol selection
  117. #
  118. my %commandfunc; # protocol command specific function callbacks
  119. my %displaytext; # text returned to client before callback runs
  120. #**********************************************************************
  121. # global vars customized for each test from the server commands file
  122. #
  123. my $ctrldelay; # set if server should throttle ctrl stream
  124. my $datadelay; # set if server should throttle data stream
  125. my $retrweirdo; # set if ftp server should use RETRWEIRDO
  126. my $retrnosize; # set if ftp server should use RETRNOSIZE
  127. my $pasvbadip; # set if ftp server should use PASVBADIP
  128. my $nosave; # set if ftp server should not save uploaded data
  129. my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
  130. my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
  131. my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
  132. my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
  133. my $storeresp;
  134. my @capabilities; # set if server supports capability commands
  135. my @auth_mechs; # set if server supports authentication commands
  136. my %fulltextreply; #
  137. my %commandreply; #
  138. my %customcount; #
  139. my %delayreply; #
  140. #**********************************************************************
  141. # global variables for to test ftp wildcardmatching or other test that
  142. # need flexible LIST responses.. and corresponding files.
  143. # $ftptargetdir is keeping the fake "name" of LIST directory.
  144. #
  145. my $ftplistparserstate;
  146. my $ftptargetdir="";
  147. #**********************************************************************
  148. # global variables used when running a ftp server to keep state info
  149. # relative to the secondary or data sockfilt process. Values of these
  150. # variables should only be modified using datasockf_state() sub, given
  151. # that they are closely related and relationship is a bit awkward.
  152. #
  153. my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
  154. my $datasockf_mode = 'none'; # ['none','active','passive']
  155. my $datasockf_runs = 'no'; # ['no','yes']
  156. my $datasockf_conn = 'no'; # ['no','yes']
  157. #**********************************************************************
  158. # global vars used for signal handling
  159. #
  160. my $got_exit_signal = 0; # set if program should finish execution ASAP
  161. my $exit_signal; # first signal handled in exit_signal_handler
  162. #**********************************************************************
  163. # Mail related definitions
  164. #
  165. my $TEXT_PASSWORD = "secret";
  166. my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
  167. #**********************************************************************
  168. # exit_signal_handler will be triggered to indicate that the program
  169. # should finish its execution in a controlled way as soon as possible.
  170. # For now, program will also terminate from within this handler.
  171. #
  172. sub exit_signal_handler {
  173. my $signame = shift;
  174. # For now, simply mimic old behavior.
  175. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  176. unlink($pidfile);
  177. unlink($portfile);
  178. if($serverlogslocked) {
  179. $serverlogslocked = 0;
  180. clear_advisor_read_lock($SERVERLOGS_LOCK);
  181. }
  182. exit;
  183. }
  184. #**********************************************************************
  185. # logmsg is general message logging subroutine for our test servers.
  186. #
  187. sub logmsg {
  188. my $now;
  189. # sub second timestamping needs Time::HiRes
  190. if($Time::HiRes::VERSION) {
  191. my ($seconds, $usec) = gettimeofday();
  192. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  193. localtime($seconds);
  194. $now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
  195. }
  196. else {
  197. my $seconds = time();
  198. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  199. localtime($seconds);
  200. $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
  201. }
  202. if(open(LOGFILEFH, ">>$logfile")) {
  203. print LOGFILEFH $now;
  204. print LOGFILEFH @_;
  205. close(LOGFILEFH);
  206. }
  207. }
  208. sub ftpmsg {
  209. # append to the server.input file
  210. open(INPUT, ">>log/server$idstr.input") ||
  211. logmsg "failed to open log/server$idstr.input\n";
  212. print INPUT @_;
  213. close(INPUT);
  214. # use this, open->print->close system only to make the file
  215. # open as little as possible, to make the test suite run
  216. # better on windows/cygwin
  217. }
  218. #**********************************************************************
  219. # eXsysread is a wrapper around perl's sysread() function. This will
  220. # repeat the call to sysread() until it has actually read the complete
  221. # number of requested bytes or an unrecoverable condition occurs.
  222. # On success returns a positive value, the number of bytes requested.
  223. # On failure or timeout returns zero.
  224. #
  225. sub eXsysread {
  226. my $FH = shift;
  227. my $scalar = shift;
  228. my $nbytes = shift;
  229. my $timeout = shift; # A zero timeout disables eXsysread() time limit
  230. #
  231. my $time_limited = 0;
  232. my $timeout_rest = 0;
  233. my $start_time = 0;
  234. my $nread = 0;
  235. my $rc;
  236. $$scalar = "";
  237. if((not defined $nbytes) || ($nbytes < 1)) {
  238. logmsg "Error: eXsysread() failure: " .
  239. "length argument must be positive\n";
  240. return 0;
  241. }
  242. if((not defined $timeout) || ($timeout < 0)) {
  243. logmsg "Error: eXsysread() failure: " .
  244. "timeout argument must be zero or positive\n";
  245. return 0;
  246. }
  247. if($timeout > 0) {
  248. # caller sets eXsysread() time limit
  249. $time_limited = 1;
  250. $timeout_rest = $timeout;
  251. $start_time = int(time());
  252. }
  253. while($nread < $nbytes) {
  254. if($time_limited) {
  255. eval {
  256. local $SIG{ALRM} = sub { die "alarm\n"; };
  257. alarm $timeout_rest;
  258. $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
  259. alarm 0;
  260. };
  261. $timeout_rest = $timeout - (int(time()) - $start_time);
  262. if($timeout_rest < 1) {
  263. logmsg "Error: eXsysread() failure: timed out\n";
  264. return 0;
  265. }
  266. }
  267. else {
  268. $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
  269. }
  270. if($got_exit_signal) {
  271. logmsg "Error: eXsysread() failure: signalled to die\n";
  272. return 0;
  273. }
  274. if(not defined $rc) {
  275. if($!{EINTR}) {
  276. logmsg "Warning: retrying sysread() interrupted system call\n";
  277. next;
  278. }
  279. if($!{EAGAIN}) {
  280. logmsg "Warning: retrying sysread() due to EAGAIN\n";
  281. next;
  282. }
  283. if($!{EWOULDBLOCK}) {
  284. logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
  285. next;
  286. }
  287. logmsg "Error: sysread() failure: $!\n";
  288. return 0;
  289. }
  290. if($rc < 0) {
  291. logmsg "Error: sysread() failure: returned negative value $rc\n";
  292. return 0;
  293. }
  294. if($rc == 0) {
  295. logmsg "Error: sysread() failure: read zero bytes\n";
  296. return 0;
  297. }
  298. $nread += $rc;
  299. }
  300. return $nread;
  301. }
  302. #**********************************************************************
  303. # read_mainsockf attempts to read the given amount of output from the
  304. # sockfilter which is in use for the main or primary connection. This
  305. # reads untranslated sockfilt lingo which may hold data read from the
  306. # main or primary socket. On success returns 1, otherwise zero.
  307. #
  308. sub read_mainsockf {
  309. my $scalar = shift;
  310. my $nbytes = shift;
  311. my $timeout = shift; # Optional argument, if zero blocks indefinitely
  312. my $FH = \*SFREAD;
  313. if(not defined $timeout) {
  314. $timeout = $sockfilt_timeout + ($nbytes >> 12);
  315. }
  316. if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
  317. my ($fcaller, $lcaller) = (caller)[1,2];
  318. logmsg "Error: read_mainsockf() failure at $fcaller " .
  319. "line $lcaller. Due to eXsysread() failure\n";
  320. return 0;
  321. }
  322. return 1;
  323. }
  324. #**********************************************************************
  325. # read_datasockf attempts to read the given amount of output from the
  326. # sockfilter which is in use for the data or secondary connection. This
  327. # reads untranslated sockfilt lingo which may hold data read from the
  328. # data or secondary socket. On success returns 1, otherwise zero.
  329. #
  330. sub read_datasockf {
  331. my $scalar = shift;
  332. my $nbytes = shift;
  333. my $timeout = shift; # Optional argument, if zero blocks indefinitely
  334. my $FH = \*DREAD;
  335. if(not defined $timeout) {
  336. $timeout = $sockfilt_timeout + ($nbytes >> 12);
  337. }
  338. if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
  339. my ($fcaller, $lcaller) = (caller)[1,2];
  340. logmsg "Error: read_datasockf() failure at $fcaller " .
  341. "line $lcaller. Due to eXsysread() failure\n";
  342. return 0;
  343. }
  344. return 1;
  345. }
  346. sub sysread_or_die {
  347. my $FH = shift;
  348. my $scalar = shift;
  349. my $length = shift;
  350. my $fcaller;
  351. my $lcaller;
  352. my $result;
  353. $result = sysread($$FH, $$scalar, $length);
  354. if(not defined $result) {
  355. ($fcaller, $lcaller) = (caller)[1,2];
  356. logmsg "Failed to read input\n";
  357. logmsg "Error: $srvrname server, sysread error: $!\n";
  358. logmsg "Exited from sysread_or_die() at $fcaller " .
  359. "line $lcaller. $srvrname server, sysread error: $!\n";
  360. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  361. unlink($pidfile);
  362. unlink($portfile);
  363. if($serverlogslocked) {
  364. $serverlogslocked = 0;
  365. clear_advisor_read_lock($SERVERLOGS_LOCK);
  366. }
  367. exit;
  368. }
  369. elsif($result == 0) {
  370. ($fcaller, $lcaller) = (caller)[1,2];
  371. logmsg "Failed to read input\n";
  372. logmsg "Error: $srvrname server, read zero\n";
  373. logmsg "Exited from sysread_or_die() at $fcaller " .
  374. "line $lcaller. $srvrname server, read zero\n";
  375. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  376. unlink($pidfile);
  377. unlink($portfile);
  378. if($serverlogslocked) {
  379. $serverlogslocked = 0;
  380. clear_advisor_read_lock($SERVERLOGS_LOCK);
  381. }
  382. exit;
  383. }
  384. return $result;
  385. }
  386. sub startsf {
  387. my $mainsockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  388. "--ipv$ipvnum --port $port " .
  389. "--pidfile \"$mainsockf_pidfile\" " .
  390. "--portfile \"$portfile\" " .
  391. "--logfile \"$mainsockf_logfile\"";
  392. $sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
  393. print STDERR "$mainsockfcmd\n" if($verbose);
  394. print SFWRITE "PING\n";
  395. my $pong;
  396. sysread_or_die(\*SFREAD, \$pong, 5);
  397. if($pong !~ /^PONG/) {
  398. logmsg "Failed sockfilt command: $mainsockfcmd\n";
  399. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  400. unlink($pidfile);
  401. unlink($portfile);
  402. if($serverlogslocked) {
  403. $serverlogslocked = 0;
  404. clear_advisor_read_lock($SERVERLOGS_LOCK);
  405. }
  406. die "Failed to start sockfilt!";
  407. }
  408. }
  409. #**********************************************************************
  410. # Returns the given test's reply data
  411. #
  412. sub getreplydata {
  413. my ($num) = @_;
  414. my $testpart = "";
  415. $num =~ s/^([^0-9]*)//;
  416. if($num > 10000) {
  417. $testpart = $num % 10000;
  418. }
  419. my @data = getpart("reply", "data$testpart");
  420. if((!@data) && ($testpart ne "")) {
  421. @data = getpart("reply", "data");
  422. }
  423. return @data;
  424. }
  425. sub sockfilt {
  426. my $l;
  427. foreach $l (@_) {
  428. printf SFWRITE "DATA\n%04x\n", length($l);
  429. print SFWRITE $l;
  430. }
  431. }
  432. sub sockfiltsecondary {
  433. my $l;
  434. foreach $l (@_) {
  435. printf DWRITE "DATA\n%04x\n", length($l);
  436. print DWRITE $l;
  437. }
  438. }
  439. #**********************************************************************
  440. # Send data to the client on the control stream, which happens to be plain
  441. # stdout.
  442. #
  443. sub sendcontrol {
  444. if(!$ctrldelay) {
  445. # spit it all out at once
  446. sockfilt @_;
  447. }
  448. else {
  449. my $a = join("", @_);
  450. my @a = split("", $a);
  451. for(@a) {
  452. sockfilt $_;
  453. portable_sleep(0.01);
  454. }
  455. }
  456. my $log;
  457. foreach $log (@_) {
  458. my $l = $log;
  459. $l =~ s/\r/[CR]/g;
  460. $l =~ s/\n/[LF]/g;
  461. logmsg "> \"$l\"\n";
  462. }
  463. }
  464. #**********************************************************************
  465. # Send data to the FTP client on the data stream when data connection
  466. # is actually established. Given that this sub should only be called
  467. # when a data connection is supposed to be established, calling this
  468. # without a data connection is an indication of weak logic somewhere.
  469. #
  470. sub senddata {
  471. my $l;
  472. if($datasockf_conn eq 'no') {
  473. logmsg "WARNING: Detected data sending attempt without DATA channel\n";
  474. foreach $l (@_) {
  475. logmsg "WARNING: Data swallowed: $l\n"
  476. }
  477. return;
  478. }
  479. foreach $l (@_) {
  480. if(!$datadelay) {
  481. # spit it all out at once
  482. sockfiltsecondary $l;
  483. }
  484. else {
  485. # pause between each byte
  486. for (split(//,$l)) {
  487. sockfiltsecondary $_;
  488. portable_sleep(0.01);
  489. }
  490. }
  491. }
  492. }
  493. #**********************************************************************
  494. # protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
  495. # for the given protocol. References to protocol command callbacks are
  496. # stored in 'commandfunc' hash, and text which will be returned to the
  497. # client before the command callback runs is stored in 'displaytext'.
  498. #
  499. sub protocolsetup {
  500. my $proto = $_[0];
  501. if($proto eq 'ftp') {
  502. %commandfunc = (
  503. 'PORT' => \&PORT_ftp,
  504. 'EPRT' => \&PORT_ftp,
  505. 'LIST' => \&LIST_ftp,
  506. 'NLST' => \&NLST_ftp,
  507. 'PASV' => \&PASV_ftp,
  508. 'CWD' => \&CWD_ftp,
  509. 'PWD' => \&PWD_ftp,
  510. 'EPSV' => \&PASV_ftp,
  511. 'RETR' => \&RETR_ftp,
  512. 'SIZE' => \&SIZE_ftp,
  513. 'REST' => \&REST_ftp,
  514. 'STOR' => \&STOR_ftp,
  515. 'APPE' => \&STOR_ftp, # append looks like upload
  516. 'MDTM' => \&MDTM_ftp,
  517. );
  518. %displaytext = (
  519. 'USER' => '331 We are happy you popped in!',
  520. 'PASS' => '230 Welcome you silly person',
  521. 'PORT' => '200 You said PORT - I say FINE',
  522. 'TYPE' => '200 I modify TYPE as you wanted',
  523. 'LIST' => '150 here comes a directory',
  524. 'NLST' => '150 here comes a directory',
  525. 'CWD' => '250 CWD command successful.',
  526. 'SYST' => '215 UNIX Type: L8', # just fake something
  527. 'QUIT' => '221 bye bye baby', # just reply something
  528. 'MKD' => '257 Created your requested directory',
  529. 'REST' => '350 Yeah yeah we set it there for you',
  530. 'DELE' => '200 OK OK OK whatever you say',
  531. 'RNFR' => '350 Received your order. Please provide more',
  532. 'RNTO' => '250 Ok, thanks. File renaming completed.',
  533. 'NOOP' => '200 Yes, I\'m very good at doing nothing.',
  534. 'PBSZ' => '500 PBSZ not implemented',
  535. 'PROT' => '500 PROT not implemented',
  536. 'welcome' => join("",
  537. '220- _ _ ____ _ '."\r\n",
  538. '220- ___| | | | _ \| | '."\r\n",
  539. '220- / __| | | | |_) | | '."\r\n",
  540. '220- | (__| |_| | _ {| |___ '."\r\n",
  541. '220 \___|\___/|_| \_\_____|'."\r\n")
  542. );
  543. }
  544. elsif($proto eq 'pop3') {
  545. %commandfunc = (
  546. 'APOP' => \&APOP_pop3,
  547. 'AUTH' => \&AUTH_pop3,
  548. 'CAPA' => \&CAPA_pop3,
  549. 'DELE' => \&DELE_pop3,
  550. 'LIST' => \&LIST_pop3,
  551. 'NOOP' => \&NOOP_pop3,
  552. 'PASS' => \&PASS_pop3,
  553. 'QUIT' => \&QUIT_pop3,
  554. 'RETR' => \&RETR_pop3,
  555. 'RSET' => \&RSET_pop3,
  556. 'STAT' => \&STAT_pop3,
  557. 'TOP' => \&TOP_pop3,
  558. 'UIDL' => \&UIDL_pop3,
  559. 'USER' => \&USER_pop3,
  560. );
  561. %displaytext = (
  562. 'welcome' => join("",
  563. ' _ _ ____ _ '."\r\n",
  564. ' ___| | | | _ \| | '."\r\n",
  565. ' / __| | | | |_) | | '."\r\n",
  566. ' | (__| |_| | _ {| |___ '."\r\n",
  567. ' \___|\___/|_| \_\_____|'."\r\n",
  568. '+OK curl POP3 server ready to serve '."\r\n")
  569. );
  570. }
  571. elsif($proto eq 'imap') {
  572. %commandfunc = (
  573. 'APPEND' => \&APPEND_imap,
  574. 'CAPABILITY' => \&CAPABILITY_imap,
  575. 'CHECK' => \&CHECK_imap,
  576. 'CLOSE' => \&CLOSE_imap,
  577. 'COPY' => \&COPY_imap,
  578. 'CREATE' => \&CREATE_imap,
  579. 'DELETE' => \&DELETE_imap,
  580. 'EXAMINE' => \&EXAMINE_imap,
  581. 'EXPUNGE' => \&EXPUNGE_imap,
  582. 'FETCH' => \&FETCH_imap,
  583. 'LIST' => \&LIST_imap,
  584. 'LSUB' => \&LSUB_imap,
  585. 'LOGIN' => \&LOGIN_imap,
  586. 'LOGOUT' => \&LOGOUT_imap,
  587. 'NOOP' => \&NOOP_imap,
  588. 'RENAME' => \&RENAME_imap,
  589. 'SEARCH' => \&SEARCH_imap,
  590. 'SELECT' => \&SELECT_imap,
  591. 'STATUS' => \&STATUS_imap,
  592. 'STORE' => \&STORE_imap,
  593. 'UID' => \&UID_imap,
  594. );
  595. %displaytext = (
  596. 'welcome' => join("",
  597. ' _ _ ____ _ '."\r\n",
  598. ' ___| | | | _ \| | '."\r\n",
  599. ' / __| | | | |_) | | '."\r\n",
  600. ' | (__| |_| | _ {| |___ '."\r\n",
  601. ' \___|\___/|_| \_\_____|'."\r\n",
  602. '* OK curl IMAP server ready to serve'."\r\n")
  603. );
  604. }
  605. elsif($proto eq 'smtp') {
  606. %commandfunc = (
  607. 'DATA' => \&DATA_smtp,
  608. 'EHLO' => \&EHLO_smtp,
  609. 'EXPN' => \&EXPN_smtp,
  610. 'HELO' => \&HELO_smtp,
  611. 'HELP' => \&HELP_smtp,
  612. 'MAIL' => \&MAIL_smtp,
  613. 'NOOP' => \&NOOP_smtp,
  614. 'RSET' => \&RSET_smtp,
  615. 'RCPT' => \&RCPT_smtp,
  616. 'VRFY' => \&VRFY_smtp,
  617. 'QUIT' => \&QUIT_smtp,
  618. );
  619. %displaytext = (
  620. 'welcome' => join("",
  621. '220- _ _ ____ _ '."\r\n",
  622. '220- ___| | | | _ \| | '."\r\n",
  623. '220- / __| | | | |_) | | '."\r\n",
  624. '220- | (__| |_| | _ {| |___ '."\r\n",
  625. '220 \___|\___/|_| \_\_____|'."\r\n")
  626. );
  627. }
  628. }
  629. sub close_dataconn {
  630. my ($closed)=@_; # non-zero if already disconnected
  631. my $datapid = processexists($datasockf_pidfile);
  632. logmsg "=====> Closing $datasockf_mode DATA connection...\n";
  633. if(!$closed) {
  634. if($datapid > 0) {
  635. logmsg "Server disconnects $datasockf_mode DATA connection\n";
  636. print DWRITE "DISC\n";
  637. my $i;
  638. sysread DREAD, $i, 5;
  639. logmsg "Server disconnected $datasockf_mode DATA connection\n";
  640. }
  641. else {
  642. logmsg "Server finds $datasockf_mode DATA connection already ".
  643. "disconnected\n";
  644. }
  645. }
  646. else {
  647. logmsg "Server knows $datasockf_mode DATA connection is already ".
  648. "disconnected\n";
  649. }
  650. if($datapid > 0) {
  651. logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
  652. "(pid $datapid)\n";
  653. print DWRITE "QUIT\n";
  654. pidwait($datapid, 0);
  655. unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
  656. logmsg "DATA sockfilt for $datasockf_mode data channel quit ".
  657. "(pid $datapid)\n";
  658. }
  659. else {
  660. logmsg "DATA sockfilt for $datasockf_mode data channel already ".
  661. "dead\n";
  662. }
  663. logmsg "=====> Closed $datasockf_mode DATA connection\n";
  664. datasockf_state('STOPPED');
  665. }
  666. ################
  667. ################ SMTP commands
  668. ################
  669. # The type of server (SMTP or ESMTP)
  670. my $smtp_type;
  671. # The client (which normally contains the test number)
  672. my $smtp_client;
  673. sub EHLO_smtp {
  674. my ($client) = @_;
  675. my @data;
  676. # TODO: Get the IP address of the client connection to use in the
  677. # EHLO response when the client doesn't specify one but for now use
  678. # 127.0.0.1
  679. if(!$client) {
  680. $client = "[127.0.0.1]";
  681. }
  682. # Set the server type to ESMTP
  683. $smtp_type = "ESMTP";
  684. # Calculate the EHLO response
  685. push @data, "$smtp_type pingpong test server Hello $client";
  686. if((@capabilities) || (@auth_mechs)) {
  687. my $mechs;
  688. for my $c (@capabilities) {
  689. push @data, $c;
  690. }
  691. for my $am (@auth_mechs) {
  692. if(!$mechs) {
  693. $mechs = "$am";
  694. }
  695. else {
  696. $mechs .= " $am";
  697. }
  698. }
  699. if($mechs) {
  700. push @data, "AUTH $mechs";
  701. }
  702. }
  703. # Send the EHLO response
  704. for(my $i = 0; $i < @data; $i++) {
  705. my $d = $data[$i];
  706. if($i < @data - 1) {
  707. sendcontrol "250-$d\r\n";
  708. }
  709. else {
  710. sendcontrol "250 $d\r\n";
  711. }
  712. }
  713. # Store the client (as it may contain the test number)
  714. $smtp_client = $client;
  715. return 0;
  716. }
  717. sub HELO_smtp {
  718. my ($client) = @_;
  719. # TODO: Get the IP address of the client connection to use in the HELO
  720. # response when the client doesn't specify one but for now use 127.0.0.1
  721. if(!$client) {
  722. $client = "[127.0.0.1]";
  723. }
  724. # Set the server type to SMTP
  725. $smtp_type = "SMTP";
  726. # Send the HELO response
  727. sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n";
  728. # Store the client (as it may contain the test number)
  729. $smtp_client = $client;
  730. return 0;
  731. }
  732. sub MAIL_smtp {
  733. my ($args) = @_;
  734. logmsg "MAIL_smtp got $args\n";
  735. if (!$args) {
  736. sendcontrol "501 Unrecognized parameter\r\n";
  737. }
  738. else {
  739. my $from;
  740. my $size;
  741. my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
  742. my @elements = split(/ /, $args);
  743. # Get the FROM and SIZE parameters
  744. for my $e (@elements) {
  745. if($e =~ /^FROM:(.*)$/) {
  746. $from = $1;
  747. }
  748. elsif($e =~ /^SIZE=(\d+)$/) {
  749. $size = $1;
  750. }
  751. }
  752. # this server doesn't "validate" MAIL FROM addresses
  753. if (length($from)) {
  754. my @found;
  755. my $valid = 1;
  756. # Check the capabilities for SIZE and if the specified size is
  757. # greater than the message size then reject it
  758. if (@found = grep /^SIZE (\d+)$/, @capabilities) {
  759. if ($found[0] =~ /^SIZE (\d+)$/) {
  760. if ($size > $1) {
  761. $valid = 0;
  762. }
  763. }
  764. }
  765. if(!$valid) {
  766. sendcontrol "552 Message size too large\r\n";
  767. }
  768. else {
  769. sendcontrol "250 Sender OK\r\n";
  770. }
  771. }
  772. else {
  773. sendcontrol "501 Invalid address\r\n";
  774. }
  775. }
  776. return 0;
  777. }
  778. sub RCPT_smtp {
  779. my ($args) = @_;
  780. logmsg "RCPT_smtp got $args\n";
  781. # Get the TO parameter
  782. if($args !~ /^TO:(.*)/) {
  783. sendcontrol "501 Unrecognized parameter\r\n";
  784. }
  785. else {
  786. my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
  787. my $to = $1;
  788. # Validate the to address (only a valid email address inside <> is
  789. # allowed, such as <user@example.com>)
  790. if ((!$smtputf8 && $to =~
  791. /^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
  792. ($smtputf8 && $to =~
  793. /^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
  794. sendcontrol "250 Recipient OK\r\n";
  795. }
  796. else {
  797. sendcontrol "501 Invalid address\r\n";
  798. }
  799. }
  800. return 0;
  801. }
  802. sub DATA_smtp {
  803. my ($args) = @_;
  804. if ($args) {
  805. sendcontrol "501 Unrecognized parameter\r\n";
  806. }
  807. elsif ($smtp_client !~ /^(\d*)$/) {
  808. sendcontrol "501 Invalid arguments\r\n";
  809. }
  810. else {
  811. sendcontrol "354 Show me the mail\r\n";
  812. my $testno = $smtp_client;
  813. my $filename = "log/upload.$testno";
  814. logmsg "Store test number $testno in $filename\n";
  815. open(FILE, ">$filename") ||
  816. return 0; # failed to open output
  817. my $line;
  818. my $ulsize=0;
  819. my $disc=0;
  820. my $raw;
  821. while (5 == (sysread \*SFREAD, $line, 5)) {
  822. if($line eq "DATA\n") {
  823. my $i;
  824. my $eob;
  825. sysread \*SFREAD, $i, 5;
  826. my $size = 0;
  827. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  828. $size = hex($1);
  829. }
  830. read_mainsockf(\$line, $size);
  831. $ulsize += $size;
  832. print FILE $line if(!$nosave);
  833. $raw .= $line;
  834. if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) {
  835. # end of data marker!
  836. $eob = 1;
  837. }
  838. logmsg "> Appending $size bytes to file\n";
  839. if($eob) {
  840. logmsg "Found SMTP EOB marker\n";
  841. last;
  842. }
  843. }
  844. elsif($line eq "DISC\n") {
  845. # disconnect!
  846. $disc=1;
  847. last;
  848. }
  849. else {
  850. logmsg "No support for: $line";
  851. last;
  852. }
  853. }
  854. if($nosave) {
  855. print FILE "$ulsize bytes would've been stored here\n";
  856. }
  857. close(FILE);
  858. logmsg "received $ulsize bytes upload\n";
  859. sendcontrol "250 OK, data received!\r\n";
  860. }
  861. return 0;
  862. }
  863. sub NOOP_smtp {
  864. my ($args) = @_;
  865. if($args) {
  866. sendcontrol "501 Unrecognized parameter\r\n";
  867. }
  868. else {
  869. sendcontrol "250 OK\r\n";
  870. }
  871. return 0;
  872. }
  873. sub RSET_smtp {
  874. my ($args) = @_;
  875. if($args) {
  876. sendcontrol "501 Unrecognized parameter\r\n";
  877. }
  878. else {
  879. sendcontrol "250 Resetting\r\n";
  880. }
  881. return 0;
  882. }
  883. sub HELP_smtp {
  884. my ($args) = @_;
  885. # One argument is optional
  886. if($args) {
  887. logmsg "HELP_smtp got $args\n";
  888. }
  889. if($smtp_client eq "verifiedserver") {
  890. # This is the secret command that verifies that this actually is
  891. # the curl test server
  892. sendcontrol "214 WE ROOLZ: $$\r\n";
  893. if($verbose) {
  894. print STDERR "FTPD: We returned proof we are the test server\n";
  895. }
  896. logmsg "return proof we are we\n";
  897. }
  898. else {
  899. sendcontrol "214-This server supports the following commands:\r\n";
  900. if(@auth_mechs) {
  901. sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP AUTH\r\n";
  902. }
  903. else {
  904. sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP\r\n";
  905. }
  906. }
  907. return 0;
  908. }
  909. sub VRFY_smtp {
  910. my ($args) = @_;
  911. my ($username, $address) = split(/ /, $args, 2);
  912. logmsg "VRFY_smtp got $args\n";
  913. if($username eq "") {
  914. sendcontrol "501 Unrecognized parameter\r\n";
  915. }
  916. else {
  917. my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
  918. # Validate the username (only a valid local or external username is
  919. # allowed, such as user or user@example.com)
  920. if ((!$smtputf8 && $username =~
  921. /^([a-zA-Z0-9._%+-]+)(\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4}))?$/) ||
  922. ($smtputf8 && $username =~
  923. /^([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)(\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4}))?$/)) {
  924. my @data = getreplydata($smtp_client);
  925. if(!@data) {
  926. if ($username !~
  927. /^([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})$/) {
  928. push @data, "250 <$username\@example.com>\r\n"
  929. }
  930. else {
  931. push @data, "250 <$username>\r\n"
  932. }
  933. }
  934. for my $d (@data) {
  935. sendcontrol $d;
  936. }
  937. }
  938. else {
  939. sendcontrol "501 Invalid address\r\n";
  940. }
  941. }
  942. return 0;
  943. }
  944. sub EXPN_smtp {
  945. my ($list_name) = @_;
  946. logmsg "EXPN_smtp got $list_name\n";
  947. if(!$list_name) {
  948. sendcontrol "501 Unrecognized parameter\r\n";
  949. }
  950. else {
  951. my @data = getreplydata($smtp_client);
  952. for my $d (@data) {
  953. sendcontrol $d;
  954. }
  955. }
  956. return 0;
  957. }
  958. sub QUIT_smtp {
  959. sendcontrol "221 curl $smtp_type server signing off\r\n";
  960. return 0;
  961. }
  962. # What was deleted by IMAP STORE / POP3 DELE commands
  963. my @deleted;
  964. ################
  965. ################ IMAP commands
  966. ################
  967. # global to allow the command functions to read it
  968. my $cmdid;
  969. # what was picked by SELECT
  970. my $selected;
  971. # Any IMAP parameter can come in escaped and in double quotes.
  972. # This function is dumb (so far) and just removes the quotes if present.
  973. sub fix_imap_params {
  974. foreach (@_) {
  975. $_ = $1 if /^"(.*)"$/;
  976. }
  977. }
  978. sub CAPABILITY_imap {
  979. if((!@capabilities) && (!@auth_mechs)) {
  980. sendcontrol "$cmdid BAD Command\r\n";
  981. }
  982. else {
  983. my $data;
  984. # Calculate the CAPABILITY response
  985. $data = "* CAPABILITY IMAP4";
  986. for my $c (@capabilities) {
  987. $data .= " $c";
  988. }
  989. for my $am (@auth_mechs) {
  990. $data .= " AUTH=$am";
  991. }
  992. $data .= " pingpong test server\r\n";
  993. # Send the CAPABILITY response
  994. sendcontrol $data;
  995. sendcontrol "$cmdid OK CAPABILITY completed\r\n";
  996. }
  997. return 0;
  998. }
  999. sub LOGIN_imap {
  1000. my ($args) = @_;
  1001. my ($user, $password) = split(/ /, $args, 2);
  1002. fix_imap_params($user, $password);
  1003. logmsg "LOGIN_imap got $args\n";
  1004. if ($user eq "") {
  1005. sendcontrol "$cmdid BAD Command Argument\r\n";
  1006. }
  1007. else {
  1008. sendcontrol "$cmdid OK LOGIN completed\r\n";
  1009. }
  1010. return 0;
  1011. }
  1012. sub SELECT_imap {
  1013. my ($mailbox) = @_;
  1014. fix_imap_params($mailbox);
  1015. logmsg "SELECT_imap got test $mailbox\n";
  1016. if($mailbox eq "") {
  1017. sendcontrol "$cmdid BAD Command Argument\r\n";
  1018. }
  1019. else {
  1020. # Example from RFC 3501, 6.3.1. SELECT Command
  1021. sendcontrol "* 172 EXISTS\r\n";
  1022. sendcontrol "* 1 RECENT\r\n";
  1023. sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n";
  1024. sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
  1025. sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
  1026. sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
  1027. sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n";
  1028. sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n";
  1029. $selected = $mailbox;
  1030. }
  1031. return 0;
  1032. }
  1033. sub FETCH_imap {
  1034. my ($args) = @_;
  1035. my ($uid, $how) = split(/ /, $args, 2);
  1036. fix_imap_params($uid, $how);
  1037. logmsg "FETCH_imap got $args\n";
  1038. if ($selected eq "") {
  1039. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1040. }
  1041. else {
  1042. my @data;
  1043. my $size;
  1044. if($selected eq "verifiedserver") {
  1045. # this is the secret command that verifies that this actually is
  1046. # the curl test server
  1047. my $response = "WE ROOLZ: $$\r\n";
  1048. if($verbose) {
  1049. print STDERR "FTPD: We returned proof we are the test server\n";
  1050. }
  1051. $data[0] = $response;
  1052. logmsg "return proof we are we\n";
  1053. }
  1054. else {
  1055. # send mail content
  1056. logmsg "retrieve a mail\n";
  1057. @data = getreplydata($selected);
  1058. }
  1059. for (@data) {
  1060. $size += length($_);
  1061. }
  1062. sendcontrol "* $uid FETCH ($how {$size}\r\n";
  1063. for my $d (@data) {
  1064. sendcontrol $d;
  1065. }
  1066. sendcontrol ")\r\n";
  1067. sendcontrol "$cmdid OK FETCH completed\r\n";
  1068. }
  1069. return 0;
  1070. }
  1071. sub APPEND_imap {
  1072. my ($args) = @_;
  1073. logmsg "APPEND_imap got $args\r\n";
  1074. $args =~ /^([^ ]+) [^{]*\{(\d+)\}$/;
  1075. my ($mailbox, $size) = ($1, $2);
  1076. fix_imap_params($mailbox);
  1077. if($mailbox eq "") {
  1078. sendcontrol "$cmdid BAD Command Argument\r\n";
  1079. }
  1080. else {
  1081. sendcontrol "+ Ready for literal data\r\n";
  1082. my $testno = $mailbox;
  1083. my $filename = "log/upload.$testno";
  1084. logmsg "Store test number $testno in $filename\n";
  1085. open(FILE, ">$filename") ||
  1086. return 0; # failed to open output
  1087. my $received = 0;
  1088. my $line;
  1089. while(5 == (sysread \*SFREAD, $line, 5)) {
  1090. if($line eq "DATA\n") {
  1091. sysread \*SFREAD, $line, 5;
  1092. my $chunksize = 0;
  1093. if($line =~ /^([0-9a-fA-F]{4})\n/) {
  1094. $chunksize = hex($1);
  1095. }
  1096. read_mainsockf(\$line, $chunksize);
  1097. my $left = $size - $received;
  1098. my $datasize = ($left > $chunksize) ? $chunksize : $left;
  1099. if($datasize > 0) {
  1100. logmsg "> Appending $datasize bytes to file\n";
  1101. print FILE substr($line, 0, $datasize) if(!$nosave);
  1102. $line = substr($line, $datasize);
  1103. $received += $datasize;
  1104. if($received == $size) {
  1105. logmsg "Received all data, waiting for final CRLF.\n";
  1106. }
  1107. }
  1108. if($received == $size && $line eq "\r\n") {
  1109. last;
  1110. }
  1111. }
  1112. elsif($line eq "DISC\n") {
  1113. logmsg "Unexpected disconnect!\n";
  1114. last;
  1115. }
  1116. else {
  1117. logmsg "No support for: $line";
  1118. last;
  1119. }
  1120. }
  1121. if($nosave) {
  1122. print FILE "$size bytes would've been stored here\n";
  1123. }
  1124. close(FILE);
  1125. logmsg "received $size bytes upload\n";
  1126. sendcontrol "$cmdid OK APPEND completed\r\n";
  1127. }
  1128. return 0;
  1129. }
  1130. sub STORE_imap {
  1131. my ($args) = @_;
  1132. my ($uid, $what, $value) = split(/ /, $args, 3);
  1133. fix_imap_params($uid);
  1134. logmsg "STORE_imap got $args\n";
  1135. if ($selected eq "") {
  1136. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1137. }
  1138. elsif (($uid eq "") || ($what ne "+Flags") || ($value eq "")) {
  1139. sendcontrol "$cmdid BAD Command Argument\r\n";
  1140. }
  1141. else {
  1142. if($value eq "\\Deleted") {
  1143. push(@deleted, $uid);
  1144. }
  1145. sendcontrol "* $uid FETCH (FLAGS (\\Seen $value))\r\n";
  1146. sendcontrol "$cmdid OK STORE completed\r\n";
  1147. }
  1148. return 0;
  1149. }
  1150. sub LIST_imap {
  1151. my ($args) = @_;
  1152. my ($reference, $mailbox) = split(/ /, $args, 2);
  1153. fix_imap_params($reference, $mailbox);
  1154. logmsg "LIST_imap got $args\n";
  1155. if ($reference eq "") {
  1156. sendcontrol "$cmdid BAD Command Argument\r\n";
  1157. }
  1158. elsif ($reference eq "verifiedserver") {
  1159. # this is the secret command that verifies that this actually is
  1160. # the curl test server
  1161. sendcontrol "* LIST () \"/\" \"WE ROOLZ: $$\"\r\n";
  1162. sendcontrol "$cmdid OK LIST Completed\r\n";
  1163. if($verbose) {
  1164. print STDERR "FTPD: We returned proof we are the test server\n";
  1165. }
  1166. logmsg "return proof we are we\n";
  1167. }
  1168. else {
  1169. my @data = getreplydata($reference);
  1170. for my $d (@data) {
  1171. sendcontrol $d;
  1172. }
  1173. sendcontrol "$cmdid OK LIST Completed\r\n";
  1174. }
  1175. return 0;
  1176. }
  1177. sub LSUB_imap {
  1178. my ($args) = @_;
  1179. my ($reference, $mailbox) = split(/ /, $args, 2);
  1180. fix_imap_params($reference, $mailbox);
  1181. logmsg "LSUB_imap got $args\n";
  1182. if ($reference eq "") {
  1183. sendcontrol "$cmdid BAD Command Argument\r\n";
  1184. }
  1185. else {
  1186. my @data = getreplydata($reference);
  1187. for my $d (@data) {
  1188. sendcontrol $d;
  1189. }
  1190. sendcontrol "$cmdid OK LSUB Completed\r\n";
  1191. }
  1192. return 0;
  1193. }
  1194. sub EXAMINE_imap {
  1195. my ($mailbox) = @_;
  1196. fix_imap_params($mailbox);
  1197. logmsg "EXAMINE_imap got $mailbox\n";
  1198. if ($mailbox eq "") {
  1199. sendcontrol "$cmdid BAD Command Argument\r\n";
  1200. }
  1201. else {
  1202. my @data = getreplydata($mailbox);
  1203. for my $d (@data) {
  1204. sendcontrol $d;
  1205. }
  1206. sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n";
  1207. }
  1208. return 0;
  1209. }
  1210. sub STATUS_imap {
  1211. my ($args) = @_;
  1212. my ($mailbox, $what) = split(/ /, $args, 2);
  1213. fix_imap_params($mailbox);
  1214. logmsg "STATUS_imap got $args\n";
  1215. if ($mailbox eq "") {
  1216. sendcontrol "$cmdid BAD Command Argument\r\n";
  1217. }
  1218. else {
  1219. my @data = getreplydata($mailbox);
  1220. for my $d (@data) {
  1221. sendcontrol $d;
  1222. }
  1223. sendcontrol "$cmdid OK STATUS completed\r\n";
  1224. }
  1225. return 0;
  1226. }
  1227. sub SEARCH_imap {
  1228. my ($what) = @_;
  1229. fix_imap_params($what);
  1230. logmsg "SEARCH_imap got $what\n";
  1231. if ($selected eq "") {
  1232. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1233. }
  1234. elsif ($what eq "") {
  1235. sendcontrol "$cmdid BAD Command Argument\r\n";
  1236. }
  1237. else {
  1238. my @data = getreplydata($selected);
  1239. for my $d (@data) {
  1240. sendcontrol $d;
  1241. }
  1242. sendcontrol "$cmdid OK SEARCH completed\r\n";
  1243. }
  1244. return 0;
  1245. }
  1246. sub CREATE_imap {
  1247. my ($args) = @_;
  1248. fix_imap_params($args);
  1249. logmsg "CREATE_imap got $args\n";
  1250. if ($args eq "") {
  1251. sendcontrol "$cmdid BAD Command Argument\r\n";
  1252. }
  1253. else {
  1254. sendcontrol "$cmdid OK CREATE completed\r\n";
  1255. }
  1256. return 0;
  1257. }
  1258. sub DELETE_imap {
  1259. my ($args) = @_;
  1260. fix_imap_params($args);
  1261. logmsg "DELETE_imap got $args\n";
  1262. if ($args eq "") {
  1263. sendcontrol "$cmdid BAD Command Argument\r\n";
  1264. }
  1265. else {
  1266. sendcontrol "$cmdid OK DELETE completed\r\n";
  1267. }
  1268. return 0;
  1269. }
  1270. sub RENAME_imap {
  1271. my ($args) = @_;
  1272. my ($from_mailbox, $to_mailbox) = split(/ /, $args, 2);
  1273. fix_imap_params($from_mailbox, $to_mailbox);
  1274. logmsg "RENAME_imap got $args\n";
  1275. if (($from_mailbox eq "") || ($to_mailbox eq "")) {
  1276. sendcontrol "$cmdid BAD Command Argument\r\n";
  1277. }
  1278. else {
  1279. sendcontrol "$cmdid OK RENAME completed\r\n";
  1280. }
  1281. return 0;
  1282. }
  1283. sub CHECK_imap {
  1284. if ($selected eq "") {
  1285. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1286. }
  1287. else {
  1288. sendcontrol "$cmdid OK CHECK completed\r\n";
  1289. }
  1290. return 0;
  1291. }
  1292. sub CLOSE_imap {
  1293. if ($selected eq "") {
  1294. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1295. }
  1296. elsif (!@deleted) {
  1297. sendcontrol "$cmdid BAD Command Argument\r\n";
  1298. }
  1299. else {
  1300. sendcontrol "$cmdid OK CLOSE completed\r\n";
  1301. @deleted = ();
  1302. }
  1303. return 0;
  1304. }
  1305. sub EXPUNGE_imap {
  1306. if ($selected eq "") {
  1307. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1308. }
  1309. else {
  1310. if (!@deleted) {
  1311. # Report the number of existing messages as per the SELECT
  1312. # command
  1313. sendcontrol "* 172 EXISTS\r\n";
  1314. }
  1315. else {
  1316. # Report the message UIDs being deleted
  1317. for my $d (@deleted) {
  1318. sendcontrol "* $d EXPUNGE\r\n";
  1319. }
  1320. @deleted = ();
  1321. }
  1322. sendcontrol "$cmdid OK EXPUNGE completed\r\n";
  1323. }
  1324. return 0;
  1325. }
  1326. sub COPY_imap {
  1327. my ($args) = @_;
  1328. my ($uid, $mailbox) = split(/ /, $args, 2);
  1329. fix_imap_params($uid, $mailbox);
  1330. logmsg "COPY_imap got $args\n";
  1331. if (($uid eq "") || ($mailbox eq "")) {
  1332. sendcontrol "$cmdid BAD Command Argument\r\n";
  1333. }
  1334. else {
  1335. sendcontrol "$cmdid OK COPY completed\r\n";
  1336. }
  1337. return 0;
  1338. }
  1339. sub UID_imap {
  1340. my ($args) = @_;
  1341. my ($command) = split(/ /, $args, 1);
  1342. fix_imap_params($command);
  1343. logmsg "UID_imap got $args\n";
  1344. if ($selected eq "") {
  1345. sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
  1346. }
  1347. elsif (substr($command, 0, 5) eq "FETCH"){
  1348. my $func = $commandfunc{"FETCH"};
  1349. if($func) {
  1350. &$func($args, $command);
  1351. }
  1352. }
  1353. elsif (($command ne "COPY") &&
  1354. ($command ne "STORE") && ($command ne "SEARCH")) {
  1355. sendcontrol "$cmdid BAD Command Argument\r\n";
  1356. }
  1357. else {
  1358. my @data = getreplydata($selected);
  1359. for my $d (@data) {
  1360. sendcontrol $d;
  1361. }
  1362. sendcontrol "$cmdid OK $command completed\r\n";
  1363. }
  1364. return 0;
  1365. }
  1366. sub NOOP_imap {
  1367. my ($args) = @_;
  1368. my @data = (
  1369. "* 22 EXPUNGE\r\n",
  1370. "* 23 EXISTS\r\n",
  1371. "* 3 RECENT\r\n",
  1372. "* 14 FETCH (FLAGS (\\Seen \\Deleted))\r\n",
  1373. );
  1374. if ($args) {
  1375. sendcontrol "$cmdid BAD Command Argument\r\n";
  1376. }
  1377. else {
  1378. for my $d (@data) {
  1379. sendcontrol $d;
  1380. }
  1381. sendcontrol "$cmdid OK NOOP completed\r\n";
  1382. }
  1383. return 0;
  1384. }
  1385. sub LOGOUT_imap {
  1386. sendcontrol "* BYE curl IMAP server signing off\r\n";
  1387. sendcontrol "$cmdid OK LOGOUT completed\r\n";
  1388. return 0;
  1389. }
  1390. ################
  1391. ################ POP3 commands
  1392. ################
  1393. # Who is attempting to log in
  1394. my $username;
  1395. sub CAPA_pop3 {
  1396. my @list = ();
  1397. my $mechs;
  1398. # Calculate the capability list based on the specified capabilities
  1399. # (except APOP) and any authentication mechanisms
  1400. for my $c (@capabilities) {
  1401. push @list, "$c\r\n" unless $c eq "APOP";
  1402. }
  1403. for my $am (@auth_mechs) {
  1404. if(!$mechs) {
  1405. $mechs = "$am";
  1406. }
  1407. else {
  1408. $mechs .= " $am";
  1409. }
  1410. }
  1411. if($mechs) {
  1412. push @list, "SASL $mechs\r\n";
  1413. }
  1414. if(!@list) {
  1415. sendcontrol "-ERR Unrecognized command\r\n";
  1416. }
  1417. else {
  1418. my @data = ();
  1419. # Calculate the CAPA response
  1420. push @data, "+OK List of capabilities follows\r\n";
  1421. for my $l (@list) {
  1422. push @data, "$l\r\n";
  1423. }
  1424. push @data, "IMPLEMENTATION POP3 pingpong test server\r\n";
  1425. # Send the CAPA response
  1426. for my $d (@data) {
  1427. sendcontrol $d;
  1428. }
  1429. # End with the magic 3-byte end of listing marker
  1430. sendcontrol ".\r\n";
  1431. }
  1432. return 0;
  1433. }
  1434. sub APOP_pop3 {
  1435. my ($args) = @_;
  1436. my ($user, $secret) = split(/ /, $args, 2);
  1437. if (!grep /^APOP$/, @capabilities) {
  1438. sendcontrol "-ERR Unrecognized command\r\n";
  1439. }
  1440. elsif (($user eq "") || ($secret eq "")) {
  1441. sendcontrol "-ERR Protocol error\r\n";
  1442. }
  1443. else {
  1444. my $digest = Digest::MD5::md5_hex($POP3_TIMESTAMP, $TEXT_PASSWORD);
  1445. if ($secret ne $digest) {
  1446. sendcontrol "-ERR Login failure\r\n";
  1447. }
  1448. else {
  1449. sendcontrol "+OK Login successful\r\n";
  1450. }
  1451. }
  1452. return 0;
  1453. }
  1454. sub AUTH_pop3 {
  1455. if(!@auth_mechs) {
  1456. sendcontrol "-ERR Unrecognized command\r\n";
  1457. }
  1458. else {
  1459. my @data = ();
  1460. # Calculate the AUTH response
  1461. push @data, "+OK List of supported mechanisms follows\r\n";
  1462. for my $am (@auth_mechs) {
  1463. push @data, "$am\r\n";
  1464. }
  1465. # Send the AUTH response
  1466. for my $d (@data) {
  1467. sendcontrol $d;
  1468. }
  1469. # End with the magic 3-byte end of listing marker
  1470. sendcontrol ".\r\n";
  1471. }
  1472. return 0;
  1473. }
  1474. sub USER_pop3 {
  1475. my ($user) = @_;
  1476. logmsg "USER_pop3 got $user\n";
  1477. if (!$user) {
  1478. sendcontrol "-ERR Protocol error\r\n";
  1479. }
  1480. else {
  1481. $username = $user;
  1482. sendcontrol "+OK\r\n";
  1483. }
  1484. return 0;
  1485. }
  1486. sub PASS_pop3 {
  1487. my ($password) = @_;
  1488. logmsg "PASS_pop3 got $password\n";
  1489. sendcontrol "+OK Login successful\r\n";
  1490. return 0;
  1491. }
  1492. sub RETR_pop3 {
  1493. my ($msgid) = @_;
  1494. my @data;
  1495. if($msgid =~ /^verifiedserver$/) {
  1496. # this is the secret command that verifies that this actually is
  1497. # the curl test server
  1498. my $response = "WE ROOLZ: $$\r\n";
  1499. if($verbose) {
  1500. print STDERR "FTPD: We returned proof we are the test server\n";
  1501. }
  1502. $data[0] = $response;
  1503. logmsg "return proof we are we\n";
  1504. }
  1505. else {
  1506. # send mail content
  1507. logmsg "retrieve a mail\n";
  1508. @data = getreplydata($msgid);
  1509. }
  1510. sendcontrol "+OK Mail transfer starts\r\n";
  1511. for my $d (@data) {
  1512. sendcontrol $d;
  1513. }
  1514. # end with the magic 3-byte end of mail marker, assumes that the
  1515. # mail body ends with a CRLF!
  1516. sendcontrol ".\r\n";
  1517. return 0;
  1518. }
  1519. sub LIST_pop3 {
  1520. # This is a built-in fake-message list
  1521. my @data = (
  1522. "1 100\r\n",
  1523. "2 4294967400\r\n", # > 4 GB
  1524. "3 200\r\n",
  1525. );
  1526. logmsg "retrieve a message list\n";
  1527. sendcontrol "+OK Listing starts\r\n";
  1528. for my $d (@data) {
  1529. sendcontrol $d;
  1530. }
  1531. # End with the magic 3-byte end of listing marker
  1532. sendcontrol ".\r\n";
  1533. return 0;
  1534. }
  1535. sub DELE_pop3 {
  1536. my ($msgid) = @_;
  1537. logmsg "DELE_pop3 got $msgid\n";
  1538. if (!$msgid) {
  1539. sendcontrol "-ERR Protocol error\r\n";
  1540. }
  1541. else {
  1542. push (@deleted, $msgid);
  1543. sendcontrol "+OK\r\n";
  1544. }
  1545. return 0;
  1546. }
  1547. sub STAT_pop3 {
  1548. my ($args) = @_;
  1549. if ($args) {
  1550. sendcontrol "-ERR Protocol error\r\n";
  1551. }
  1552. else {
  1553. # Send statistics for the built-in fake message list as
  1554. # detailed in the LIST_pop3 function above
  1555. sendcontrol "+OK 3 4294967800\r\n";
  1556. }
  1557. return 0;
  1558. }
  1559. sub NOOP_pop3 {
  1560. my ($args) = @_;
  1561. if ($args) {
  1562. sendcontrol "-ERR Protocol error\r\n";
  1563. }
  1564. else {
  1565. sendcontrol "+OK\r\n";
  1566. }
  1567. return 0;
  1568. }
  1569. sub UIDL_pop3 {
  1570. # This is a built-in fake-message UID list
  1571. my @data = (
  1572. "1 1\r\n",
  1573. "2 2\r\n",
  1574. "3 4\r\n", # Note that UID 3 is a simulated "deleted" message
  1575. );
  1576. if (!grep /^UIDL$/, @capabilities) {
  1577. sendcontrol "-ERR Unrecognized command\r\n";
  1578. }
  1579. else {
  1580. logmsg "retrieve a message UID list\n";
  1581. sendcontrol "+OK Listing starts\r\n";
  1582. for my $d (@data) {
  1583. sendcontrol $d;
  1584. }
  1585. # End with the magic 3-byte end of listing marker
  1586. sendcontrol ".\r\n";
  1587. }
  1588. return 0;
  1589. }
  1590. sub TOP_pop3 {
  1591. my ($args) = @_;
  1592. my ($msgid, $lines) = split(/ /, $args, 2);
  1593. logmsg "TOP_pop3 got $args\n";
  1594. if (!grep /^TOP$/, @capabilities) {
  1595. sendcontrol "-ERR Unrecognized command\r\n";
  1596. }
  1597. elsif (($msgid eq "") || ($lines eq "")) {
  1598. sendcontrol "-ERR Protocol error\r\n";
  1599. }
  1600. else {
  1601. if ($lines == "0") {
  1602. logmsg "retrieve header of mail\n";
  1603. }
  1604. else {
  1605. logmsg "retrieve top $lines lines of mail\n";
  1606. }
  1607. my @data = getreplydata($msgid);
  1608. sendcontrol "+OK Mail transfer starts\r\n";
  1609. # Send mail content
  1610. for my $d (@data) {
  1611. sendcontrol $d;
  1612. }
  1613. # End with the magic 3-byte end of mail marker, assumes that the
  1614. # mail body ends with a CRLF!
  1615. sendcontrol ".\r\n";
  1616. }
  1617. return 0;
  1618. }
  1619. sub RSET_pop3 {
  1620. my ($args) = @_;
  1621. if ($args) {
  1622. sendcontrol "-ERR Protocol error\r\n";
  1623. }
  1624. else {
  1625. if (@deleted) {
  1626. logmsg "resetting @deleted message(s)\n";
  1627. @deleted = ();
  1628. }
  1629. sendcontrol "+OK\r\n";
  1630. }
  1631. return 0;
  1632. }
  1633. sub QUIT_pop3 {
  1634. if(@deleted) {
  1635. logmsg "deleting @deleted message(s)\n";
  1636. @deleted = ();
  1637. }
  1638. sendcontrol "+OK curl POP3 server signing off\r\n";
  1639. return 0;
  1640. }
  1641. ################
  1642. ################ FTP commands
  1643. ################
  1644. my $rest=0;
  1645. sub REST_ftp {
  1646. $rest = $_[0];
  1647. logmsg "Set REST position to $rest\n"
  1648. }
  1649. sub switch_directory_goto {
  1650. my $target_dir = $_;
  1651. if(!$ftptargetdir) {
  1652. $ftptargetdir = "/";
  1653. }
  1654. if($target_dir eq "") {
  1655. $ftptargetdir = "/";
  1656. }
  1657. elsif($target_dir eq "..") {
  1658. if($ftptargetdir eq "/") {
  1659. $ftptargetdir = "/";
  1660. }
  1661. else {
  1662. $ftptargetdir =~ s/[[:alnum:]]+\/$//;
  1663. }
  1664. }
  1665. else {
  1666. $ftptargetdir .= $target_dir . "/";
  1667. }
  1668. }
  1669. sub switch_directory {
  1670. my $target_dir = $_[0];
  1671. if($target_dir =~ /^test-(\d+)/) {
  1672. $cwd_testno = $1;
  1673. }
  1674. elsif($target_dir eq "/") {
  1675. $ftptargetdir = "/";
  1676. }
  1677. else {
  1678. my @dirs = split("/", $target_dir);
  1679. for(@dirs) {
  1680. switch_directory_goto($_);
  1681. }
  1682. }
  1683. }
  1684. sub CWD_ftp {
  1685. my ($folder, $fullcommand) = $_[0];
  1686. switch_directory($folder);
  1687. if($ftptargetdir =~ /^\/fully_simulated/) {
  1688. $ftplistparserstate = "enabled";
  1689. }
  1690. else {
  1691. undef $ftplistparserstate;
  1692. }
  1693. }
  1694. sub PWD_ftp {
  1695. my $mydir;
  1696. $mydir = $ftptargetdir ? $ftptargetdir : "/";
  1697. if($mydir ne "/") {
  1698. $mydir =~ s/\/$//;
  1699. }
  1700. sendcontrol "257 \"$mydir\" is current directory\r\n";
  1701. }
  1702. sub LIST_ftp {
  1703. # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n";
  1704. # this is a built-in fake-dir ;-)
  1705. my @ftpdir=("total 20\r\n",
  1706. "drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n",
  1707. "drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n",
  1708. "drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n",
  1709. "-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n",
  1710. "lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n",
  1711. "dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n",
  1712. "drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n",
  1713. "dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n",
  1714. "drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n",
  1715. "dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n");
  1716. if($datasockf_conn eq 'no') {
  1717. if($nodataconn425) {
  1718. sendcontrol "150 Opening data connection\r\n";
  1719. sendcontrol "425 Can't open data connection\r\n";
  1720. }
  1721. elsif($nodataconn421) {
  1722. sendcontrol "150 Opening data connection\r\n";
  1723. sendcontrol "421 Connection timed out\r\n";
  1724. }
  1725. elsif($nodataconn150) {
  1726. sendcontrol "150 Opening data connection\r\n";
  1727. # client shall timeout
  1728. }
  1729. else {
  1730. # client shall timeout
  1731. }
  1732. return 0;
  1733. }
  1734. if($ftplistparserstate) {
  1735. @ftpdir = ftp_contentlist($ftptargetdir);
  1736. }
  1737. logmsg "pass LIST data on data connection\n";
  1738. if($cwd_testno) {
  1739. loadtest("$logdir/test$cwd_testno");
  1740. my @data = getpart("reply", "data");
  1741. for(@data) {
  1742. my $send = $_;
  1743. # convert all \n to \r\n for ASCII transfer
  1744. $send =~ s/\r\n/\n/g;
  1745. $send =~ s/\n/\r\n/g;
  1746. logmsg "send $send as data\n";
  1747. senddata $send;
  1748. }
  1749. $cwd_testno = 0; # forget it again
  1750. }
  1751. else {
  1752. # old hard-coded style
  1753. for(@ftpdir) {
  1754. senddata $_;
  1755. }
  1756. }
  1757. close_dataconn(0);
  1758. sendcontrol "226 ASCII transfer complete\r\n";
  1759. return 0;
  1760. }
  1761. sub NLST_ftp {
  1762. my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
  1763. if($datasockf_conn eq 'no') {
  1764. if($nodataconn425) {
  1765. sendcontrol "150 Opening data connection\r\n";
  1766. sendcontrol "425 Can't open data connection\r\n";
  1767. }
  1768. elsif($nodataconn421) {
  1769. sendcontrol "150 Opening data connection\r\n";
  1770. sendcontrol "421 Connection timed out\r\n";
  1771. }
  1772. elsif($nodataconn150) {
  1773. sendcontrol "150 Opening data connection\r\n";
  1774. # client shall timeout
  1775. }
  1776. else {
  1777. # client shall timeout
  1778. }
  1779. return 0;
  1780. }
  1781. logmsg "pass NLST data on data connection\n";
  1782. for(@ftpdir) {
  1783. senddata "$_\r\n";
  1784. }
  1785. close_dataconn(0);
  1786. sendcontrol "226 ASCII transfer complete\r\n";
  1787. return 0;
  1788. }
  1789. sub MDTM_ftp {
  1790. my $testno = $_[0];
  1791. my $testpart = "";
  1792. if ($testno > 10000) {
  1793. $testpart = $testno % 10000;
  1794. $testno = int($testno / 10000);
  1795. }
  1796. loadtest("$logdir/test$testno");
  1797. my @data = getpart("reply", "mdtm");
  1798. my $reply = $data[0];
  1799. chomp $reply if($reply);
  1800. if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
  1801. sendcontrol "550 $testno: no such file.\r\n";
  1802. }
  1803. elsif($reply) {
  1804. sendcontrol "$reply\r\n";
  1805. }
  1806. else {
  1807. sendcontrol "500 MDTM: no such command.\r\n";
  1808. }
  1809. return 0;
  1810. }
  1811. sub SIZE_ftp {
  1812. my $testno = $_[0];
  1813. if($ftplistparserstate) {
  1814. my $size = wildcard_filesize($ftptargetdir, $testno);
  1815. if($size == -1) {
  1816. sendcontrol "550 $testno: No such file or directory.\r\n";
  1817. }
  1818. else {
  1819. sendcontrol "213 $size\r\n";
  1820. }
  1821. return 0;
  1822. }
  1823. if($testno =~ /^verifiedserver$/) {
  1824. my $response = "WE ROOLZ: $$\r\n";
  1825. my $size = length($response);
  1826. sendcontrol "213 $size\r\n";
  1827. return 0;
  1828. }
  1829. if($testno =~ /(\d+)\/?$/) {
  1830. $testno = $1;
  1831. }
  1832. else {
  1833. print STDERR "SIZE_ftp: invalid test number: $testno\n";
  1834. return 1;
  1835. }
  1836. my $testpart = "";
  1837. if($testno > 10000) {
  1838. $testpart = $testno % 10000;
  1839. $testno = int($testno / 10000);
  1840. }
  1841. loadtest("$logdir/test$testno");
  1842. my @data = getpart("reply", "size");
  1843. my $size = $data[0];
  1844. if($size) {
  1845. if($size > -1) {
  1846. sendcontrol "213 $size\r\n";
  1847. }
  1848. else {
  1849. sendcontrol "550 $testno: No such file or directory.\r\n";
  1850. }
  1851. }
  1852. else {
  1853. $size=0;
  1854. @data = getpart("reply", "data$testpart");
  1855. for(@data) {
  1856. $size += length($_);
  1857. }
  1858. if($size) {
  1859. sendcontrol "213 $size\r\n";
  1860. }
  1861. else {
  1862. sendcontrol "550 $testno: No such file or directory.\r\n";
  1863. }
  1864. }
  1865. return 0;
  1866. }
  1867. sub RETR_ftp {
  1868. my ($testno) = @_;
  1869. if($datasockf_conn eq 'no') {
  1870. if($nodataconn425) {
  1871. sendcontrol "150 Opening data connection\r\n";
  1872. sendcontrol "425 Can't open data connection\r\n";
  1873. }
  1874. elsif($nodataconn421) {
  1875. sendcontrol "150 Opening data connection\r\n";
  1876. sendcontrol "421 Connection timed out\r\n";
  1877. }
  1878. elsif($nodataconn150) {
  1879. sendcontrol "150 Opening data connection\r\n";
  1880. # client shall timeout
  1881. }
  1882. else {
  1883. # client shall timeout
  1884. }
  1885. return 0;
  1886. }
  1887. if($ftplistparserstate) {
  1888. my @content = wildcard_getfile($ftptargetdir, $testno);
  1889. if($content[0] == -1) {
  1890. #file not found
  1891. }
  1892. else {
  1893. my $size = length $content[1];
  1894. sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
  1895. senddata $content[1];
  1896. close_dataconn(0);
  1897. sendcontrol "226 File transfer complete\r\n";
  1898. }
  1899. return 0;
  1900. }
  1901. if($testno =~ /^verifiedserver$/) {
  1902. # this is the secret command that verifies that this actually is
  1903. # the curl test server
  1904. my $response = "WE ROOLZ: $$\r\n";
  1905. my $len = length($response);
  1906. sendcontrol "150 Binary junk ($len bytes).\r\n";
  1907. senddata "WE ROOLZ: $$\r\n";
  1908. close_dataconn(0);
  1909. sendcontrol "226 File transfer complete\r\n";
  1910. if($verbose) {
  1911. print STDERR "FTPD: We returned proof we are the test server\n";
  1912. }
  1913. return 0;
  1914. }
  1915. $testno =~ s/^([^0-9]*)//;
  1916. my $testpart = "";
  1917. if ($testno > 10000) {
  1918. $testpart = $testno % 10000;
  1919. $testno = int($testno / 10000);
  1920. }
  1921. loadtest("$logdir/test$testno");
  1922. my @data = getpart("reply", "data$testpart");
  1923. my $size=0;
  1924. for(@data) {
  1925. $size += length($_);
  1926. }
  1927. my %hash = getpartattr("reply", "data$testpart");
  1928. if($size || $hash{'sendzero'}) {
  1929. if($rest) {
  1930. # move read pointer forward
  1931. $size -= $rest;
  1932. logmsg "REST $rest was removed from size, makes $size left\n";
  1933. $rest = 0; # reset REST offset again
  1934. }
  1935. if($retrweirdo) {
  1936. sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
  1937. "226 File transfer complete\r\n";
  1938. for(@data) {
  1939. my $send = $_;
  1940. senddata $send;
  1941. }
  1942. close_dataconn(0);
  1943. $retrweirdo=0; # switch off the weirdo again!
  1944. }
  1945. else {
  1946. my $sz = "($size bytes)";
  1947. if($retrnosize) {
  1948. $sz = "size?";
  1949. }
  1950. sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
  1951. for(@data) {
  1952. my $send = $_;
  1953. senddata $send;
  1954. }
  1955. close_dataconn(0);
  1956. sendcontrol "226 File transfer complete\r\n";
  1957. }
  1958. }
  1959. else {
  1960. sendcontrol "550 $testno: No such file or directory.\r\n";
  1961. }
  1962. return 0;
  1963. }
  1964. sub STOR_ftp {
  1965. my $testno=$_[0];
  1966. my $filename = "log/upload.$testno";
  1967. if($datasockf_conn eq 'no') {
  1968. if($nodataconn425) {
  1969. sendcontrol "150 Opening data connection\r\n";
  1970. sendcontrol "425 Can't open data connection\r\n";
  1971. }
  1972. elsif($nodataconn421) {
  1973. sendcontrol "150 Opening data connection\r\n";
  1974. sendcontrol "421 Connection timed out\r\n";
  1975. }
  1976. elsif($nodataconn150) {
  1977. sendcontrol "150 Opening data connection\r\n";
  1978. # client shall timeout
  1979. }
  1980. else {
  1981. # client shall timeout
  1982. }
  1983. return 0;
  1984. }
  1985. logmsg "STOR test number $testno in $filename\n";
  1986. sendcontrol "125 Gimme gimme gimme!\r\n";
  1987. open(FILE, ">$filename") ||
  1988. return 0; # failed to open output
  1989. my $line;
  1990. my $ulsize=0;
  1991. my $disc=0;
  1992. while (5 == (sysread DREAD, $line, 5)) {
  1993. if($line eq "DATA\n") {
  1994. my $i;
  1995. sysread DREAD, $i, 5;
  1996. my $size = 0;
  1997. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  1998. $size = hex($1);
  1999. }
  2000. read_datasockf(\$line, $size);
  2001. #print STDERR " GOT: $size bytes\n";
  2002. $ulsize += $size;
  2003. print FILE $line if(!$nosave);
  2004. logmsg "> Appending $size bytes to file\n";
  2005. }
  2006. elsif($line eq "DISC\n") {
  2007. # disconnect!
  2008. $disc=1;
  2009. last;
  2010. }
  2011. else {
  2012. logmsg "No support for: $line";
  2013. last;
  2014. }
  2015. if($storeresp) {
  2016. # abort early
  2017. last;
  2018. }
  2019. }
  2020. if($nosave) {
  2021. print FILE "$ulsize bytes would've been stored here\n";
  2022. }
  2023. close(FILE);
  2024. close_dataconn($disc);
  2025. logmsg "received $ulsize bytes upload\n";
  2026. if($storeresp) {
  2027. sendcontrol "$storeresp\r\n";
  2028. }
  2029. else {
  2030. sendcontrol "226 File transfer complete\r\n";
  2031. }
  2032. return 0;
  2033. }
  2034. sub PASV_ftp {
  2035. my ($arg, $cmd)=@_;
  2036. my $pasvport;
  2037. my $bindonly = ($nodataconn) ? '--bindonly' : '';
  2038. # kill previous data connection sockfilt when alive
  2039. if($datasockf_runs eq 'yes') {
  2040. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2041. logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
  2042. }
  2043. datasockf_state('STOPPED');
  2044. logmsg "====> Passive DATA channel requested by client\n";
  2045. logmsg "DATA sockfilt for passive data channel starting...\n";
  2046. # We fire up a new sockfilt to do the data transfer for us.
  2047. my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  2048. "--ipv$ipvnum $bindonly --port 0 " .
  2049. "--pidfile \"$datasockf_pidfile\" " .
  2050. "--logfile \"$datasockf_logfile\"";
  2051. $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
  2052. if($nodataconn) {
  2053. datasockf_state('PASSIVE_NODATACONN');
  2054. }
  2055. else {
  2056. datasockf_state('PASSIVE');
  2057. }
  2058. print STDERR "$datasockfcmd\n" if($verbose);
  2059. print DWRITE "PING\n";
  2060. my $pong;
  2061. sysread_or_die(\*DREAD, \$pong, 5);
  2062. if($pong =~ /^FAIL/) {
  2063. logmsg "DATA sockfilt said: FAIL\n";
  2064. logmsg "DATA sockfilt for passive data channel failed\n";
  2065. logmsg "DATA sockfilt not running\n";
  2066. datasockf_state('STOPPED');
  2067. sendcontrol "500 no free ports!\r\n";
  2068. return;
  2069. }
  2070. elsif($pong !~ /^PONG/) {
  2071. logmsg "DATA sockfilt unexpected response: $pong\n";
  2072. logmsg "DATA sockfilt for passive data channel failed\n";
  2073. logmsg "DATA sockfilt killed now\n";
  2074. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2075. logmsg "DATA sockfilt not running\n";
  2076. datasockf_state('STOPPED');
  2077. sendcontrol "500 no free ports!\r\n";
  2078. return;
  2079. }
  2080. logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
  2081. # Find out on what port we listen on or have bound
  2082. my $i;
  2083. print DWRITE "PORT\n";
  2084. # READ the response code
  2085. sysread_or_die(\*DREAD, \$i, 5);
  2086. # READ the response size
  2087. sysread_or_die(\*DREAD, \$i, 5);
  2088. my $size = 0;
  2089. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  2090. $size = hex($1);
  2091. }
  2092. # READ the response data
  2093. read_datasockf(\$i, $size);
  2094. # The data is in the format
  2095. # IPvX/NNN
  2096. if($i =~ /IPv(\d)\/(\d+)/) {
  2097. # FIX: deal with IP protocol version
  2098. $pasvport = $2;
  2099. }
  2100. if(!$pasvport) {
  2101. logmsg "DATA sockfilt unknown listener port\n";
  2102. logmsg "DATA sockfilt for passive data channel failed\n";
  2103. logmsg "DATA sockfilt killed now\n";
  2104. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2105. logmsg "DATA sockfilt not running\n";
  2106. datasockf_state('STOPPED');
  2107. sendcontrol "500 no free ports!\r\n";
  2108. return;
  2109. }
  2110. if($nodataconn) {
  2111. my $str = nodataconn_str();
  2112. logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
  2113. "$pasvport\n";
  2114. }
  2115. else {
  2116. logmsg "DATA sockfilt for passive data channel listens on port ".
  2117. "$pasvport\n";
  2118. }
  2119. if($cmd ne "EPSV") {
  2120. # PASV reply
  2121. my $p=$listenaddr;
  2122. $p =~ s/\./,/g;
  2123. if($pasvbadip) {
  2124. $p="1,2,3,4";
  2125. }
  2126. sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
  2127. int($pasvport/256), int($pasvport%256));
  2128. }
  2129. else {
  2130. # EPSV reply
  2131. sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
  2132. }
  2133. logmsg "Client has been notified that DATA conn ".
  2134. "will be accepted on port $pasvport\n";
  2135. if($nodataconn) {
  2136. my $str = nodataconn_str();
  2137. logmsg "====> Client fooled ($str)\n";
  2138. return;
  2139. }
  2140. eval {
  2141. local $SIG{ALRM} = sub { die "alarm\n" };
  2142. # assume swift operations unless explicitly slow
  2143. alarm ($datadelay?20:10);
  2144. # Wait for 'CNCT'
  2145. my $input;
  2146. # FIX: Monitor ctrl conn for disconnect
  2147. while(sysread(DREAD, $input, 5)) {
  2148. if($input !~ /^CNCT/) {
  2149. # we wait for a connected client
  2150. logmsg "Odd, we got $input from client\n";
  2151. next;
  2152. }
  2153. logmsg "Client connects to port $pasvport\n";
  2154. last;
  2155. }
  2156. alarm 0;
  2157. };
  2158. if ($@) {
  2159. # timed out
  2160. logmsg "$srvrname server timed out awaiting data connection ".
  2161. "on port $pasvport\n";
  2162. logmsg "accept failed or connection not even attempted\n";
  2163. logmsg "DATA sockfilt killed now\n";
  2164. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2165. logmsg "DATA sockfilt not running\n";
  2166. datasockf_state('STOPPED');
  2167. return;
  2168. }
  2169. else {
  2170. logmsg "====> Client established passive DATA connection ".
  2171. "on port $pasvport\n";
  2172. }
  2173. return;
  2174. }
  2175. #
  2176. # Support both PORT and EPRT here.
  2177. #
  2178. sub PORT_ftp {
  2179. my ($arg, $cmd) = @_;
  2180. my $port;
  2181. my $addr;
  2182. # kill previous data connection sockfilt when alive
  2183. if($datasockf_runs eq 'yes') {
  2184. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2185. logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
  2186. }
  2187. datasockf_state('STOPPED');
  2188. logmsg "====> Active DATA channel requested by client\n";
  2189. # We always ignore the given IP and use localhost.
  2190. if($cmd eq "PORT") {
  2191. if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
  2192. logmsg "DATA sockfilt for active data channel not started ".
  2193. "(bad PORT-line: $arg)\n";
  2194. sendcontrol "500 silly you, go away\r\n";
  2195. return;
  2196. }
  2197. $port = ($5<<8)+$6;
  2198. $addr = "$1.$2.$3.$4";
  2199. }
  2200. # EPRT |2|::1|49706|
  2201. elsif($cmd eq "EPRT") {
  2202. if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
  2203. logmsg "DATA sockfilt for active data channel not started ".
  2204. "(bad EPRT-line: $arg)\n";
  2205. sendcontrol "500 silly you, go away\r\n";
  2206. return;
  2207. }
  2208. sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
  2209. $port = $3;
  2210. $addr = $2;
  2211. }
  2212. else {
  2213. logmsg "DATA sockfilt for active data channel not started ".
  2214. "(invalid command: $cmd)\n";
  2215. sendcontrol "500 we don't like $cmd now\r\n";
  2216. return;
  2217. }
  2218. if(!$port || $port > 65535) {
  2219. logmsg "DATA sockfilt for active data channel not started ".
  2220. "(illegal PORT number: $port)\n";
  2221. return;
  2222. }
  2223. if($nodataconn) {
  2224. my $str = nodataconn_str();
  2225. logmsg "DATA sockfilt for active data channel not started ($str)\n";
  2226. datasockf_state('ACTIVE_NODATACONN');
  2227. logmsg "====> Active DATA channel not established\n";
  2228. return;
  2229. }
  2230. logmsg "DATA sockfilt for active data channel starting...\n";
  2231. # We fire up a new sockfilt to do the data transfer for us.
  2232. my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  2233. "--ipv$ipvnum --connect $port --addr \"$addr\" " .
  2234. "--pidfile \"$datasockf_pidfile\" " .
  2235. "--logfile \"$datasockf_logfile\"";
  2236. $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
  2237. datasockf_state('ACTIVE');
  2238. print STDERR "$datasockfcmd\n" if($verbose);
  2239. print DWRITE "PING\n";
  2240. my $pong;
  2241. sysread_or_die(\*DREAD, \$pong, 5);
  2242. if($pong =~ /^FAIL/) {
  2243. logmsg "DATA sockfilt said: FAIL\n";
  2244. logmsg "DATA sockfilt for active data channel failed\n";
  2245. logmsg "DATA sockfilt not running\n";
  2246. datasockf_state('STOPPED');
  2247. # client shall timeout awaiting connection from server
  2248. return;
  2249. }
  2250. elsif($pong !~ /^PONG/) {
  2251. logmsg "DATA sockfilt unexpected response: $pong\n";
  2252. logmsg "DATA sockfilt for active data channel failed\n";
  2253. logmsg "DATA sockfilt killed now\n";
  2254. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2255. logmsg "DATA sockfilt not running\n";
  2256. datasockf_state('STOPPED');
  2257. # client shall timeout awaiting connection from server
  2258. return;
  2259. }
  2260. logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
  2261. logmsg "====> Active DATA channel connected to client port $port\n";
  2262. return;
  2263. }
  2264. #**********************************************************************
  2265. # datasockf_state is used to change variables that keep state info
  2266. # relative to the FTP secondary or data sockfilt process as soon as
  2267. # one of the five possible stable states is reached. Variables that
  2268. # are modified by this sub may be checked independently but should
  2269. # not be changed except by calling this sub.
  2270. #
  2271. sub datasockf_state {
  2272. my $state = $_[0];
  2273. if($state eq 'STOPPED') {
  2274. # Data sockfilter initial state, not running,
  2275. # not connected and not used.
  2276. $datasockf_state = $state;
  2277. $datasockf_mode = 'none';
  2278. $datasockf_runs = 'no';
  2279. $datasockf_conn = 'no';
  2280. }
  2281. elsif($state eq 'PASSIVE') {
  2282. # Data sockfilter accepted connection from client.
  2283. $datasockf_state = $state;
  2284. $datasockf_mode = 'passive';
  2285. $datasockf_runs = 'yes';
  2286. $datasockf_conn = 'yes';
  2287. }
  2288. elsif($state eq 'ACTIVE') {
  2289. # Data sockfilter has connected to client.
  2290. $datasockf_state = $state;
  2291. $datasockf_mode = 'active';
  2292. $datasockf_runs = 'yes';
  2293. $datasockf_conn = 'yes';
  2294. }
  2295. elsif($state eq 'PASSIVE_NODATACONN') {
  2296. # Data sockfilter bound port without listening,
  2297. # client won't be able to establish data connection.
  2298. $datasockf_state = $state;
  2299. $datasockf_mode = 'passive';
  2300. $datasockf_runs = 'yes';
  2301. $datasockf_conn = 'no';
  2302. }
  2303. elsif($state eq 'ACTIVE_NODATACONN') {
  2304. # Data sockfilter does not even run,
  2305. # client awaits data connection from server in vain.
  2306. $datasockf_state = $state;
  2307. $datasockf_mode = 'active';
  2308. $datasockf_runs = 'no';
  2309. $datasockf_conn = 'no';
  2310. }
  2311. else {
  2312. die "Internal error. Unknown datasockf state: $state!";
  2313. }
  2314. }
  2315. #**********************************************************************
  2316. # nodataconn_str returns string of effective nodataconn command. Notice
  2317. # that $nodataconn may be set alone or in addition to a $nodataconnXXX.
  2318. #
  2319. sub nodataconn_str {
  2320. my $str;
  2321. # order matters
  2322. $str = 'NODATACONN' if($nodataconn);
  2323. $str = 'NODATACONN425' if($nodataconn425);
  2324. $str = 'NODATACONN421' if($nodataconn421);
  2325. $str = 'NODATACONN150' if($nodataconn150);
  2326. return "$str";
  2327. }
  2328. #**********************************************************************
  2329. # customize configures test server operation for each curl test, reading
  2330. # configuration commands/parameters from server commands file each time
  2331. # a new client control connection is established with the test server.
  2332. # On success returns 1, otherwise zero.
  2333. #
  2334. sub customize {
  2335. $ctrldelay = 0; # default is no throttling of the ctrl stream
  2336. $datadelay = 0; # default is no throttling of the data stream
  2337. $retrweirdo = 0; # default is no use of RETRWEIRDO
  2338. $retrnosize = 0; # default is no use of RETRNOSIZE
  2339. $pasvbadip = 0; # default is no use of PASVBADIP
  2340. $nosave = 0; # default is to actually save uploaded data to file
  2341. $nodataconn = 0; # default is to establish or accept data channel
  2342. $nodataconn425 = 0; # default is to not send 425 without data channel
  2343. $nodataconn421 = 0; # default is to not send 421 without data channel
  2344. $nodataconn150 = 0; # default is to not send 150 without data channel
  2345. $storeresp = ""; # send as ultimate STOR response
  2346. @capabilities = (); # default is to not support capability commands
  2347. @auth_mechs = (); # default is to not support authentication commands
  2348. %fulltextreply = ();#
  2349. %commandreply = (); #
  2350. %customcount = (); #
  2351. %delayreply = (); #
  2352. open(CUSTOM, "<log/ftpserver.cmd") ||
  2353. return 1;
  2354. logmsg "FTPD: Getting commands from log/ftpserver.cmd\n";
  2355. while(<CUSTOM>) {
  2356. if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) {
  2357. $fulltextreply{$1}=eval "qq{$2}";
  2358. logmsg "FTPD: set custom reply for $1\n";
  2359. }
  2360. elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) {
  2361. $commandreply{$2}=eval "qq{$3}";
  2362. if($1 ne "LF") {
  2363. $commandreply{$2}.="\r\n";
  2364. }
  2365. else {
  2366. $commandreply{$2}.="\n";
  2367. }
  2368. if($2 eq "") {
  2369. logmsg "FTPD: set custom reply for empty command\n";
  2370. }
  2371. else {
  2372. logmsg "FTPD: set custom reply for $2 command\n";
  2373. }
  2374. }
  2375. elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
  2376. # we blank the custom reply for this command when having
  2377. # been used this number of times
  2378. $customcount{$1}=$2;
  2379. logmsg "FTPD: blank custom reply for $1 command after $2 uses\n";
  2380. }
  2381. elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
  2382. $delayreply{$1}=$2;
  2383. logmsg "FTPD: delay reply for $1 with $2 seconds\n";
  2384. }
  2385. elsif($_ =~ /SLOWDOWN/) {
  2386. $ctrldelay=1;
  2387. $datadelay=1;
  2388. logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
  2389. }
  2390. elsif($_ =~ /RETRWEIRDO/) {
  2391. logmsg "FTPD: instructed to use RETRWEIRDO\n";
  2392. $retrweirdo=1;
  2393. }
  2394. elsif($_ =~ /RETRNOSIZE/) {
  2395. logmsg "FTPD: instructed to use RETRNOSIZE\n";
  2396. $retrnosize=1;
  2397. }
  2398. elsif($_ =~ /PASVBADIP/) {
  2399. logmsg "FTPD: instructed to use PASVBADIP\n";
  2400. $pasvbadip=1;
  2401. }
  2402. elsif($_ =~ /NODATACONN425/) {
  2403. # applies to both active and passive FTP modes
  2404. logmsg "FTPD: instructed to use NODATACONN425\n";
  2405. $nodataconn425=1;
  2406. $nodataconn=1;
  2407. }
  2408. elsif($_ =~ /NODATACONN421/) {
  2409. # applies to both active and passive FTP modes
  2410. logmsg "FTPD: instructed to use NODATACONN421\n";
  2411. $nodataconn421=1;
  2412. $nodataconn=1;
  2413. }
  2414. elsif($_ =~ /NODATACONN150/) {
  2415. # applies to both active and passive FTP modes
  2416. logmsg "FTPD: instructed to use NODATACONN150\n";
  2417. $nodataconn150=1;
  2418. $nodataconn=1;
  2419. }
  2420. elsif($_ =~ /NODATACONN/) {
  2421. # applies to both active and passive FTP modes
  2422. logmsg "FTPD: instructed to use NODATACONN\n";
  2423. $nodataconn=1;
  2424. }
  2425. elsif($_ =~ /^STOR (.*)/) {
  2426. $storeresp=$1;
  2427. logmsg "FTPD: instructed to use respond to STOR with '$storeresp'\n";
  2428. }
  2429. elsif($_ =~ /CAPA (.*)/) {
  2430. logmsg "FTPD: instructed to support CAPABILITY command\n";
  2431. @capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1);
  2432. foreach (@capabilities) {
  2433. $_ = $1 if /^"(.*)"$/;
  2434. }
  2435. }
  2436. elsif($_ =~ /AUTH (.*)/) {
  2437. logmsg "FTPD: instructed to support AUTHENTICATION command\n";
  2438. @auth_mechs = split(/ /, $1);
  2439. }
  2440. elsif($_ =~ /NOSAVE/) {
  2441. # don't actually store the file we upload - to be used when
  2442. # uploading insanely huge amounts
  2443. $nosave = 1;
  2444. logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
  2445. }
  2446. elsif($_ =~ /^Testnum (\d+)/){
  2447. $testno = $1;
  2448. logmsg "FTPD: run test case number: $testno\n";
  2449. }
  2450. }
  2451. close(CUSTOM);
  2452. }
  2453. #----------------------------------------------------------------------
  2454. #----------------------------------------------------------------------
  2455. #--------------------------- END OF SUBS ----------------------------
  2456. #----------------------------------------------------------------------
  2457. #----------------------------------------------------------------------
  2458. #**********************************************************************
  2459. # Parse command line options
  2460. #
  2461. # Options:
  2462. #
  2463. # --verbose # verbose
  2464. # --srcdir # source directory
  2465. # --id # server instance number
  2466. # --proto # server protocol
  2467. # --pidfile # server pid file
  2468. # --portfile # server port file
  2469. # --logfile # server log file
  2470. # --ipv4 # server IP version 4
  2471. # --ipv6 # server IP version 6
  2472. # --port # server listener port
  2473. # --addr # server address for listener port binding
  2474. #
  2475. while(@ARGV) {
  2476. if($ARGV[0] eq '--verbose') {
  2477. $verbose = 1;
  2478. }
  2479. elsif($ARGV[0] eq '--srcdir') {
  2480. if($ARGV[1]) {
  2481. $srcdir = $ARGV[1];
  2482. shift @ARGV;
  2483. }
  2484. }
  2485. elsif($ARGV[0] eq '--id') {
  2486. if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
  2487. $idnum = $1 if($1 > 0);
  2488. shift @ARGV;
  2489. }
  2490. }
  2491. elsif($ARGV[0] eq '--proto') {
  2492. if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
  2493. $proto = $1;
  2494. shift @ARGV;
  2495. }
  2496. else {
  2497. die "unsupported protocol $ARGV[1]";
  2498. }
  2499. }
  2500. elsif($ARGV[0] eq '--pidfile') {
  2501. if($ARGV[1]) {
  2502. $pidfile = $ARGV[1];
  2503. shift @ARGV;
  2504. }
  2505. }
  2506. elsif($ARGV[0] eq '--portfile') {
  2507. if($ARGV[1]) {
  2508. $portfile = $ARGV[1];
  2509. shift @ARGV;
  2510. }
  2511. }
  2512. elsif($ARGV[0] eq '--logfile') {
  2513. if($ARGV[1]) {
  2514. $logfile = $ARGV[1];
  2515. shift @ARGV;
  2516. }
  2517. }
  2518. elsif($ARGV[0] eq '--ipv4') {
  2519. $ipvnum = 4;
  2520. $listenaddr = '127.0.0.1' if($listenaddr eq '::1');
  2521. }
  2522. elsif($ARGV[0] eq '--ipv6') {
  2523. $ipvnum = 6;
  2524. $listenaddr = '::1' if($listenaddr eq '127.0.0.1');
  2525. }
  2526. elsif($ARGV[0] eq '--port') {
  2527. if($ARGV[1] =~ /^(\d+)$/) {
  2528. $port = $1;
  2529. shift @ARGV;
  2530. }
  2531. }
  2532. elsif($ARGV[0] eq '--addr') {
  2533. if($ARGV[1]) {
  2534. my $tmpstr = $ARGV[1];
  2535. if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
  2536. $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
  2537. }
  2538. elsif($ipvnum == 6) {
  2539. $listenaddr = $tmpstr;
  2540. $listenaddr =~ s/^\[(.*)\]$/$1/;
  2541. }
  2542. shift @ARGV;
  2543. }
  2544. }
  2545. else {
  2546. print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
  2547. }
  2548. shift @ARGV;
  2549. }
  2550. #***************************************************************************
  2551. # Initialize command line option dependent variables
  2552. #
  2553. if(!$srcdir) {
  2554. $srcdir = $ENV{'srcdir'} || '.';
  2555. }
  2556. if(!$pidfile) {
  2557. $pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
  2558. }
  2559. if(!$logfile) {
  2560. $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
  2561. }
  2562. $mainsockf_pidfile = "$path/".
  2563. mainsockf_pidfilename($proto, $ipvnum, $idnum);
  2564. $mainsockf_logfile =
  2565. mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
  2566. if($proto eq 'ftp') {
  2567. $datasockf_pidfile = "$path/".
  2568. datasockf_pidfilename($proto, $ipvnum, $idnum);
  2569. $datasockf_logfile =
  2570. datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
  2571. }
  2572. $srvrname = servername_str($proto, $ipvnum, $idnum);
  2573. $idstr = "$idnum" if($idnum > 1);
  2574. protocolsetup($proto);
  2575. $SIG{INT} = \&exit_signal_handler;
  2576. $SIG{TERM} = \&exit_signal_handler;
  2577. startsf();
  2578. # actual port
  2579. if($portfile && !$port) {
  2580. my $aport;
  2581. open(P, "<$portfile");
  2582. $aport = <P>;
  2583. close(P);
  2584. $port = 0 + $aport;
  2585. }
  2586. logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
  2587. open(PID, ">$pidfile");
  2588. print PID $$."\n";
  2589. close(PID);
  2590. logmsg("logged pid $$ in $pidfile\n");
  2591. while(1) {
  2592. # kill previous data connection sockfilt when alive
  2593. if($datasockf_runs eq 'yes') {
  2594. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2595. logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
  2596. }
  2597. datasockf_state('STOPPED');
  2598. #
  2599. # We read 'sockfilt' commands.
  2600. #
  2601. my $input;
  2602. logmsg "Awaiting input\n";
  2603. sysread_or_die(\*SFREAD, \$input, 5);
  2604. if($input !~ /^CNCT/) {
  2605. # we wait for a connected client
  2606. logmsg "MAIN sockfilt said: $input";
  2607. next;
  2608. }
  2609. logmsg "====> Client connect\n";
  2610. set_advisor_read_lock($SERVERLOGS_LOCK);
  2611. $serverlogslocked = 1;
  2612. # flush data:
  2613. $| = 1;
  2614. &customize(); # read test control instructions
  2615. loadtest("$logdir/test$testno");
  2616. my $welcome = $commandreply{"welcome"};
  2617. if(!$welcome) {
  2618. $welcome = $displaytext{"welcome"};
  2619. }
  2620. else {
  2621. # clear it after use
  2622. $commandreply{"welcome"}="";
  2623. if($welcome !~ /\r\n\z/) {
  2624. $welcome .= "\r\n";
  2625. }
  2626. }
  2627. sendcontrol $welcome;
  2628. #remove global variables from last connection
  2629. if($ftplistparserstate) {
  2630. undef $ftplistparserstate;
  2631. }
  2632. if($ftptargetdir) {
  2633. $ftptargetdir = "";
  2634. }
  2635. if($verbose) {
  2636. print STDERR "OUT: $welcome";
  2637. }
  2638. my $full = "";
  2639. while(1) {
  2640. my $i;
  2641. # Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
  2642. # part only is FTP lingo.
  2643. # COMMAND
  2644. sysread_or_die(\*SFREAD, \$i, 5);
  2645. if($i !~ /^DATA/) {
  2646. logmsg "MAIN sockfilt said $i";
  2647. if($i =~ /^DISC/) {
  2648. # disconnect
  2649. last;
  2650. }
  2651. next;
  2652. }
  2653. # SIZE of data
  2654. sysread_or_die(\*SFREAD, \$i, 5);
  2655. my $size = 0;
  2656. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  2657. $size = hex($1);
  2658. }
  2659. # data
  2660. read_mainsockf(\$input, $size);
  2661. ftpmsg $input;
  2662. $full .= $input;
  2663. # Loop until command completion
  2664. next unless($full =~ /\r\n$/);
  2665. # Remove trailing CRLF.
  2666. $full =~ s/[\n\r]+$//;
  2667. my $FTPCMD;
  2668. my $FTPARG;
  2669. if($proto eq "imap") {
  2670. # IMAP is different with its identifier first on the command line
  2671. if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
  2672. ($full =~ /^([^ ]+) ([^ ]+)/)) {
  2673. $cmdid=$1; # set the global variable
  2674. $FTPCMD=$2;
  2675. $FTPARG=$3;
  2676. }
  2677. # IMAP authentication cancellation
  2678. elsif($full =~ /^\*$/) {
  2679. # Command id has already been set
  2680. $FTPCMD="*";
  2681. $FTPARG="";
  2682. }
  2683. # IMAP long "commands" are base64 authentication data
  2684. elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
  2685. # Command id has already been set
  2686. $FTPCMD=$full;
  2687. $FTPARG="";
  2688. }
  2689. else {
  2690. sendcontrol "$full BAD Command\r\n";
  2691. last;
  2692. }
  2693. }
  2694. elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
  2695. $FTPCMD=$1;
  2696. $FTPARG=$3;
  2697. }
  2698. elsif($proto eq "pop3") {
  2699. # POP3 authentication cancellation
  2700. if($full =~ /^\*$/) {
  2701. $FTPCMD="*";
  2702. $FTPARG="";
  2703. }
  2704. # POP3 long "commands" are base64 authentication data
  2705. elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
  2706. $FTPCMD=$full;
  2707. $FTPARG="";
  2708. }
  2709. else {
  2710. sendcontrol "-ERR Unrecognized command\r\n";
  2711. last;
  2712. }
  2713. }
  2714. elsif($proto eq "smtp") {
  2715. # SMTP authentication cancellation
  2716. if($full =~ /^\*$/) {
  2717. $FTPCMD="*";
  2718. $FTPARG="";
  2719. }
  2720. # SMTP long "commands" are base64 authentication data
  2721. elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) {
  2722. $FTPCMD=$full;
  2723. $FTPARG="";
  2724. }
  2725. else {
  2726. sendcontrol "500 Unrecognized command\r\n";
  2727. last;
  2728. }
  2729. }
  2730. else {
  2731. sendcontrol "500 Unrecognized command\r\n";
  2732. last;
  2733. }
  2734. logmsg "< \"$full\"\n";
  2735. if($verbose) {
  2736. print STDERR "IN: $full\n";
  2737. }
  2738. $full = "";
  2739. my $delay = $delayreply{$FTPCMD};
  2740. if($delay) {
  2741. # just go sleep this many seconds!
  2742. logmsg("Sleep for $delay seconds\n");
  2743. my $twentieths = $delay * 20;
  2744. while($twentieths--) {
  2745. portable_sleep(0.05) unless($got_exit_signal);
  2746. }
  2747. }
  2748. my $check = 1; # no response yet
  2749. # See if there is a custom reply for the full text
  2750. my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD;
  2751. my $text = $fulltextreply{$fulltext};
  2752. if($text && ($text ne "")) {
  2753. sendcontrol "$text\r\n";
  2754. $check = 0;
  2755. }
  2756. else {
  2757. # See if there is a custom reply for the command
  2758. $text = $commandreply{$FTPCMD};
  2759. if($text && ($text ne "")) {
  2760. if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
  2761. # used enough times so blank the custom command reply
  2762. $commandreply{$FTPCMD}="";
  2763. }
  2764. sendcontrol $text;
  2765. $check = 0;
  2766. }
  2767. else {
  2768. # See if there is any display text for the command
  2769. $text = $displaytext{$FTPCMD};
  2770. if($text && ($text ne "")) {
  2771. if($proto eq 'imap') {
  2772. sendcontrol "$cmdid $text\r\n";
  2773. }
  2774. else {
  2775. sendcontrol "$text\r\n";
  2776. }
  2777. $check = 0;
  2778. }
  2779. # only perform this if we're not faking a reply
  2780. my $func = $commandfunc{uc($FTPCMD)};
  2781. if($func) {
  2782. &$func($FTPARG, $FTPCMD);
  2783. $check = 0;
  2784. }
  2785. }
  2786. }
  2787. if($check) {
  2788. logmsg "$FTPCMD wasn't handled!\n";
  2789. if($proto eq 'pop3') {
  2790. sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
  2791. }
  2792. elsif($proto eq 'imap') {
  2793. sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
  2794. }
  2795. else {
  2796. sendcontrol "500 $FTPCMD is not dealt with!\r\n";
  2797. }
  2798. }
  2799. } # while(1)
  2800. logmsg "====> Client disconnected\n";
  2801. if($serverlogslocked) {
  2802. $serverlogslocked = 0;
  2803. clear_advisor_read_lock($SERVERLOGS_LOCK);
  2804. }
  2805. }
  2806. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  2807. unlink($pidfile);
  2808. if($serverlogslocked) {
  2809. $serverlogslocked = 0;
  2810. clear_advisor_read_lock($SERVERLOGS_LOCK);
  2811. }
  2812. exit;