Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

snf4sa.pm 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. #
  2. # SpamAssassin SNF4SA Plugin for SNFServer.
  3. #
  4. # This plugin implements a SpamAssassin rule to use SNFServer to test
  5. # whether an email is spam.
  6. #
  7. # Copyright (C) 2009 ARM Research Labs, LLC.
  8. #
  9. # snf4sa.pm
  10. #
  11. # The plugin implements a single evaluation rule, which passes the
  12. # email message through SNFServer. The communication with SNFServer
  13. # is through XCI and a temporary file on disk which contains the email
  14. # message truncated to the frist 64K bytes.
  15. #
  16. package Snf4sa;
  17. use strict;
  18. use Mail::SpamAssassin;
  19. use Mail::SpamAssassin::Plugin;
  20. use Mail::SpamAssassin::PerMsgStatus;
  21. use Mail::SpamAssassin::Logger;
  22. use IO::Socket;
  23. use IO::File;
  24. use File::Temp qw/ tempfile tempdir /;
  25. our @ISA = qw(Mail::SpamAssassin::Plugin);
  26. # Convenience variables and pseudo-constants
  27. my $CRLF = "\x0d\x0a";
  28. # translation table for SNF rule codes
  29. my $rule_code_xlat = {
  30. 0 => 'Standard White Rules',
  31. 20 => 'GBUdb Truncate (superblack)',
  32. 40 => 'GBUdb Caution (suspicious)',
  33. 47 => 'Travel',
  34. 48 => 'Insurance',
  35. 49 => 'Antivirus Push',
  36. 50 => 'Media Theft',
  37. 51 => 'Spamware',
  38. 52 => 'Snake Oil',
  39. 53 => 'Scam Patterns',
  40. 54 => 'Porn/Adult',
  41. 55 => 'Malware & Scumware Greetings',
  42. 56 => 'Ink & Toner',
  43. 57 => 'Get Rich',
  44. 58 => 'Debt & Credit',
  45. 59 => 'Casinos & Gambling',
  46. 60 => 'Ungrouped Black Rules',
  47. 61 => 'Experimental Abstract',
  48. 62 => 'Obfuscation Techniques',
  49. 63 => 'Experimental Received [ip]',
  50. };
  51. sub new {
  52. my ($class, $mailsa) = @_;
  53. $class = ref($class) || $class;
  54. my $self = $class->SUPER::new($mailsa);
  55. bless ($self, $class);
  56. # Name of evaluation rule.
  57. $self->register_eval_rule ("snf4sa_sacheck");
  58. # Use localhost.
  59. $self->{SNF_Host} = "localhost";
  60. # Use default port.
  61. $self->{SNF_Port} = 9001;
  62. # Timeout.
  63. $self->{SNF_Timeout} = 1;
  64. # Directory for files containing emails read by SNFServer.
  65. $self->{Temp_Dir} = '/tmp/snf4sa';
  66. # Maximum email message size (including headers).
  67. $self->{SNF_MaxTempFileSize} = 64 * 1024;
  68. # Key for confidence in mail header inserted by SNFServer.
  69. $self->{GBUdb_ConfidenceKey} = "c=";
  70. # Key for probability in mail header inserted by SNFServer.
  71. $self->{GBUdb_ProbabilityKey} = "p=";
  72. # Key for GBUdb maximum weight in the configuration file.
  73. $self->{GBUdb_MaxWeightKey} = "gbudb_max_weight";
  74. # Key for SNFServer code in configuration file.
  75. $self->{SNF_CodeKey} = "snf_result";
  76. # Key for SA score increment in configuration file.
  77. $self->{SA_DeltaScoreKey} = "sa_score";
  78. # Key for short circuit in configuration file.
  79. $self->{SA_ShortCircuitYesKey} = "short_circuit_yes";
  80. # Key for no short circuit in configuration file.
  81. $self->{SA_ShortCircuitNoKey} = "short_circuit_no";
  82. return $self;
  83. }
  84. # DEBUG/TEST.
  85. #sub extract_metadata {
  86. #
  87. # my ($self, $opts) = @_;
  88. #
  89. # print "***********************\n";
  90. # print "extract_metadata called\n";
  91. # print "***********************\n";
  92. #
  93. # $opts->{msg}->put_metadata("X-Extract-Metadata:", "Test header");
  94. #
  95. #}
  96. # END OF DEBUG/TEST.
  97. sub have_shortcircuited {
  98. my ($self, $options) = @_;
  99. if (defined($options->{permsgstatus}->{shortCircuit})) {
  100. return $options->{permsgstatus}->{shortCircuit};
  101. }
  102. return 0;
  103. }
  104. sub parse_config {
  105. my ($self, $options) = @_;
  106. # DEBUG.
  107. #print "parse_confg. key: $options->{key}\n";
  108. #print "parse_config. line: $options->{line}\n";
  109. #print "parse_config. value: $options->{value}\n";
  110. #END OF DEBUG.
  111. # Process GBUdb_max_weight.
  112. if (lc($options->{key}) eq $self->{GBUdb_MaxWeightKey}) {
  113. # GBUdb maximum weight.
  114. my $tempValue = $options->{value};
  115. # Test that the value was a number.
  116. #$self->log_debug("Found $self->{GBUdb_MaxWeightKey} . " value: $options->{value}, tempValue: $tempValue\n"; # DEBUG.
  117. if ($tempValue =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) {
  118. # Value was a number. Load and return success.
  119. $options->{conf}->{gbuDbMaxWeight} = $tempValue;
  120. $self->inhibit_further_callbacks();
  121. return 1;
  122. } else {
  123. $self->log_debug("Invalid value for $self->{GBUdb_MaxWeightKey} " .
  124. $tempValue);
  125. }
  126. } elsif (lc($options->{key}) eq $self->{SNF_CodeKey}) {
  127. # Relationship between SNFServer code and SA score delta.
  128. my $snf = $self->parse_snf_sa_mapping($options);
  129. if (defined($snf)) {
  130. my @snfCode = @{$snf->{snfCode}};
  131. #print "snf->{snfCode}: @snfCode\n"; # DEBUG.
  132. #print "snf->{deltaScore}: $snf->{deltaScore}\n"; # DEBUG.
  133. #print "snf->{shortCircuit}: $snf->{shortCircuit}\n"; # DEBUG.
  134. # Save configuration.
  135. foreach my $i (@{$snf->{snfCode}}) {
  136. # Create (or update) an element in the mapping array
  137. # that snfSaMapping is a reference to.
  138. $options->{conf}->{snfSaMapping}->[$i] = {
  139. deltaScore => $snf->{deltaScore},
  140. shortCircuit => $snf->{shortCircuit}
  141. };
  142. }
  143. # DEBUG.
  144. #for (my $i = 0; $i < @{$options->{conf}->{snfSaMapping}}; $i++) {
  145. # if (! defined($options->{conf}->{snfSaMapping}->[$i])) {
  146. # print "No configuration for SNFServer code $i\n";
  147. # next;
  148. # }
  149. # print "SNFServer code: $i, " .
  150. # "deltaScore: " .
  151. # "$options->{conf}->{snfSaMapping}->[$i]->{deltaScore}, " .
  152. # "shortCircuit: " .
  153. # "$options->{conf}->{snfSaMapping}->[$i]->{shortCircuit}\n";
  154. #}
  155. # END OF DEBUG.
  156. # Successfully parsed.
  157. $self->inhibit_further_callbacks();
  158. return 1;
  159. }
  160. }
  161. # Wasn't handled.
  162. return 0;
  163. }
  164. # Parse a snf_result configuration line.
  165. #
  166. # Input--
  167. #
  168. # $line--String containing the snf_result line without the first word.
  169. #
  170. # Returns a reference with the following fields (if no error)--
  171. #
  172. # snfCode--Array of SNFServer result codes that this configuration
  173. # line specifies.
  174. #
  175. # deltaScore--SA score increment for the codes in @snfCode.
  176. #
  177. # shortCircuit--True if a SNFServer code in @snfCode is to
  178. # short-circuit the message scan, false otherwise.
  179. #
  180. # If the line cannot be parsed, the return value is undef.
  181. #
  182. sub parse_snf_sa_mapping
  183. {
  184. my ($self, $options) = @_;
  185. my $value = $options->{value};
  186. my $ret_hash = {
  187. snfCode => undef,
  188. deltaScore => undef,
  189. shortCircuit => undef
  190. };
  191. # SNFServer codes found.
  192. my @snfCode = ();
  193. # Remove leading and trailing whitespace.
  194. $value =~ s/^\s+//;
  195. $value =~ s/\s+$//;
  196. # Convert to lower case.
  197. $value = lc($value);
  198. # Split up by white space.
  199. my @specVal = split(/\s+/, $value);
  200. if (0 == @specVal) {
  201. # No separate words.
  202. $self->log_debug("No separate words found in configuration line '" .
  203. $options->{line} . "'");
  204. return undef;
  205. }
  206. # Convert each SNFServer result specification into an integer.
  207. my $lastSpec;
  208. for ($lastSpec = 0; $lastSpec < @specVal; $lastSpec++) {
  209. # Check for next keyword.
  210. if ($specVal[$lastSpec] eq $self->{SA_DeltaScoreKey}) {
  211. # We've completed the processing of the SNFServer result
  212. # codes.
  213. last;
  214. }
  215. # Get the code values.
  216. my @codeVal = $self->get_code_values($specVal[$lastSpec]);
  217. if (0 == @codeVal) {
  218. # No code values were obtained.
  219. $self->log_debug("Couldn't parse all the SNFServer code values " .
  220. "in configuration line '" .
  221. $options->{line} . "'");
  222. return undef;
  223. }
  224. # Add to the list of codes.
  225. @snfCode = (@snfCode, @codeVal);
  226. }
  227. # Sort the SNFServer result codes and remove duplicates.
  228. @snfCode = sort { $a <=> $b } @snfCode;
  229. my $prev = -1;
  230. my @temp = grep($_ != $prev && ($prev = $_), @snfCode);
  231. $ret_hash->{snfCode} = \@temp;
  232. # The $specVal[$lastSpec] is $self->{SA_DeltaScoreKey}. Return if
  233. # there aren't enough parameters.
  234. $lastSpec++;
  235. if ($lastSpec >= @specVal) {
  236. # Not enough parameters.
  237. $self->log_debug("Not enough parameters in configuration line '" .
  238. $options->{line} . "'");
  239. return undef;
  240. }
  241. # Extract the SA delta score.
  242. $ret_hash->{deltaScore} = $specVal[$lastSpec];
  243. if (!($ret_hash->{deltaScore} =~
  244. /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)) {
  245. # SA delta score isn't a number.
  246. $self->log_debug("Value after '" . $self->{SA_DeltaScoreKey} .
  247. "' ($specVal[$lastSpec]) must be a number " .
  248. "in configuration line '" .
  249. $options->{line} . "'");
  250. return undef;
  251. }
  252. # Get short circuit spec.
  253. $lastSpec++;
  254. $ret_hash->{shortCircuit} = 0;
  255. if ( ($lastSpec + 1) == @specVal) {
  256. # A parameter was specified.
  257. my $shortCircuitSpec = $specVal[$lastSpec];
  258. if ($self->{SA_ShortCircuitYesKey} eq $shortCircuitSpec) {
  259. # Specified short-circuit evaluation.
  260. $ret_hash->{shortCircuit} = 1;
  261. } elsif ($self->{SA_ShortCircuitNoKey} ne $shortCircuitSpec) {
  262. # Invalid short-circuit specification.
  263. $self->log_debug("Invalid short-circuit specification: '" .
  264. $specVal[$lastSpec] .
  265. "' in configuration line '" . $options->{line} .
  266. "'. Must be '$self->{SA_ShortCircuitYesKey}' " .
  267. " or '$self->{SA_ShortCircuitNoKey}'.");
  268. return undef;
  269. }
  270. } elsif ($lastSpec != @specVal) {
  271. # Too many parameters were specified.
  272. $self->log_debug("Too many parameters were specified in " .
  273. "configuration line '" . $options->{line} . "'");
  274. return undef;
  275. }
  276. return $ret_hash;
  277. }
  278. sub get_code_values
  279. {
  280. my ($self, $specElement) = @_;
  281. my @snfCode = ();
  282. # Split the specification.
  283. my @codeVal = split(/-/, $specElement);
  284. #$self->log_debug("snf4sa: get_code_values. specElement: $specElement. codeVal: @codeVal"); # DEBUG
  285. if (1 == @codeVal) {
  286. if ($specElement =~ /^\d+$/) {
  287. # Found a single code.
  288. $snfCode[0] = 1 * $specElement;
  289. }
  290. } elsif (2 == @codeVal) {
  291. # Check range.
  292. if ( ($codeVal[0] =~ /^\d+$/) && ($codeVal[1] =~ /^\d+$/) ) {
  293. # Found a range of codes.
  294. $codeVal[0] = 1 * $codeVal[0];
  295. $codeVal[1] = 1 * $codeVal[1];
  296. if ($codeVal[0] <= $codeVal[1]) {
  297. # Add these SNF codes.
  298. for (my $i = $codeVal[0]; $i <= $codeVal[1]; $i++) {
  299. push(@snfCode, $i);
  300. }
  301. }
  302. }
  303. }
  304. return @snfCode;
  305. }
  306. # Output a debug message.
  307. #
  308. # Input--
  309. #
  310. # $message--String containing the message to output.
  311. #
  312. sub log_debug
  313. {
  314. my ($self, $message) = @_;
  315. dbg("snf4sa: $message");
  316. }
  317. # Check the message with SNFServer.
  318. sub snf4sa_sacheck {
  319. my ($self, $permsgstatus, $fulltext) = @_;
  320. my $response ='';
  321. my $exitvalue;
  322. # Make sure we have a temp dir
  323. unless(-d $self->{Temp_Dir}) {
  324. mkdir($self->{Temp_Dir});
  325. chmod(0777, $self->{Temp_Dir});
  326. };
  327. # Truncate the message.
  328. my $mailtext = substr( ${$fulltext}, 0, $self->{SNF_MaxTempFileSize});
  329. # create our temp file, $filename will contain the full path
  330. my ($fh, $filename) = tempfile( DIR => $self->{Temp_Dir} );
  331. # spew our mail into the temp file
  332. my $SNF_fh = IO::File->new( $filename, "w" ) ||
  333. die(__PACKAGE__ . ": Unable to create temporary file '" . $filename . "'");
  334. $SNF_fh->print($mailtext) ||
  335. $self->cleanup_die($filename,
  336. __PACKAGE__ . ": Unable to write to temporary file '" .
  337. $filename . "'");
  338. $SNF_fh->close ||
  339. $self->cleanup_die($filename,
  340. __PACKAGE__ . ": Unable to close temporary file '" .
  341. $filename . "'");
  342. # Change permissions.
  343. my $cnt = chmod(0666, $filename) ||
  344. $self->cleanup_die($filename, __PACKAGE__ .
  345. ": Unable to change permissions of temporary file '" .
  346. $filename . "'");
  347. # xci_scan connects to SNFServer with XCI to scan the message
  348. my $SNF_XCI_Return = $self->xci_scan( $filename );
  349. #print "header:\n\n$SNF_XCI_Return->{header}\n\n"; # DEBUG
  350. # Remove the temp file, we are done with it.
  351. unlink($filename);
  352. # Check response from SNFServer.
  353. if (! $SNF_XCI_Return ) {
  354. die(__PACKAGE__ . ": Internal error");
  355. }
  356. # Check for success.
  357. if (! $SNF_XCI_Return->{"success"}) {
  358. die(__PACKAGE__ . ": Error from SNFServer: " .
  359. $SNF_XCI_Return->{"message"});
  360. }
  361. # get the return code and translation
  362. my ( $rc, $rcx ) = ( $SNF_XCI_Return->{"code"},
  363. $rule_code_xlat->{ $SNF_XCI_Return->{"code"} } );
  364. $rc = -1 unless defined $rc; # default values
  365. $rcx = 'Unknown' unless $rcx;
  366. my $rch = $SNF_XCI_Return->{"header"}; # the SNF header(s)
  367. # Initialize the change in the SA score.
  368. my $deltaScore = 0.0;
  369. # Add the score from the SNFServer return.
  370. if (defined($permsgstatus->{main}->{conf}->{snfSaMapping}->[$rc])) {
  371. $deltaScore +=
  372. $permsgstatus->{main}->{conf}->{snfSaMapping}->[$rc]->{deltaScore};
  373. $permsgstatus->{shortCircuit} =
  374. $permsgstatus->{main}->{conf}->{snfSaMapping}->[$rc]->{shortCircuit};
  375. }
  376. # Perform GBUdb processing.
  377. if (defined($permsgstatus->{main}->{conf}->{gbuDbMaxWeight})) {
  378. #print "gbudbMaxWeight: $permsgstatus->{main}->{conf}->{gbuDbMaxWeight}\n\n"; # DEBUG.
  379. # Calculate the contribution to the scrore from the GBUdb results.
  380. $deltaScore +=
  381. $self->calc_GBUdb($SNF_XCI_Return->{header},
  382. $permsgstatus->{main}->{conf}->{gbuDbMaxWeight});
  383. }
  384. # Add the headers.
  385. $permsgstatus->set_tag("SNFRESULTTAG", "$rc ($rcx)");
  386. $permsgstatus->set_tag("SNFMESSAGESNIFFERSCANRESULT",
  387. $self->extract_header_body($SNF_XCI_Return->{header},
  388. "X-MessageSniffer-Scan-Result"));
  389. $permsgstatus->set_tag("SNFMESSAGESNIFFERRULES",
  390. $self->extract_header_body($SNF_XCI_Return->{header},
  391. "X-MessageSniffer-Rules"));
  392. $permsgstatus->set_tag("SNFGBUDBANALYSIS",
  393. $self->extract_header_body($SNF_XCI_Return->{header},
  394. "X-GBUdb-Analysis"));
  395. # Submit the score.
  396. if ($deltaScore) {
  397. $permsgstatus->got_hit("SNF4SA", "", score => $deltaScore);
  398. for my $set (0..3) {
  399. $permsgstatus->{conf}->{scoreset}->[$set]->{"SNF4SA"} =
  400. sprintf("%0.3f", $deltaScore);
  401. }
  402. }
  403. # Always return zero, since the score was submitted via got_hit()
  404. # above.
  405. return 0;
  406. }
  407. # Calculate the contribution of the GBUdb scan to the SA score.
  408. #
  409. # Input--
  410. #
  411. # $headers--String containing the headers.
  412. #
  413. # $weight--Weight used to calculate the contribution.
  414. #
  415. # Returns the contribution to the SA score (float).
  416. #
  417. sub calc_GBUdb
  418. {
  419. my ( $self, $headers, $weight ) = @_;
  420. # Split the header into lines.
  421. my @headerLine = split(/\n/, $headers);
  422. # Find the line containing the GBUdb results.
  423. my $line;
  424. foreach $line (@headerLine) {
  425. # Search for the tag.
  426. if ($line =~ /^X-GBUdb-Analysis:/) {
  427. # GBUdb analysis was done. Extract the values.
  428. my $ind0 = index($line, $self->{GBUdb_ConfidenceKey});
  429. my $ind1 = index($line, " ", $ind0 + 2);
  430. if (-1 == $ind0) {
  431. return 0.0;
  432. }
  433. my $c = 1.0 * substr($line, $ind0 + 2, $ind1 - $ind0 - 2);
  434. #print "calc_GBUdb. line: $line\n"; # DEBUG
  435. #print "calc_GBUdb. c: $c, ind0: $ind0, ind1: $ind1\n"; # DEBUG
  436. $ind0 = index($line, $self->{GBUdb_ProbabilityKey});
  437. $ind1 = index($line, " ", $ind0 + 2);
  438. if (-1 == $ind0) {
  439. return 0.0;
  440. }
  441. my $p = 1.0 * substr($line, $ind0 + 2, $ind1 - $ind0 - 2);
  442. #print "calc_GBUdb. p: $p, ind0: $ind0, ind1: $ind1\n"; # DEBUG
  443. # Calculate and return the score.
  444. my $score = abs($p * $c) ** 0.5;
  445. $score *= $weight;
  446. if ($p < 0.0) {
  447. $score *= -1.0;
  448. }
  449. # DEBUG.
  450. #print "calc_GBUdb. p: $p, c: $c, weight: $weight\n";
  451. #print "calc_GBUdb. score: $score\n";
  452. # END OF DEBUG.
  453. return $score;
  454. }
  455. }
  456. }
  457. # Extract the specified header body from a string containing all the
  458. # headers.
  459. #
  460. # Input--
  461. #
  462. # $headers--String containing the headers.
  463. #
  464. # $head--String containing the head of the header to extract.
  465. #
  466. # Returns the body of the header.
  467. #
  468. sub extract_header_body
  469. {
  470. my ( $self, $headers, $head ) = @_;
  471. my $body = "";
  472. if ($headers =~ /$head:(.*)/s) {
  473. my $temp = $1;
  474. $temp =~ /(.*)\nX-(.*)/s;
  475. $body = $1;
  476. }
  477. return $body;
  478. }
  479. # xci_scan( $file )
  480. # returns hashref:
  481. # success : true/false
  482. # code : response code from SNF
  483. # message : scalar message (if any)
  484. sub xci_scan
  485. {
  486. my ( $self, $file ) = @_;
  487. return undef unless $self and $file;
  488. my $ret_hash = {
  489. success => undef,
  490. code => undef,
  491. message => undef,
  492. header => undef,
  493. xml => undef
  494. };
  495. my $xci = $self->connect_socket( $self->{SNF_Host}, $self->{SNF_Port} )
  496. or return $self->err_hash("cannot connect to socket ($!)");
  497. $xci->print("<snf><xci><scanner><scan file='$file' xhdr='yes' /></scanner></xci></snf>\n");
  498. my $rc = $ret_hash->{xml} = $self->socket_response($xci, $file);
  499. $xci->close;
  500. if ( $rc =~ /^<snf><xci><scanner><result code='(\d*)'>/ ) {
  501. $ret_hash->{success} = 1;
  502. $ret_hash->{code} = $1;
  503. $rc =~ /<xhdr>(.*)<\/xhdr>/s and $ret_hash->{header} = $1;
  504. } elsif ( $rc =~ /^<snf><xci><error message='(.*)'/ ) {
  505. $ret_hash->{message} = $1;
  506. } else {
  507. $ret_hash->{message} = "unknown XCI response: $rc";
  508. }
  509. return $ret_hash;
  510. }
  511. # connect_socket( $host, $port )
  512. # returns IO::Socket handle
  513. sub connect_socket
  514. {
  515. my ( $self, $host, $port ) = @_;
  516. return undef unless $self and $host and $port;
  517. my $protoname = 'tcp'; # Proto should default to tcp but it's not expensive to specify
  518. $self->{XCI_Socket} = IO::Socket::INET->new(
  519. PeerAddr => $host,
  520. PeerPort => $port,
  521. Proto => $protoname,
  522. Timeout => $self->{SNF_Timeout} ) or return undef;
  523. $self->{XCI_Socket}->autoflush(1); # make sure autoflush is on -- legacy
  524. return $self->{XCI_Socket}; # return the socket handle
  525. }
  526. # socket_response( $socket_handle )
  527. # returns scalar string
  528. sub socket_response
  529. {
  530. my ( $self, $rs, $file ) = @_;
  531. my $buf = ''; # buffer for response
  532. # blocking timeout for servers who accept but don't answer
  533. eval {
  534. local $SIG{ALRM} = sub { die "timeout\n" }; # set up the interrupt
  535. alarm $self->{SNF_Timeout}; # set up the alarm
  536. while (<$rs>) { # read the socket
  537. $buf .= $_;
  538. }
  539. alarm 0; # reset the alarm
  540. };
  541. # report a blocking timeout
  542. if ( $@ eq "timeout\n" ) {
  543. $self->cleanup_die($file,
  544. __PACKAGE__ . ": Timeout waiting for response from SNFServer");
  545. } elsif ( $@ =~ /alarm.*unimplemented/ ) { # no signals on Win32
  546. while (<$rs>) { # get whatever's left
  547. # in the socket.
  548. $buf .= $_;
  549. }
  550. }
  551. return $buf;
  552. }
  553. # return an error message for xci_scan
  554. sub err_hash
  555. {
  556. my ( $self, $message ) = @_;
  557. return {
  558. success => undef,
  559. code => undef,
  560. message => $message
  561. };
  562. }
  563. sub cleanup_die
  564. {
  565. my ( $self, $file, $message ) = @_;
  566. unlink($file);
  567. die($message);
  568. }
  569. 1;