ftpserver.pl 89 KB

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