ftpserver.pl 89 KB

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