ftpserver.pl 86 KB

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