2
0

ftpserver.pl 90 KB

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