ftpserver.pl 89 KB

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