ftpserver.pl 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298
  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.haxx.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 $path = '.';
  80. my $logdir = $path .'/log';
  81. #**********************************************************************
  82. # global vars used for server address and primary listener port
  83. #
  84. my $port = 8921; # default primary listener port
  85. my $listenaddr = '127.0.0.1'; # default address for listener port
  86. #**********************************************************************
  87. # global vars used for file names
  88. #
  89. my $pidfile; # server pid file name
  90. my $portfile=".ftpserver.port"; # server port file name
  91. my $logfile; # server log file name
  92. my $mainsockf_pidfile; # pid file for primary connection sockfilt process
  93. my $mainsockf_logfile; # log file for primary connection sockfilt process
  94. my $datasockf_pidfile; # pid file for secondary connection sockfilt process
  95. my $datasockf_logfile; # log file for secondary connection sockfilt process
  96. #**********************************************************************
  97. # global vars used for server logs advisor read lock handling
  98. #
  99. my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
  100. my $serverlogslocked = 0;
  101. #**********************************************************************
  102. # global vars used for child processes PID tracking
  103. #
  104. my $sfpid; # PID for primary connection sockfilt process
  105. my $slavepid; # PID for secondary connection sockfilt process
  106. #**********************************************************************
  107. # global typeglob filehandle vars to read/write from/to sockfilters
  108. #
  109. local *SFREAD; # used to read from primary connection
  110. local *SFWRITE; # used to write to primary connection
  111. local *DREAD; # used to read from secondary connection
  112. local *DWRITE; # used to write to secondary connection
  113. my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
  114. #**********************************************************************
  115. # global vars which depend on server protocol selection
  116. #
  117. my %commandfunc; # protocol command specific function callbacks
  118. my %displaytext; # text returned to client before callback runs
  119. #**********************************************************************
  120. # global vars customized for each test from the server commands file
  121. #
  122. my $ctrldelay; # set if server should throttle ctrl stream
  123. my $datadelay; # set if server should throttle data stream
  124. my $retrweirdo; # set if ftp server should use RETRWEIRDO
  125. my $retrnosize; # set if ftp server should use RETRNOSIZE
  126. my $pasvbadip; # set if ftp server should use PASVBADIP
  127. my $nosave; # set if ftp server should not save uploaded data
  128. my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
  129. my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
  130. my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
  131. my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
  132. my @capabilities; # set if server supports capability commands
  133. my @auth_mechs; # set if server supports authentication commands
  134. my %fulltextreply; #
  135. my %commandreply; #
  136. my %customcount; #
  137. my %delayreply; #
  138. #**********************************************************************
  139. # global variables for to test ftp wildcardmatching or other test that
  140. # need flexible LIST responses.. and corresponding files.
  141. # $ftptargetdir is keeping the fake "name" of LIST directory.
  142. #
  143. my $ftplistparserstate;
  144. my $ftptargetdir="";
  145. #**********************************************************************
  146. # global variables used when running a ftp server to keep state info
  147. # relative to the secondary or data sockfilt process. Values of these
  148. # variables should only be modified using datasockf_state() sub, given
  149. # that they are closely related and relationship is a bit awkward.
  150. #
  151. my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
  152. my $datasockf_mode = 'none'; # ['none','active','passive']
  153. my $datasockf_runs = 'no'; # ['no','yes']
  154. my $datasockf_conn = 'no'; # ['no','yes']
  155. #**********************************************************************
  156. # global vars used for signal handling
  157. #
  158. my $got_exit_signal = 0; # set if program should finish execution ASAP
  159. my $exit_signal; # first signal handled in exit_signal_handler
  160. #**********************************************************************
  161. # Mail related definitions
  162. #
  163. my $TEXT_PASSWORD = "secret";
  164. my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
  165. #**********************************************************************
  166. # exit_signal_handler will be triggered to indicate that the program
  167. # should finish its execution in a controlled way as soon as possible.
  168. # For now, program will also terminate from within this handler.
  169. #
  170. sub exit_signal_handler {
  171. my $signame = shift;
  172. # For now, simply mimic old behavior.
  173. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  174. unlink($pidfile);
  175. unlink($portfile);
  176. if($serverlogslocked) {
  177. $serverlogslocked = 0;
  178. clear_advisor_read_lock($SERVERLOGS_LOCK);
  179. }
  180. exit;
  181. }
  182. #**********************************************************************
  183. # logmsg is general message logging subroutine for our test servers.
  184. #
  185. sub logmsg {
  186. my $now;
  187. # sub second timestamping needs Time::HiRes
  188. if($Time::HiRes::VERSION) {
  189. my ($seconds, $usec) = gettimeofday();
  190. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  191. localtime($seconds);
  192. $now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
  193. }
  194. else {
  195. my $seconds = time();
  196. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  197. localtime($seconds);
  198. $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
  199. }
  200. if(open(LOGFILEFH, ">>$logfile")) {
  201. print LOGFILEFH $now;
  202. print LOGFILEFH @_;
  203. close(LOGFILEFH);
  204. }
  205. }
  206. sub ftpmsg {
  207. # append to the server.input file
  208. open(INPUT, ">>log/server$idstr.input") ||
  209. logmsg "failed to open log/server$idstr.input\n";
  210. print INPUT @_;
  211. close(INPUT);
  212. # use this, open->print->close system only to make the file
  213. # open as little as possible, to make the test suite run
  214. # better on windows/cygwin
  215. }
  216. #**********************************************************************
  217. # eXsysread is a wrapper around perl's sysread() function. This will
  218. # repeat the call to sysread() until it has actually read the complete
  219. # number of requested bytes or an unrecoverable condition occurs.
  220. # On success returns a positive value, the number of bytes requested.
  221. # On failure or timeout returns zero.
  222. #
  223. sub eXsysread {
  224. my $FH = shift;
  225. my $scalar = shift;
  226. my $nbytes = shift;
  227. my $timeout = shift; # A zero timeout disables eXsysread() time limit
  228. #
  229. my $time_limited = 0;
  230. my $timeout_rest = 0;
  231. my $start_time = 0;
  232. my $nread = 0;
  233. my $rc;
  234. $$scalar = "";
  235. if((not defined $nbytes) || ($nbytes < 1)) {
  236. logmsg "Error: eXsysread() failure: " .
  237. "length argument must be positive\n";
  238. return 0;
  239. }
  240. if((not defined $timeout) || ($timeout < 0)) {
  241. logmsg "Error: eXsysread() failure: " .
  242. "timeout argument must be zero or positive\n";
  243. return 0;
  244. }
  245. if($timeout > 0) {
  246. # caller sets eXsysread() time limit
  247. $time_limited = 1;
  248. $timeout_rest = $timeout;
  249. $start_time = int(time());
  250. }
  251. while($nread < $nbytes) {
  252. if($time_limited) {
  253. eval {
  254. local $SIG{ALRM} = sub { die "alarm\n"; };
  255. alarm $timeout_rest;
  256. $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
  257. alarm 0;
  258. };
  259. $timeout_rest = $timeout - (int(time()) - $start_time);
  260. if($timeout_rest < 1) {
  261. logmsg "Error: eXsysread() failure: timed out\n";
  262. return 0;
  263. }
  264. }
  265. else {
  266. $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
  267. }
  268. if($got_exit_signal) {
  269. logmsg "Error: eXsysread() failure: signalled to die\n";
  270. return 0;
  271. }
  272. if(not defined $rc) {
  273. if($!{EINTR}) {
  274. logmsg "Warning: retrying sysread() interrupted system call\n";
  275. next;
  276. }
  277. if($!{EAGAIN}) {
  278. logmsg "Warning: retrying sysread() due to EAGAIN\n";
  279. next;
  280. }
  281. if($!{EWOULDBLOCK}) {
  282. logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
  283. next;
  284. }
  285. logmsg "Error: sysread() failure: $!\n";
  286. return 0;
  287. }
  288. if($rc < 0) {
  289. logmsg "Error: sysread() failure: returned negative value $rc\n";
  290. return 0;
  291. }
  292. if($rc == 0) {
  293. logmsg "Error: sysread() failure: read zero bytes\n";
  294. return 0;
  295. }
  296. $nread += $rc;
  297. }
  298. return $nread;
  299. }
  300. #**********************************************************************
  301. # read_mainsockf attempts to read the given amount of output from the
  302. # sockfilter which is in use for the main or primary connection. This
  303. # reads untranslated sockfilt lingo which may hold data read from the
  304. # main or primary socket. On success returns 1, otherwise zero.
  305. #
  306. sub read_mainsockf {
  307. my $scalar = shift;
  308. my $nbytes = shift;
  309. my $timeout = shift; # Optional argument, if zero blocks indefinitely
  310. my $FH = \*SFREAD;
  311. if(not defined $timeout) {
  312. $timeout = $sockfilt_timeout + ($nbytes >> 12);
  313. }
  314. if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
  315. my ($fcaller, $lcaller) = (caller)[1,2];
  316. logmsg "Error: read_mainsockf() failure at $fcaller " .
  317. "line $lcaller. Due to eXsysread() failure\n";
  318. return 0;
  319. }
  320. return 1;
  321. }
  322. #**********************************************************************
  323. # read_datasockf attempts to read the given amount of output from the
  324. # sockfilter which is in use for the data or secondary connection. This
  325. # reads untranslated sockfilt lingo which may hold data read from the
  326. # data or secondary socket. On success returns 1, otherwise zero.
  327. #
  328. sub read_datasockf {
  329. my $scalar = shift;
  330. my $nbytes = shift;
  331. my $timeout = shift; # Optional argument, if zero blocks indefinitely
  332. my $FH = \*DREAD;
  333. if(not defined $timeout) {
  334. $timeout = $sockfilt_timeout + ($nbytes >> 12);
  335. }
  336. if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
  337. my ($fcaller, $lcaller) = (caller)[1,2];
  338. logmsg "Error: read_datasockf() failure at $fcaller " .
  339. "line $lcaller. Due to eXsysread() failure\n";
  340. return 0;
  341. }
  342. return 1;
  343. }
  344. sub sysread_or_die {
  345. my $FH = shift;
  346. my $scalar = shift;
  347. my $length = shift;
  348. my $fcaller;
  349. my $lcaller;
  350. my $result;
  351. $result = sysread($$FH, $$scalar, $length);
  352. if(not defined $result) {
  353. ($fcaller, $lcaller) = (caller)[1,2];
  354. logmsg "Failed to read input\n";
  355. logmsg "Error: $srvrname server, sysread error: $!\n";
  356. logmsg "Exited from sysread_or_die() at $fcaller " .
  357. "line $lcaller. $srvrname server, sysread error: $!\n";
  358. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  359. unlink($pidfile);
  360. unlink($portfile);
  361. if($serverlogslocked) {
  362. $serverlogslocked = 0;
  363. clear_advisor_read_lock($SERVERLOGS_LOCK);
  364. }
  365. exit;
  366. }
  367. elsif($result == 0) {
  368. ($fcaller, $lcaller) = (caller)[1,2];
  369. logmsg "Failed to read input\n";
  370. logmsg "Error: $srvrname server, read zero\n";
  371. logmsg "Exited from sysread_or_die() at $fcaller " .
  372. "line $lcaller. $srvrname server, read zero\n";
  373. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  374. unlink($pidfile);
  375. unlink($portfile);
  376. if($serverlogslocked) {
  377. $serverlogslocked = 0;
  378. clear_advisor_read_lock($SERVERLOGS_LOCK);
  379. }
  380. exit;
  381. }
  382. return $result;
  383. }
  384. sub startsf {
  385. my $mainsockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  386. "--ipv$ipvnum --port $port " .
  387. "--pidfile \"$mainsockf_pidfile\" " .
  388. "--portfile \"$portfile\" " .
  389. "--logfile \"$mainsockf_logfile\"";
  390. $sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
  391. print STDERR "$mainsockfcmd\n" if($verbose);
  392. print SFWRITE "PING\n";
  393. my $pong;
  394. sysread_or_die(\*SFREAD, \$pong, 5);
  395. if($pong !~ /^PONG/) {
  396. logmsg "Failed sockfilt command: $mainsockfcmd\n";
  397. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  398. unlink($pidfile);
  399. unlink($portfile);
  400. if($serverlogslocked) {
  401. $serverlogslocked = 0;
  402. clear_advisor_read_lock($SERVERLOGS_LOCK);
  403. }
  404. die "Failed to start sockfilt!";
  405. }
  406. }
  407. #**********************************************************************
  408. # Returns the given test's reply data
  409. #
  410. sub getreplydata {
  411. my ($testno) = @_;
  412. my $testpart = "";
  413. $testno =~ s/^([^0-9]*)//;
  414. if($testno > 10000) {
  415. $testpart = $testno % 10000;
  416. $testno = int($testno / 10000);
  417. }
  418. loadtest("$srcdir/data/test$testno");
  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("$srcdir/data/test$cwd_testno");
  1740. my @data = getpart("reply", "data");
  1741. for(@data) {
  1742. my $send = $_;
  1743. # convert all \n to \r\n for ASCII transfer
  1744. $send =~ s/\r\n/\n/g;
  1745. $send =~ s/\n/\r\n/g;
  1746. logmsg "send $send as data\n";
  1747. senddata $send;
  1748. }
  1749. $cwd_testno = 0; # forget it again
  1750. }
  1751. else {
  1752. # old hard-coded style
  1753. for(@ftpdir) {
  1754. senddata $_;
  1755. }
  1756. }
  1757. close_dataconn(0);
  1758. sendcontrol "226 ASCII transfer complete\r\n";
  1759. return 0;
  1760. }
  1761. sub NLST_ftp {
  1762. my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
  1763. if($datasockf_conn eq 'no') {
  1764. if($nodataconn425) {
  1765. sendcontrol "150 Opening data connection\r\n";
  1766. sendcontrol "425 Can't open data connection\r\n";
  1767. }
  1768. elsif($nodataconn421) {
  1769. sendcontrol "150 Opening data connection\r\n";
  1770. sendcontrol "421 Connection timed out\r\n";
  1771. }
  1772. elsif($nodataconn150) {
  1773. sendcontrol "150 Opening data connection\r\n";
  1774. # client shall timeout
  1775. }
  1776. else {
  1777. # client shall timeout
  1778. }
  1779. return 0;
  1780. }
  1781. logmsg "pass NLST data on data connection\n";
  1782. for(@ftpdir) {
  1783. senddata "$_\r\n";
  1784. }
  1785. close_dataconn(0);
  1786. sendcontrol "226 ASCII transfer complete\r\n";
  1787. return 0;
  1788. }
  1789. sub MDTM_ftp {
  1790. my $testno = $_[0];
  1791. my $testpart = "";
  1792. if ($testno > 10000) {
  1793. $testpart = $testno % 10000;
  1794. $testno = int($testno / 10000);
  1795. }
  1796. loadtest("$srcdir/data/test$testno");
  1797. my @data = getpart("reply", "mdtm");
  1798. my $reply = $data[0];
  1799. chomp $reply if($reply);
  1800. if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
  1801. sendcontrol "550 $testno: no such file.\r\n";
  1802. }
  1803. elsif($reply) {
  1804. sendcontrol "$reply\r\n";
  1805. }
  1806. else {
  1807. sendcontrol "500 MDTM: no such command.\r\n";
  1808. }
  1809. return 0;
  1810. }
  1811. sub SIZE_ftp {
  1812. my $testno = $_[0];
  1813. if($ftplistparserstate) {
  1814. my $size = wildcard_filesize($ftptargetdir, $testno);
  1815. if($size == -1) {
  1816. sendcontrol "550 $testno: No such file or directory.\r\n";
  1817. }
  1818. else {
  1819. sendcontrol "213 $size\r\n";
  1820. }
  1821. return 0;
  1822. }
  1823. if($testno =~ /^verifiedserver$/) {
  1824. my $response = "WE ROOLZ: $$\r\n";
  1825. my $size = length($response);
  1826. sendcontrol "213 $size\r\n";
  1827. return 0;
  1828. }
  1829. if($testno =~ /(\d+)\/?$/) {
  1830. $testno = $1;
  1831. }
  1832. else {
  1833. print STDERR "SIZE_ftp: invalid test number: $testno\n";
  1834. return 1;
  1835. }
  1836. my $testpart = "";
  1837. if($testno > 10000) {
  1838. $testpart = $testno % 10000;
  1839. $testno = int($testno / 10000);
  1840. }
  1841. loadtest("$srcdir/data/test$testno");
  1842. my @data = getpart("reply", "size");
  1843. my $size = $data[0];
  1844. if($size) {
  1845. if($size > -1) {
  1846. sendcontrol "213 $size\r\n";
  1847. }
  1848. else {
  1849. sendcontrol "550 $testno: No such file or directory.\r\n";
  1850. }
  1851. }
  1852. else {
  1853. $size=0;
  1854. @data = getpart("reply", "data$testpart");
  1855. for(@data) {
  1856. $size += length($_);
  1857. }
  1858. if($size) {
  1859. sendcontrol "213 $size\r\n";
  1860. }
  1861. else {
  1862. sendcontrol "550 $testno: No such file or directory.\r\n";
  1863. }
  1864. }
  1865. return 0;
  1866. }
  1867. sub RETR_ftp {
  1868. my ($testno) = @_;
  1869. if($datasockf_conn eq 'no') {
  1870. if($nodataconn425) {
  1871. sendcontrol "150 Opening data connection\r\n";
  1872. sendcontrol "425 Can't open data connection\r\n";
  1873. }
  1874. elsif($nodataconn421) {
  1875. sendcontrol "150 Opening data connection\r\n";
  1876. sendcontrol "421 Connection timed out\r\n";
  1877. }
  1878. elsif($nodataconn150) {
  1879. sendcontrol "150 Opening data connection\r\n";
  1880. # client shall timeout
  1881. }
  1882. else {
  1883. # client shall timeout
  1884. }
  1885. return 0;
  1886. }
  1887. if($ftplistparserstate) {
  1888. my @content = wildcard_getfile($ftptargetdir, $testno);
  1889. if($content[0] == -1) {
  1890. #file not found
  1891. }
  1892. else {
  1893. my $size = length $content[1];
  1894. sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
  1895. senddata $content[1];
  1896. close_dataconn(0);
  1897. sendcontrol "226 File transfer complete\r\n";
  1898. }
  1899. return 0;
  1900. }
  1901. if($testno =~ /^verifiedserver$/) {
  1902. # this is the secret command that verifies that this actually is
  1903. # the curl test server
  1904. my $response = "WE ROOLZ: $$\r\n";
  1905. my $len = length($response);
  1906. sendcontrol "150 Binary junk ($len bytes).\r\n";
  1907. senddata "WE ROOLZ: $$\r\n";
  1908. close_dataconn(0);
  1909. sendcontrol "226 File transfer complete\r\n";
  1910. if($verbose) {
  1911. print STDERR "FTPD: We returned proof we are the test server\n";
  1912. }
  1913. return 0;
  1914. }
  1915. $testno =~ s/^([^0-9]*)//;
  1916. my $testpart = "";
  1917. if ($testno > 10000) {
  1918. $testpart = $testno % 10000;
  1919. $testno = int($testno / 10000);
  1920. }
  1921. loadtest("$srcdir/data/test$testno");
  1922. my @data = getpart("reply", "data$testpart");
  1923. my $size=0;
  1924. for(@data) {
  1925. $size += length($_);
  1926. }
  1927. my %hash = getpartattr("reply", "data$testpart");
  1928. if($size || $hash{'sendzero'}) {
  1929. if($rest) {
  1930. # move read pointer forward
  1931. $size -= $rest;
  1932. logmsg "REST $rest was removed from size, makes $size left\n";
  1933. $rest = 0; # reset REST offset again
  1934. }
  1935. if($retrweirdo) {
  1936. sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
  1937. "226 File transfer complete\r\n";
  1938. for(@data) {
  1939. my $send = $_;
  1940. senddata $send;
  1941. }
  1942. close_dataconn(0);
  1943. $retrweirdo=0; # switch off the weirdo again!
  1944. }
  1945. else {
  1946. my $sz = "($size bytes)";
  1947. if($retrnosize) {
  1948. $sz = "size?";
  1949. }
  1950. sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
  1951. for(@data) {
  1952. my $send = $_;
  1953. senddata $send;
  1954. }
  1955. close_dataconn(0);
  1956. sendcontrol "226 File transfer complete\r\n";
  1957. }
  1958. }
  1959. else {
  1960. sendcontrol "550 $testno: No such file or directory.\r\n";
  1961. }
  1962. return 0;
  1963. }
  1964. sub STOR_ftp {
  1965. my $testno=$_[0];
  1966. my $filename = "log/upload.$testno";
  1967. if($datasockf_conn eq 'no') {
  1968. if($nodataconn425) {
  1969. sendcontrol "150 Opening data connection\r\n";
  1970. sendcontrol "425 Can't open data connection\r\n";
  1971. }
  1972. elsif($nodataconn421) {
  1973. sendcontrol "150 Opening data connection\r\n";
  1974. sendcontrol "421 Connection timed out\r\n";
  1975. }
  1976. elsif($nodataconn150) {
  1977. sendcontrol "150 Opening data connection\r\n";
  1978. # client shall timeout
  1979. }
  1980. else {
  1981. # client shall timeout
  1982. }
  1983. return 0;
  1984. }
  1985. logmsg "STOR test number $testno in $filename\n";
  1986. sendcontrol "125 Gimme gimme gimme!\r\n";
  1987. open(FILE, ">$filename") ||
  1988. return 0; # failed to open output
  1989. my $line;
  1990. my $ulsize=0;
  1991. my $disc=0;
  1992. while (5 == (sysread DREAD, $line, 5)) {
  1993. if($line eq "DATA\n") {
  1994. my $i;
  1995. sysread DREAD, $i, 5;
  1996. my $size = 0;
  1997. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  1998. $size = hex($1);
  1999. }
  2000. read_datasockf(\$line, $size);
  2001. #print STDERR " GOT: $size bytes\n";
  2002. $ulsize += $size;
  2003. print FILE $line if(!$nosave);
  2004. logmsg "> Appending $size bytes to file\n";
  2005. }
  2006. elsif($line eq "DISC\n") {
  2007. # disconnect!
  2008. $disc=1;
  2009. last;
  2010. }
  2011. else {
  2012. logmsg "No support for: $line";
  2013. last;
  2014. }
  2015. }
  2016. if($nosave) {
  2017. print FILE "$ulsize bytes would've been stored here\n";
  2018. }
  2019. close(FILE);
  2020. close_dataconn($disc);
  2021. logmsg "received $ulsize bytes upload\n";
  2022. sendcontrol "226 File transfer complete\r\n";
  2023. return 0;
  2024. }
  2025. sub PASV_ftp {
  2026. my ($arg, $cmd)=@_;
  2027. my $pasvport;
  2028. my $bindonly = ($nodataconn) ? '--bindonly' : '';
  2029. # kill previous data connection sockfilt when alive
  2030. if($datasockf_runs eq 'yes') {
  2031. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2032. logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
  2033. }
  2034. datasockf_state('STOPPED');
  2035. logmsg "====> Passive DATA channel requested by client\n";
  2036. logmsg "DATA sockfilt for passive data channel starting...\n";
  2037. # We fire up a new sockfilt to do the data transfer for us.
  2038. my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  2039. "--ipv$ipvnum $bindonly --port 0 " .
  2040. "--pidfile \"$datasockf_pidfile\" " .
  2041. "--logfile \"$datasockf_logfile\"";
  2042. $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
  2043. if($nodataconn) {
  2044. datasockf_state('PASSIVE_NODATACONN');
  2045. }
  2046. else {
  2047. datasockf_state('PASSIVE');
  2048. }
  2049. print STDERR "$datasockfcmd\n" if($verbose);
  2050. print DWRITE "PING\n";
  2051. my $pong;
  2052. sysread_or_die(\*DREAD, \$pong, 5);
  2053. if($pong =~ /^FAIL/) {
  2054. logmsg "DATA sockfilt said: FAIL\n";
  2055. logmsg "DATA sockfilt for passive data channel failed\n";
  2056. logmsg "DATA sockfilt not running\n";
  2057. datasockf_state('STOPPED');
  2058. sendcontrol "500 no free ports!\r\n";
  2059. return;
  2060. }
  2061. elsif($pong !~ /^PONG/) {
  2062. logmsg "DATA sockfilt unexpected response: $pong\n";
  2063. logmsg "DATA sockfilt for passive data channel failed\n";
  2064. logmsg "DATA sockfilt killed now\n";
  2065. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2066. logmsg "DATA sockfilt not running\n";
  2067. datasockf_state('STOPPED');
  2068. sendcontrol "500 no free ports!\r\n";
  2069. return;
  2070. }
  2071. logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
  2072. # Find out on what port we listen on or have bound
  2073. my $i;
  2074. print DWRITE "PORT\n";
  2075. # READ the response code
  2076. sysread_or_die(\*DREAD, \$i, 5);
  2077. # READ the response size
  2078. sysread_or_die(\*DREAD, \$i, 5);
  2079. my $size = 0;
  2080. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  2081. $size = hex($1);
  2082. }
  2083. # READ the response data
  2084. read_datasockf(\$i, $size);
  2085. # The data is in the format
  2086. # IPvX/NNN
  2087. if($i =~ /IPv(\d)\/(\d+)/) {
  2088. # FIX: deal with IP protocol version
  2089. $pasvport = $2;
  2090. }
  2091. if(!$pasvport) {
  2092. logmsg "DATA sockfilt unknown listener port\n";
  2093. logmsg "DATA sockfilt for passive data channel failed\n";
  2094. logmsg "DATA sockfilt killed now\n";
  2095. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2096. logmsg "DATA sockfilt not running\n";
  2097. datasockf_state('STOPPED');
  2098. sendcontrol "500 no free ports!\r\n";
  2099. return;
  2100. }
  2101. if($nodataconn) {
  2102. my $str = nodataconn_str();
  2103. logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
  2104. "$pasvport\n";
  2105. }
  2106. else {
  2107. logmsg "DATA sockfilt for passive data channel listens on port ".
  2108. "$pasvport\n";
  2109. }
  2110. if($cmd ne "EPSV") {
  2111. # PASV reply
  2112. my $p=$listenaddr;
  2113. $p =~ s/\./,/g;
  2114. if($pasvbadip) {
  2115. $p="1,2,3,4";
  2116. }
  2117. sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
  2118. int($pasvport/256), int($pasvport%256));
  2119. }
  2120. else {
  2121. # EPSV reply
  2122. sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
  2123. }
  2124. logmsg "Client has been notified that DATA conn ".
  2125. "will be accepted on port $pasvport\n";
  2126. if($nodataconn) {
  2127. my $str = nodataconn_str();
  2128. logmsg "====> Client fooled ($str)\n";
  2129. return;
  2130. }
  2131. eval {
  2132. local $SIG{ALRM} = sub { die "alarm\n" };
  2133. # assume swift operations unless explicitly slow
  2134. alarm ($datadelay?20:10);
  2135. # Wait for 'CNCT'
  2136. my $input;
  2137. # FIX: Monitor ctrl conn for disconnect
  2138. while(sysread(DREAD, $input, 5)) {
  2139. if($input !~ /^CNCT/) {
  2140. # we wait for a connected client
  2141. logmsg "Odd, we got $input from client\n";
  2142. next;
  2143. }
  2144. logmsg "Client connects to port $pasvport\n";
  2145. last;
  2146. }
  2147. alarm 0;
  2148. };
  2149. if ($@) {
  2150. # timed out
  2151. logmsg "$srvrname server timed out awaiting data connection ".
  2152. "on port $pasvport\n";
  2153. logmsg "accept failed or connection not even attempted\n";
  2154. logmsg "DATA sockfilt killed now\n";
  2155. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2156. logmsg "DATA sockfilt not running\n";
  2157. datasockf_state('STOPPED');
  2158. return;
  2159. }
  2160. else {
  2161. logmsg "====> Client established passive DATA connection ".
  2162. "on port $pasvport\n";
  2163. }
  2164. return;
  2165. }
  2166. #
  2167. # Support both PORT and EPRT here.
  2168. #
  2169. sub PORT_ftp {
  2170. my ($arg, $cmd) = @_;
  2171. my $port;
  2172. my $addr;
  2173. # kill previous data connection sockfilt when alive
  2174. if($datasockf_runs eq 'yes') {
  2175. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2176. logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
  2177. }
  2178. datasockf_state('STOPPED');
  2179. logmsg "====> Active DATA channel requested by client\n";
  2180. # We always ignore the given IP and use localhost.
  2181. if($cmd eq "PORT") {
  2182. if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
  2183. logmsg "DATA sockfilt for active data channel not started ".
  2184. "(bad PORT-line: $arg)\n";
  2185. sendcontrol "500 silly you, go away\r\n";
  2186. return;
  2187. }
  2188. $port = ($5<<8)+$6;
  2189. $addr = "$1.$2.$3.$4";
  2190. }
  2191. # EPRT |2|::1|49706|
  2192. elsif($cmd eq "EPRT") {
  2193. if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
  2194. logmsg "DATA sockfilt for active data channel not started ".
  2195. "(bad EPRT-line: $arg)\n";
  2196. sendcontrol "500 silly you, go away\r\n";
  2197. return;
  2198. }
  2199. sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
  2200. $port = $3;
  2201. $addr = $2;
  2202. }
  2203. else {
  2204. logmsg "DATA sockfilt for active data channel not started ".
  2205. "(invalid command: $cmd)\n";
  2206. sendcontrol "500 we don't like $cmd now\r\n";
  2207. return;
  2208. }
  2209. if(!$port || $port > 65535) {
  2210. logmsg "DATA sockfilt for active data channel not started ".
  2211. "(illegal PORT number: $port)\n";
  2212. return;
  2213. }
  2214. if($nodataconn) {
  2215. my $str = nodataconn_str();
  2216. logmsg "DATA sockfilt for active data channel not started ($str)\n";
  2217. datasockf_state('ACTIVE_NODATACONN');
  2218. logmsg "====> Active DATA channel not established\n";
  2219. return;
  2220. }
  2221. logmsg "DATA sockfilt for active data channel starting...\n";
  2222. # We fire up a new sockfilt to do the data transfer for us.
  2223. my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
  2224. "--ipv$ipvnum --connect $port --addr \"$addr\" " .
  2225. "--pidfile \"$datasockf_pidfile\" " .
  2226. "--logfile \"$datasockf_logfile\"";
  2227. $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
  2228. datasockf_state('ACTIVE');
  2229. print STDERR "$datasockfcmd\n" if($verbose);
  2230. print DWRITE "PING\n";
  2231. my $pong;
  2232. sysread_or_die(\*DREAD, \$pong, 5);
  2233. if($pong =~ /^FAIL/) {
  2234. logmsg "DATA sockfilt said: FAIL\n";
  2235. logmsg "DATA sockfilt for active data channel failed\n";
  2236. logmsg "DATA sockfilt not running\n";
  2237. datasockf_state('STOPPED');
  2238. # client shall timeout awaiting connection from server
  2239. return;
  2240. }
  2241. elsif($pong !~ /^PONG/) {
  2242. logmsg "DATA sockfilt unexpected response: $pong\n";
  2243. logmsg "DATA sockfilt for active data channel failed\n";
  2244. logmsg "DATA sockfilt killed now\n";
  2245. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2246. logmsg "DATA sockfilt not running\n";
  2247. datasockf_state('STOPPED');
  2248. # client shall timeout awaiting connection from server
  2249. return;
  2250. }
  2251. logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
  2252. logmsg "====> Active DATA channel connected to client port $port\n";
  2253. return;
  2254. }
  2255. #**********************************************************************
  2256. # datasockf_state is used to change variables that keep state info
  2257. # relative to the FTP secondary or data sockfilt process as soon as
  2258. # one of the five possible stable states is reached. Variables that
  2259. # are modified by this sub may be checked independently but should
  2260. # not be changed except by calling this sub.
  2261. #
  2262. sub datasockf_state {
  2263. my $state = $_[0];
  2264. if($state eq 'STOPPED') {
  2265. # Data sockfilter initial state, not running,
  2266. # not connected and not used.
  2267. $datasockf_state = $state;
  2268. $datasockf_mode = 'none';
  2269. $datasockf_runs = 'no';
  2270. $datasockf_conn = 'no';
  2271. }
  2272. elsif($state eq 'PASSIVE') {
  2273. # Data sockfilter accepted connection from client.
  2274. $datasockf_state = $state;
  2275. $datasockf_mode = 'passive';
  2276. $datasockf_runs = 'yes';
  2277. $datasockf_conn = 'yes';
  2278. }
  2279. elsif($state eq 'ACTIVE') {
  2280. # Data sockfilter has connected to client.
  2281. $datasockf_state = $state;
  2282. $datasockf_mode = 'active';
  2283. $datasockf_runs = 'yes';
  2284. $datasockf_conn = 'yes';
  2285. }
  2286. elsif($state eq 'PASSIVE_NODATACONN') {
  2287. # Data sockfilter bound port without listening,
  2288. # client won't be able to establish data connection.
  2289. $datasockf_state = $state;
  2290. $datasockf_mode = 'passive';
  2291. $datasockf_runs = 'yes';
  2292. $datasockf_conn = 'no';
  2293. }
  2294. elsif($state eq 'ACTIVE_NODATACONN') {
  2295. # Data sockfilter does not even run,
  2296. # client awaits data connection from server in vain.
  2297. $datasockf_state = $state;
  2298. $datasockf_mode = 'active';
  2299. $datasockf_runs = 'no';
  2300. $datasockf_conn = 'no';
  2301. }
  2302. else {
  2303. die "Internal error. Unknown datasockf state: $state!";
  2304. }
  2305. }
  2306. #**********************************************************************
  2307. # nodataconn_str returns string of effective nodataconn command. Notice
  2308. # that $nodataconn may be set alone or in addition to a $nodataconnXXX.
  2309. #
  2310. sub nodataconn_str {
  2311. my $str;
  2312. # order matters
  2313. $str = 'NODATACONN' if($nodataconn);
  2314. $str = 'NODATACONN425' if($nodataconn425);
  2315. $str = 'NODATACONN421' if($nodataconn421);
  2316. $str = 'NODATACONN150' if($nodataconn150);
  2317. return "$str";
  2318. }
  2319. #**********************************************************************
  2320. # customize configures test server operation for each curl test, reading
  2321. # configuration commands/parameters from server commands file each time
  2322. # a new client control connection is established with the test server.
  2323. # On success returns 1, otherwise zero.
  2324. #
  2325. sub customize {
  2326. $ctrldelay = 0; # default is no throttling of the ctrl stream
  2327. $datadelay = 0; # default is no throttling of the data stream
  2328. $retrweirdo = 0; # default is no use of RETRWEIRDO
  2329. $retrnosize = 0; # default is no use of RETRNOSIZE
  2330. $pasvbadip = 0; # default is no use of PASVBADIP
  2331. $nosave = 0; # default is to actually save uploaded data to file
  2332. $nodataconn = 0; # default is to establish or accept data channel
  2333. $nodataconn425 = 0; # default is to not send 425 without data channel
  2334. $nodataconn421 = 0; # default is to not send 421 without data channel
  2335. $nodataconn150 = 0; # default is to not send 150 without data channel
  2336. @capabilities = (); # default is to not support capability commands
  2337. @auth_mechs = (); # default is to not support authentication commands
  2338. %fulltextreply = ();#
  2339. %commandreply = (); #
  2340. %customcount = (); #
  2341. %delayreply = (); #
  2342. open(CUSTOM, "<log/ftpserver.cmd") ||
  2343. return 1;
  2344. logmsg "FTPD: Getting commands from log/ftpserver.cmd\n";
  2345. while(<CUSTOM>) {
  2346. if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) {
  2347. $fulltextreply{$1}=eval "qq{$2}";
  2348. logmsg "FTPD: set custom reply for $1\n";
  2349. }
  2350. elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) {
  2351. $commandreply{$2}=eval "qq{$3}";
  2352. if($1 ne "LF") {
  2353. $commandreply{$2}.="\r\n";
  2354. }
  2355. else {
  2356. $commandreply{$2}.="\n";
  2357. }
  2358. if($2 eq "") {
  2359. logmsg "FTPD: set custom reply for empty command\n";
  2360. }
  2361. else {
  2362. logmsg "FTPD: set custom reply for $2 command\n";
  2363. }
  2364. }
  2365. elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
  2366. # we blank the custom reply for this command when having
  2367. # been used this number of times
  2368. $customcount{$1}=$2;
  2369. logmsg "FTPD: blank custom reply for $1 command after $2 uses\n";
  2370. }
  2371. elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
  2372. $delayreply{$1}=$2;
  2373. logmsg "FTPD: delay reply for $1 with $2 seconds\n";
  2374. }
  2375. elsif($_ =~ /SLOWDOWN/) {
  2376. $ctrldelay=1;
  2377. $datadelay=1;
  2378. logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
  2379. }
  2380. elsif($_ =~ /RETRWEIRDO/) {
  2381. logmsg "FTPD: instructed to use RETRWEIRDO\n";
  2382. $retrweirdo=1;
  2383. }
  2384. elsif($_ =~ /RETRNOSIZE/) {
  2385. logmsg "FTPD: instructed to use RETRNOSIZE\n";
  2386. $retrnosize=1;
  2387. }
  2388. elsif($_ =~ /PASVBADIP/) {
  2389. logmsg "FTPD: instructed to use PASVBADIP\n";
  2390. $pasvbadip=1;
  2391. }
  2392. elsif($_ =~ /NODATACONN425/) {
  2393. # applies to both active and passive FTP modes
  2394. logmsg "FTPD: instructed to use NODATACONN425\n";
  2395. $nodataconn425=1;
  2396. $nodataconn=1;
  2397. }
  2398. elsif($_ =~ /NODATACONN421/) {
  2399. # applies to both active and passive FTP modes
  2400. logmsg "FTPD: instructed to use NODATACONN421\n";
  2401. $nodataconn421=1;
  2402. $nodataconn=1;
  2403. }
  2404. elsif($_ =~ /NODATACONN150/) {
  2405. # applies to both active and passive FTP modes
  2406. logmsg "FTPD: instructed to use NODATACONN150\n";
  2407. $nodataconn150=1;
  2408. $nodataconn=1;
  2409. }
  2410. elsif($_ =~ /NODATACONN/) {
  2411. # applies to both active and passive FTP modes
  2412. logmsg "FTPD: instructed to use NODATACONN\n";
  2413. $nodataconn=1;
  2414. }
  2415. elsif($_ =~ /CAPA (.*)/) {
  2416. logmsg "FTPD: instructed to support CAPABILITY command\n";
  2417. @capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1);
  2418. foreach (@capabilities) {
  2419. $_ = $1 if /^"(.*)"$/;
  2420. }
  2421. }
  2422. elsif($_ =~ /AUTH (.*)/) {
  2423. logmsg "FTPD: instructed to support AUTHENTICATION command\n";
  2424. @auth_mechs = split(/ /, $1);
  2425. }
  2426. elsif($_ =~ /NOSAVE/) {
  2427. # don't actually store the file we upload - to be used when
  2428. # uploading insanely huge amounts
  2429. $nosave = 1;
  2430. logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
  2431. }
  2432. }
  2433. close(CUSTOM);
  2434. }
  2435. #----------------------------------------------------------------------
  2436. #----------------------------------------------------------------------
  2437. #--------------------------- END OF SUBS ----------------------------
  2438. #----------------------------------------------------------------------
  2439. #----------------------------------------------------------------------
  2440. #**********************************************************************
  2441. # Parse command line options
  2442. #
  2443. # Options:
  2444. #
  2445. # --verbose # verbose
  2446. # --srcdir # source directory
  2447. # --id # server instance number
  2448. # --proto # server protocol
  2449. # --pidfile # server pid file
  2450. # --portfile # server port file
  2451. # --logfile # server log file
  2452. # --ipv4 # server IP version 4
  2453. # --ipv6 # server IP version 6
  2454. # --port # server listener port
  2455. # --addr # server address for listener port binding
  2456. #
  2457. while(@ARGV) {
  2458. if($ARGV[0] eq '--verbose') {
  2459. $verbose = 1;
  2460. }
  2461. elsif($ARGV[0] eq '--srcdir') {
  2462. if($ARGV[1]) {
  2463. $srcdir = $ARGV[1];
  2464. shift @ARGV;
  2465. }
  2466. }
  2467. elsif($ARGV[0] eq '--id') {
  2468. if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
  2469. $idnum = $1 if($1 > 0);
  2470. shift @ARGV;
  2471. }
  2472. }
  2473. elsif($ARGV[0] eq '--proto') {
  2474. if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
  2475. $proto = $1;
  2476. shift @ARGV;
  2477. }
  2478. else {
  2479. die "unsupported protocol $ARGV[1]";
  2480. }
  2481. }
  2482. elsif($ARGV[0] eq '--pidfile') {
  2483. if($ARGV[1]) {
  2484. $pidfile = $ARGV[1];
  2485. shift @ARGV;
  2486. }
  2487. }
  2488. elsif($ARGV[0] eq '--portfile') {
  2489. if($ARGV[1]) {
  2490. $portfile = $ARGV[1];
  2491. shift @ARGV;
  2492. }
  2493. }
  2494. elsif($ARGV[0] eq '--logfile') {
  2495. if($ARGV[1]) {
  2496. $logfile = $ARGV[1];
  2497. shift @ARGV;
  2498. }
  2499. }
  2500. elsif($ARGV[0] eq '--ipv4') {
  2501. $ipvnum = 4;
  2502. $listenaddr = '127.0.0.1' if($listenaddr eq '::1');
  2503. }
  2504. elsif($ARGV[0] eq '--ipv6') {
  2505. $ipvnum = 6;
  2506. $listenaddr = '::1' if($listenaddr eq '127.0.0.1');
  2507. }
  2508. elsif($ARGV[0] eq '--port') {
  2509. if($ARGV[1] =~ /^(\d+)$/) {
  2510. $port = $1;
  2511. shift @ARGV;
  2512. }
  2513. }
  2514. elsif($ARGV[0] eq '--addr') {
  2515. if($ARGV[1]) {
  2516. my $tmpstr = $ARGV[1];
  2517. if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
  2518. $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
  2519. }
  2520. elsif($ipvnum == 6) {
  2521. $listenaddr = $tmpstr;
  2522. $listenaddr =~ s/^\[(.*)\]$/$1/;
  2523. }
  2524. shift @ARGV;
  2525. }
  2526. }
  2527. else {
  2528. print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
  2529. }
  2530. shift @ARGV;
  2531. }
  2532. #***************************************************************************
  2533. # Initialize command line option dependent variables
  2534. #
  2535. if(!$srcdir) {
  2536. $srcdir = $ENV{'srcdir'} || '.';
  2537. }
  2538. if(!$pidfile) {
  2539. $pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
  2540. }
  2541. if(!$logfile) {
  2542. $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
  2543. }
  2544. $mainsockf_pidfile = "$path/".
  2545. mainsockf_pidfilename($proto, $ipvnum, $idnum);
  2546. $mainsockf_logfile =
  2547. mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
  2548. if($proto eq 'ftp') {
  2549. $datasockf_pidfile = "$path/".
  2550. datasockf_pidfilename($proto, $ipvnum, $idnum);
  2551. $datasockf_logfile =
  2552. datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
  2553. }
  2554. $srvrname = servername_str($proto, $ipvnum, $idnum);
  2555. $idstr = "$idnum" if($idnum > 1);
  2556. protocolsetup($proto);
  2557. $SIG{INT} = \&exit_signal_handler;
  2558. $SIG{TERM} = \&exit_signal_handler;
  2559. startsf();
  2560. # actual port
  2561. if($portfile && !$port) {
  2562. my $aport;
  2563. open(P, "<$portfile");
  2564. $aport = <P>;
  2565. close(P);
  2566. $port = 0 + $aport;
  2567. }
  2568. logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
  2569. open(PID, ">$pidfile");
  2570. print PID $$."\n";
  2571. close(PID);
  2572. logmsg("logged pid $$ in $pidfile\n");
  2573. while(1) {
  2574. # kill previous data connection sockfilt when alive
  2575. if($datasockf_runs eq 'yes') {
  2576. killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
  2577. logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
  2578. }
  2579. datasockf_state('STOPPED');
  2580. #
  2581. # We read 'sockfilt' commands.
  2582. #
  2583. my $input;
  2584. logmsg "Awaiting input\n";
  2585. sysread_or_die(\*SFREAD, \$input, 5);
  2586. if($input !~ /^CNCT/) {
  2587. # we wait for a connected client
  2588. logmsg "MAIN sockfilt said: $input";
  2589. next;
  2590. }
  2591. logmsg "====> Client connect\n";
  2592. set_advisor_read_lock($SERVERLOGS_LOCK);
  2593. $serverlogslocked = 1;
  2594. # flush data:
  2595. $| = 1;
  2596. &customize(); # read test control instructions
  2597. my $welcome = $commandreply{"welcome"};
  2598. if(!$welcome) {
  2599. $welcome = $displaytext{"welcome"};
  2600. }
  2601. else {
  2602. # clear it after use
  2603. $commandreply{"welcome"}="";
  2604. if($welcome !~ /\r\n\z/) {
  2605. $welcome .= "\r\n";
  2606. }
  2607. }
  2608. sendcontrol $welcome;
  2609. #remove global variables from last connection
  2610. if($ftplistparserstate) {
  2611. undef $ftplistparserstate;
  2612. }
  2613. if($ftptargetdir) {
  2614. $ftptargetdir = "";
  2615. }
  2616. if($verbose) {
  2617. print STDERR "OUT: $welcome";
  2618. }
  2619. my $full = "";
  2620. while(1) {
  2621. my $i;
  2622. # Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
  2623. # part only is FTP lingo.
  2624. # COMMAND
  2625. sysread_or_die(\*SFREAD, \$i, 5);
  2626. if($i !~ /^DATA/) {
  2627. logmsg "MAIN sockfilt said $i";
  2628. if($i =~ /^DISC/) {
  2629. # disconnect
  2630. last;
  2631. }
  2632. next;
  2633. }
  2634. # SIZE of data
  2635. sysread_or_die(\*SFREAD, \$i, 5);
  2636. my $size = 0;
  2637. if($i =~ /^([0-9a-fA-F]{4})\n/) {
  2638. $size = hex($1);
  2639. }
  2640. # data
  2641. read_mainsockf(\$input, $size);
  2642. ftpmsg $input;
  2643. $full .= $input;
  2644. # Loop until command completion
  2645. next unless($full =~ /\r\n$/);
  2646. # Remove trailing CRLF.
  2647. $full =~ s/[\n\r]+$//;
  2648. my $FTPCMD;
  2649. my $FTPARG;
  2650. if($proto eq "imap") {
  2651. # IMAP is different with its identifier first on the command line
  2652. if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
  2653. ($full =~ /^([^ ]+) ([^ ]+)/)) {
  2654. $cmdid=$1; # set the global variable
  2655. $FTPCMD=$2;
  2656. $FTPARG=$3;
  2657. }
  2658. # IMAP authentication cancellation
  2659. elsif($full =~ /^\*$/) {
  2660. # Command id has already been set
  2661. $FTPCMD="*";
  2662. $FTPARG="";
  2663. }
  2664. # IMAP long "commands" are base64 authentication data
  2665. elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
  2666. # Command id has already been set
  2667. $FTPCMD=$full;
  2668. $FTPARG="";
  2669. }
  2670. else {
  2671. sendcontrol "$full BAD Command\r\n";
  2672. last;
  2673. }
  2674. }
  2675. elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
  2676. $FTPCMD=$1;
  2677. $FTPARG=$3;
  2678. }
  2679. elsif($proto eq "pop3") {
  2680. # POP3 authentication cancellation
  2681. if($full =~ /^\*$/) {
  2682. $FTPCMD="*";
  2683. $FTPARG="";
  2684. }
  2685. # POP3 long "commands" are base64 authentication data
  2686. elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
  2687. $FTPCMD=$full;
  2688. $FTPARG="";
  2689. }
  2690. else {
  2691. sendcontrol "-ERR Unrecognized command\r\n";
  2692. last;
  2693. }
  2694. }
  2695. elsif($proto eq "smtp") {
  2696. # SMTP authentication cancellation
  2697. if($full =~ /^\*$/) {
  2698. $FTPCMD="*";
  2699. $FTPARG="";
  2700. }
  2701. # SMTP long "commands" are base64 authentication data
  2702. elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) {
  2703. $FTPCMD=$full;
  2704. $FTPARG="";
  2705. }
  2706. else {
  2707. sendcontrol "500 Unrecognized command\r\n";
  2708. last;
  2709. }
  2710. }
  2711. else {
  2712. sendcontrol "500 Unrecognized command\r\n";
  2713. last;
  2714. }
  2715. logmsg "< \"$full\"\n";
  2716. if($verbose) {
  2717. print STDERR "IN: $full\n";
  2718. }
  2719. $full = "";
  2720. my $delay = $delayreply{$FTPCMD};
  2721. if($delay) {
  2722. # just go sleep this many seconds!
  2723. logmsg("Sleep for $delay seconds\n");
  2724. my $twentieths = $delay * 20;
  2725. while($twentieths--) {
  2726. portable_sleep(0.05) unless($got_exit_signal);
  2727. }
  2728. }
  2729. my $check = 1; # no response yet
  2730. # See if there is a custom reply for the full text
  2731. my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD;
  2732. my $text = $fulltextreply{$fulltext};
  2733. if($text && ($text ne "")) {
  2734. sendcontrol "$text\r\n";
  2735. $check = 0;
  2736. }
  2737. else {
  2738. # See if there is a custom reply for the command
  2739. $text = $commandreply{$FTPCMD};
  2740. if($text && ($text ne "")) {
  2741. if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
  2742. # used enough times so blank the custom command reply
  2743. $commandreply{$FTPCMD}="";
  2744. }
  2745. sendcontrol $text;
  2746. $check = 0;
  2747. }
  2748. else {
  2749. # See if there is any display text for the command
  2750. $text = $displaytext{$FTPCMD};
  2751. if($text && ($text ne "")) {
  2752. if($proto eq 'imap') {
  2753. sendcontrol "$cmdid $text\r\n";
  2754. }
  2755. else {
  2756. sendcontrol "$text\r\n";
  2757. }
  2758. $check = 0;
  2759. }
  2760. # only perform this if we're not faking a reply
  2761. my $func = $commandfunc{uc($FTPCMD)};
  2762. if($func) {
  2763. &$func($FTPARG, $FTPCMD);
  2764. $check = 0;
  2765. }
  2766. }
  2767. }
  2768. if($check) {
  2769. logmsg "$FTPCMD wasn't handled!\n";
  2770. if($proto eq 'pop3') {
  2771. sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
  2772. }
  2773. elsif($proto eq 'imap') {
  2774. sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
  2775. }
  2776. else {
  2777. sendcontrol "500 $FTPCMD is not dealt with!\r\n";
  2778. }
  2779. }
  2780. } # while(1)
  2781. logmsg "====> Client disconnected\n";
  2782. if($serverlogslocked) {
  2783. $serverlogslocked = 0;
  2784. clear_advisor_read_lock($SERVERLOGS_LOCK);
  2785. }
  2786. }
  2787. killsockfilters($proto, $ipvnum, $idnum, $verbose);
  2788. unlink($pidfile);
  2789. if($serverlogslocked) {
  2790. $serverlogslocked = 0;
  2791. clear_advisor_read_lock($SERVERLOGS_LOCK);
  2792. }
  2793. exit;