You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redirector.pl.in 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. #!/usr/bin/env perl
  2. use warnings;
  3. use strict;
  4. # Required ports:
  5. # www/p5-POE-Component-Client-HTTP
  6. # www/p5-POE-Component-Server-HTTP
  7. # dns/p5-POE-Component-Client-DNS
  8. # databases/p5-Cache-Memcached-Fast
  9. # devel/p5-Proc-Daemon
  10. # sysutils/p5-Proc-PidUtil
  11. # POE::Component::Client::HTTP uses HTTP::Request and response
  12. # objects.
  13. use POSIX qw(strftime);
  14. use HTTP::Request::Common qw(GET POST);
  15. use HTTP::Response;
  16. use URI::Escape qw(uri_unescape);
  17. use Sys::Syslog qw/:standard :macros setlogsock/;
  18. use HTML::HeadParser;
  19. use Digest;
  20. use Proc::Daemon;
  21. use Proc::PidUtil;
  22. use POE qw(@POE_LOOP@ Component::Server::TCP Filter::HTTPD Component::Client::HTTP);
  23. use Redis::Fast;
  24. my $with_swf = 1;
  25. my $swf_parser;
  26. my $saved_swf_url = "";
  27. eval "require SWF::Element" or $with_swf = 0; # p5-SWF-File
  28. my $DEBUG = grep { $_ eq '-debug' } @ARGV;
  29. our %cfg = (
  30. port => 8080,
  31. max_size => 102400,
  32. http_timeout => 5,
  33. max_rec => 5,
  34. pidfile => '/tmp/redirector.pid',
  35. do_log => 0,
  36. debug => 0,
  37. redis_server => 'localhost:6379',
  38. facility => LOG_LOCAL3, # syslog facility
  39. log_level => LOG_INFO,
  40. digest_bits => 256,
  41. cache_expire => 3600,
  42. user => '@RSPAMD_USER@',
  43. group => '@RSPAMD_GROUP@',
  44. cfg_file => '@CMAKE_INSTALL_PREFIX@/etc/rspamd-redirector.conf',
  45. );
  46. our $do_reopen_log = 0;
  47. our $redis_conn;
  48. ############################################ Subs ########################################
  49. # Read file into string
  50. sub read_file {
  51. my ($file) = @_;
  52. open( IN, $file ) or _log( LOG_ALERT, "Can't open $file: $!" );
  53. local $/;
  54. my $content = <IN>;
  55. close IN;
  56. return $content;
  57. }
  58. # Write log line:
  59. sub _log {
  60. my ( $l, $w, @s ) = @_;
  61. if ($DEBUG) {
  62. printf STDERR $w . "\n", @s;
  63. }
  64. else {
  65. syslog( $l, $w . "\n", @s ) if ( $l <= $cfg{'log_level'} );
  66. }
  67. if ( $l == LOG_ALERT ) {
  68. die $w;
  69. }
  70. }
  71. # Init swf parser
  72. sub swf_init_parser {
  73. if ($with_swf) {
  74. $swf_parser = SWF::Parser->new( 'tag-callback' => \&swf_tag_callback );
  75. }
  76. }
  77. # Checking for SWF url
  78. sub swf_search_get_url {
  79. my $actions = shift;
  80. my $saved_pool_str = "";
  81. for my $action (@$actions) {
  82. if ( $action->tag_name eq 'ActionConstantPool' ) {
  83. my $pool = $action->ConstantPool;
  84. for my $string (@$pool) {
  85. if ( $string =~ /^https?:\/\// ) {
  86. $saved_pool_str = $string->value;
  87. }
  88. }
  89. }
  90. elsif ( $action->tag_name eq 'ActionGetURL2' ) {
  91. if ( $saved_pool_str ne "" ) {
  92. $saved_swf_url = $saved_pool_str;
  93. }
  94. }
  95. elsif ( $action->tag_name =~ 'ActionGetURL' ) {
  96. $saved_swf_url = $action->UrlString->value;
  97. }
  98. }
  99. }
  100. # SWF check tag utility
  101. sub swf_check_tag {
  102. my ( $t, $stream ) = @_;
  103. my ($tagname) = $t->tag_name;
  104. for ($tagname) {
  105. ( /^Do(Init)?Action$/ or /^DefineButton$/ ) and do {
  106. swf_search_get_url( $t->Actions );
  107. last;
  108. };
  109. /^PlaceObject2$/ and do {
  110. for my $ca ( @{ $t->ClipActions } ) {
  111. swf_search_get_url( $ca->Actions );
  112. }
  113. last;
  114. };
  115. /^DefineButton2$/ and do {
  116. for my $ba ( @{ $t->Actions } ) {
  117. swf_search_get_url( $ba->Actions );
  118. }
  119. last;
  120. };
  121. /^DefineSprite$/ and do {
  122. for my $tag ( @{ $t->ControlTags } ) {
  123. swf_search_get_url( $tag, $stream );
  124. }
  125. last;
  126. };
  127. }
  128. }
  129. # Callback for swf parser
  130. sub swf_tag_callback {
  131. my ( $self, $tag, $length, $stream ) = @_;
  132. my $t = SWF::Element::Tag->new( Tag => $tag, Length => $length );
  133. my ($tagname) = $t->tag_name;
  134. return
  135. unless $tagname eq 'DoAction'
  136. or $tagname eq 'DoInitAction'
  137. or $tagname eq 'PlaceObject2'
  138. or $tagname eq 'DefineButton'
  139. or $tagname eq 'DefineButton2'
  140. or $tagname eq 'DefineSprite';
  141. if ( $tagname eq 'DefineSprite' ) {
  142. # Tags in the sprite are not unpacked here.
  143. $t->shallow_unpack($stream);
  144. $t->TagStream->parse( callback => \&swf_tag_callback );
  145. return;
  146. }
  147. elsif ( $tagname eq 'PlaceObject2' ) {
  148. # Most of PlaceObject2 tags don't have ClipActions.
  149. $t->lookahead_Flags($stream);
  150. return unless $t->PlaceFlagHasClipActions;
  151. }
  152. # unpack the tag and search actions.
  153. $t->unpack($stream);
  154. swf_check_tag($t);
  155. }
  156. # Check url from redis cache first
  157. sub redis_check_url {
  158. my ($url) = @_;
  159. my $context = Digest->new("SHA-512");
  160. $context->add($url);
  161. return $redis_conn->get( $context->digest() );
  162. }
  163. # Write url to redis key
  164. sub redis_cache_url {
  165. my ( $url, $url_real ) = @_;
  166. if ( $url ne $url_real ) {
  167. my $context = Digest->new("SHA-512");
  168. $context->add($url);
  169. if ( !$redis_conn->setex( $context->digest(), $cfg{cache_expire}, $url_real ) ) {
  170. _log( LOG_INFO, "cannot save redirect from $url to $url_real in redis" );
  171. }
  172. }
  173. }
  174. sub create_response {
  175. my ( $code, $uri ) = @_;
  176. my $new_response;
  177. if ($uri) {
  178. $new_response = HTTP::Response->new( $code, 'OK' );
  179. $new_response->header( "Uri", $uri );
  180. $new_response->content($uri);
  181. $new_response->content_length( length($uri) );
  182. }
  183. else {
  184. $new_response = HTTP::Response->new($code);
  185. $new_response->content_length(0);
  186. }
  187. $new_response->header( "Connection", "Close" );
  188. $new_response->header( "Proxy-Connection", "Close" );
  189. return $new_response;
  190. }
  191. # POE http client callback
  192. sub process_client {
  193. my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
  194. my $http_request = $_[ARG0]->[0];
  195. my $rec = $_[ARG0]->[1][0];
  196. my $http_response = $_[ARG1]->[0];
  197. my $base_url = $_[ARG0]->[1][1];
  198. $saved_swf_url = "";
  199. if ( $rec == 0 ) {
  200. $base_url = $http_request->uri;
  201. }
  202. else {
  203. # Check cache for each url
  204. my $redirect = redis_check_url( $http_request->uri );
  205. if ($redirect) {
  206. _log( LOG_INFO, "Memcached redirect from %s to %s for request from: %s",
  207. $http_response->base, $redirect, $heap->{remote_ip} );
  208. my $new_response = create_response( 200, $redirect );
  209. # Avoid sending the response if the client has gone away.
  210. $heap->{client}->put($new_response) if defined $heap->{client};
  211. # Shut down the client's connection when the response is sent.
  212. return;
  213. }
  214. }
  215. if ($do_reopen_log) {
  216. $do_reopen_log = 0;
  217. reopen_log();
  218. }
  219. if ( $rec > $cfg{max_rec} ) {
  220. _log( LOG_INFO, "Max recursion exceeded: %d from %s to %s for request from: %s",
  221. $rec, $base_url, $http_request->uri, $heap->{remote_ip} );
  222. # Write to cache
  223. redis_cache_url( $base_url, $http_request->uri );
  224. my $new_response = create_response( 200, $http_request->uri );
  225. # Avoid sending the response if the client has gone away.
  226. $heap->{client}->put($new_response) if defined $heap->{client};
  227. # Shut down the client's connection when the response is sent.
  228. $kernel->yield("shutdown");
  229. return;
  230. }
  231. # Detect HTTP redirects
  232. if ( $http_response->is_redirect ) {
  233. my $redirect = $http_response->header('Location');
  234. if ($redirect) {
  235. if ( $redirect =~ /^https?:\/\// ) {
  236. _log( LOG_INFO, "HTML redirect from %s to %s for request from: %s",
  237. $http_response->base, $redirect, $heap->{remote_ip} );
  238. my $request = HTTP::Request->new( 'GET', $redirect );
  239. $request->header( "Connection", "close" );
  240. $request->header( "Proxy-Connection", "close" );
  241. $kernel->post( "cl", "request", "got_response", $request, [ $rec + 1, $base_url ] );
  242. return;
  243. }
  244. else {
  245. _log( LOG_INFO, "ignoring internal redirect from %s to %s for request from: %s",
  246. $http_request->uri, $redirect, $heap->{remote_ip} );
  247. my $new_response = create_response( 200, $http_request->uri );
  248. # Avoid sending the response if the client has gone away.
  249. $heap->{client}->put($new_response) if defined $heap->{client};
  250. # Shut down the client's connection when the response is sent.
  251. $kernel->yield("shutdown");
  252. return;
  253. }
  254. }
  255. }
  256. elsif ( $http_response->code != 200 ) {
  257. _log( LOG_INFO, "HTTP response was %d, for request to %s", $http_response->code, $http_request->uri );
  258. my $new_response;
  259. if ( $rec == 0 ) {
  260. $new_response = create_response( $http_response->code );
  261. }
  262. else {
  263. redis_cache_url( $base_url, $http_request->uri );
  264. $new_response = create_response( 200, $http_request->uri );
  265. }
  266. # Avoid sending the response if the client has gone away.
  267. $heap->{client}->put($new_response) if defined $heap->{client};
  268. # Shut down the client's connection when the response is sent.
  269. $kernel->yield("shutdown");
  270. return;
  271. }
  272. my $response_type = $http_response->content_type();
  273. if ( $response_type =~ /^text/i ) {
  274. my $content = $http_response->decoded_content();
  275. my $p = HTML::HeadParser->new($http_response);
  276. $p->parse($content);
  277. my $expire = $http_response->header('Refresh');
  278. if ( $http_response->is_redirect || $expire ) {
  279. my $redirect;
  280. if ($expire) {
  281. $expire =~ /URL=(\S+)/;
  282. $redirect = $1;
  283. }
  284. else {
  285. $redirect = $http_response->header('Location');
  286. }
  287. if ($redirect) {
  288. if ( $redirect =~ /^https?:\/\// ) {
  289. _log( LOG_INFO, "HTML redirect from %s to %s for request from: %s",
  290. $http_response->base, $redirect, $heap->{remote_ip} );
  291. my $request = HTTP::Request->new( 'GET', $redirect );
  292. $request->header( "Connection", "close" );
  293. $request->header( "Proxy-Connection", "close" );
  294. $kernel->post( "cl", "request", "got_response", $request, [ $rec + 1, $base_url ] );
  295. return;
  296. }
  297. else {
  298. _log( LOG_INFO, "ignoring internal redirect from %s to %s for request from: %s",
  299. $http_response->base, $redirect, $heap->{remote_ip} );
  300. }
  301. }
  302. }
  303. if ( $content =~ /location\s*=\s*["']*(https?:\/\/[^"'\s]+)["']*/im ) {
  304. my $redir = uri_unescape($1);
  305. _log( LOG_INFO, "js redirect from %s to %s for request from: %s",
  306. $http_response->base, $1, $heap->{remote_ip} );
  307. my $request = HTTP::Request->new( 'GET', $redir );
  308. $request->header( "Connection", "close" );
  309. $request->header( "Proxy-Connection", "close" );
  310. $kernel->post( "cl", "request", "got_response", $request, [ $rec + 1, $base_url ] );
  311. return;
  312. }
  313. }
  314. elsif (
  315. $with_swf
  316. && (
  317. $response_type eq 'application/x-shockwave-flash'
  318. || ( $http_request->uri =~ /\.swf(\?.*)?$/i
  319. && $http_response->code == 200 )
  320. )
  321. )
  322. {
  323. my $content = $http_response->decoded_content();
  324. $swf_parser->parse($content);
  325. if ( $saved_swf_url ne "" ) {
  326. _log( LOG_INFO, "flash redirect from %s to %s for request from: %s",
  327. $http_response->base, $saved_swf_url, $heap->{remote_ip} );
  328. my $request = HTTP::Request->new( 'GET', $saved_swf_url );
  329. # Reset swf redirect global variable
  330. $saved_swf_url = "";
  331. $request->header( "Connection", "close" );
  332. $request->header( "Proxy-Connection", "close" );
  333. $kernel->post( "cl", "request", "got_response", $request, [ $rec + 1, $base_url ] );
  334. return;
  335. }
  336. }
  337. else {
  338. _log( LOG_INFO, "response wasn't text request from: %s, response is: %s", $heap->{remote_ip}, $response_type );
  339. }
  340. _log( LOG_INFO, "redirect from %s to %s for request from: %s", $base_url, $http_request->uri, $heap->{remote_ip} );
  341. # Write to cache
  342. redis_cache_url( $base_url, $http_request->uri );
  343. my $new_response = create_response( $http_response->code, $http_request->uri );
  344. # Avoid sending the response if the client has gone away.
  345. $heap->{client}->put($new_response) if defined $heap->{client};
  346. # Shut down the client's connection when the response is sent.
  347. $kernel->yield("shutdown");
  348. }
  349. sub process_input {
  350. my ( $kernel, $heap, $request ) = @_[ KERNEL, HEAP, ARG0 ];
  351. if ( $request->isa("HTTP::Response") ) {
  352. $heap->{client}->put($request);
  353. $kernel->yield("shutdown");
  354. return;
  355. }
  356. my $domain;
  357. if ( $request->uri =~ /^http:\/\/([^\/]+)\// ) {
  358. my @parts = split( /\./, $1 );
  359. my $c1 = pop @parts;
  360. my $c2 = pop @parts;
  361. $domain = "$c2.$c1";
  362. }
  363. if (
  364. ( defined( $cfg{check_regexp} ) && $request->uri !~ $cfg{check_regexp} )
  365. || ( defined( $cfg{check_domains} )
  366. && scalar( grep { $_ eq $domain } @{ $cfg{check_domains} } ) == 0 )
  367. )
  368. {
  369. my $new_response = create_response( 200, $request->uri );
  370. # Avoid sending the response if the client has gone away.
  371. $heap->{client}->put($new_response) if defined $heap->{client};
  372. $kernel->yield("shutdown");
  373. # Shut down the client's connection when the response is sent.
  374. return;
  375. }
  376. # Check cache first
  377. my $redirect = redis_check_url( $request->uri );
  378. if ($redirect) {
  379. _log( LOG_INFO, "Memcached redirect from %s to %s for request from: %s",
  380. $request->uri, $redirect, $heap->{remote_ip} );
  381. my $new_response = create_response( 200, $redirect );
  382. # Avoid sending the response if the client has gone away.
  383. $heap->{client}->put($new_response) if defined $heap->{client};
  384. $kernel->yield("shutdown");
  385. # Shut down the client's connection when the response is sent.
  386. return;
  387. }
  388. # Start http request
  389. my $new_request = HTTP::Request->new( 'GET', $request->uri );
  390. $new_request->header( "Connection", "close" );
  391. $new_request->header( "Proxy-Connection", "close" );
  392. $kernel->post( "cl", "request", "got_response", $new_request, [ 0, "" ] );
  393. }
  394. sub sig_DIE {
  395. my ( $sig, $ex ) = @_[ ARG0, ARG1 ];
  396. _log( LOG_ERR, "$$: error in $ex->{event}: $ex->{error_str}" );
  397. $poe_kernel->sig_handled();
  398. # Send the signal to session that sent the original event.
  399. if ( $ex->{source_session} ne $_[SESSION] ) {
  400. $poe_kernel->signal( $ex->{source_session}, 'DIE', $sig, $ex );
  401. }
  402. }
  403. sub sig_CLD {
  404. my ( $heap, $child_pid ) = @_[ HEAP, ARG1 ];
  405. return 0;
  406. }
  407. ############################### Main code fragment ##################################
  408. # Do daemonization
  409. if ( !$DEBUG ) {
  410. Proc::Daemon::Init;
  411. POE::Kernel->has_forked;
  412. setlogsock('unix');
  413. openlog( 'redirector', 'ndelay,pid', $cfg{'facility'} );
  414. }
  415. # Try to eval config file
  416. if ( -f $cfg{cfg_file} ) {
  417. my $config = read_file( $cfg{cfg_file} );
  418. eval $config;
  419. }
  420. _log( LOG_ALERT, "Process is already started, check $cfg{pidfile}" )
  421. if Proc::PidUtil::is_running( $cfg{pidfile} );
  422. # Drop privileges
  423. if ( $> == 0 ) {
  424. my $uid = getpwnam( $cfg{user} )
  425. or _log( LOG_ALERT, "user $cfg{user} unknown" );
  426. my $gid = getgrnam( $cfg{group} )
  427. or _log( LOG_ALERT, "group $cfg{group} unknown" );
  428. $< = $> = $uid;
  429. $) = $( = $gid;
  430. }
  431. if ( !$DEBUG ) {
  432. _log( LOG_ALERT, "Cannot write to pidfile $cfg{pidfile}" )
  433. if !open( PID, "> $cfg{pidfile}" );
  434. close(PID);
  435. }
  436. # Reopen log on SIGUSR1
  437. $poe_kernel->sig( DIE => \&sig_DIE );
  438. $poe_kernel->sig( CLD => \&sig_CLD );
  439. $SIG{USR1} = sub { $do_reopen_log = 1; $poe_kernel->sig_handled(); };
  440. $SIG{INT} = sub { $poe_kernel->stop(); };
  441. $SIG{QUIT} = sub { $poe_kernel->stop(); };
  442. $SIG{PIPE} = 'IGNORE';
  443. if ( !$DEBUG ) {
  444. Proc::PidUtil::make_pidfile( $cfg{pidfile}, $$ )
  445. or _log( LOG_ALERT, "Cannot write pidfile $cfg{pidfile}" );
  446. }
  447. # Init redis connection
  448. _log( LOG_INFO, "Starting redis connection" );
  449. $redis_conn = Redis::Fast->new(
  450. server => $cfg{redis_server},
  451. reconnect => 60,
  452. every => 500_000,
  453. encoding => undef,
  454. );
  455. # POE part
  456. POE::Component::Client::HTTP->spawn(
  457. Alias => 'cl',
  458. MaxSize => $cfg{max_size}, # Remove for unlimited page sizes
  459. Timeout => $cfg{http_timeout},
  460. ConnectionManager => POE::Component::Client::Keepalive->new(
  461. max_per_host => 256,
  462. max_open => 1024,
  463. keep_alive => 1,
  464. timeout => $cfg{http_timeout},
  465. ),
  466. );
  467. _log( LOG_INFO, "Starting HTTP server" );
  468. POE::Component::Server::TCP->new(
  469. Alias => "",
  470. Port => $cfg{port},
  471. ClientFilter => 'POE::Filter::HTTPD',
  472. ClientInput => \&process_input,
  473. InlineStates => { got_response => \&process_client, },
  474. );
  475. swf_init_parser();
  476. _log( LOG_NOTICE, "Starting URL resolver" );
  477. # Start POE. This will run the server until it exits.
  478. POE::Kernel->run();
  479. exit 0;
  480. ############################## Final block ####################################
  481. END {
  482. _log( LOG_NOTICE, 'redirector stopped' );
  483. closelog();
  484. }