2
0

ftpserver.pl 89 KB

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