script/latexmlc

filter: Statementstmt 93.3% 28 / 30 Branchbran 50.0% 2 / 4 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 83.6% 41 / 49 CC 4 SCAR 8.2
CC
4
Cov
84%
BEGIN
5.0
BEGIN
1.3
BEGIN
1.0
CRAP 2.3
« lib/LaTeXML/Core/Definition/CharDef.pm ↑ Summary lib/LaTeXML/Common/Color/cmy.pm »
1 #!/usr/bin/env perl
2 # /=====================================================================\ #
3 # | latexmlc | #
4 # | client/server conversion program | #
5 # |=====================================================================| #
6 # | Part of LaTeXML: | #
7 # | Public domain software, produced as part of work done by the | #
8 # | United States Government & not subject to copyright in the US. | #
9 # |---------------------------------------------------------------------| #
10 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
11 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
12 # \=========================================================ooo==U==ooo=/ #
13 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 2 ▶use Cwd qw(cwd abs_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 my $RealBin_safe;
20 2 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use File::Spec::Functions;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 2 ▶use File::Which;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 BEGIN {
25 2 ▶ if ($FindBin::RealBin =~ /^([^\0]+)\z/) { # Valid Unix path TODO: Windows, revisit regexp
Subroutine BEGIN: called CC=4 SCAR=16.1
Branch: 1 branch
BranchTrueFalseTotal
if ($FindBin::RealBin =~ /^([^\0]+)\z/) 2 0 2
26 2 $RealBin_safe = $1; }
27 2 ▶ die 'Fatal:I/O:tainted RealBin was tainted! Failing...'
Branch: 1 branch
BranchTrueFalseTotal
unless $RealBin_safe and -e catfile($RealBin_safe, "latexmlc") 0 2 2
Condition33%1/3
$RealBin_safe and -e catfile($RealBin_safe, "latexmlc")
!ll&&!rl&&r
002
MC/DC0%0/2
$RealBin_safe and -e catfile($RealBin_safe, "latexmlc")
$RealBin_safe -e catfile($RealBin_safe, "latexmlc")
Truth table33%1/3
A and B
A= $RealBin_safeB= -e catfile($RealBin_safe, "latexmlc")
ABresult
0X0
100
111
28 unless ($RealBin_safe && (-e catfile($RealBin_safe, 'latexmlc')));
29 }
30 # TODO: We probably want file cat for things like /../lib instead of spelling out a Unix path
31 2 ▶use lib catdir($RealBin_safe, "..", "lib");
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 #TODO: Do we ever care about ENV PATH that much? Do we miss on some feature like that?
34 #$ENV{PATH} = "$RealBin_safe:/usr/bin:/usr/local/bin:";
35 2 ▶use LaTeXML;
Subroutine BEGIN: called CC=1 SCAR=2.6
36 use LaTeXML::Common::Config;
37 use URI::Escape;
38 use HTTP::Response;
39 use HTTP::Request;
40 use JSON::XS qw(decode_json);
41  
42 binmode(STDERR, ":encoding(UTF-8)");
43  
44 # Determine if a socket server is installed locally and obtain its pathname:
45 my $latexmls;
46 $latexmls = catfile($RealBin_safe, 'latexmls') if (-e catfile($RealBin_safe, 'latexmls'));
47 $latexmls = which('latexmls') unless defined $latexmls;
48  
49 # Some defaults:
50 my $opts = LaTeXML::Common::Config->new(input_limit => 100);
51  
52 # Parse and load command-line options
53 $opts->read(\@ARGV);
54 my $keyvals = $opts->scan_to_keyvals(\@ARGV);
55  
56 # Client-side options:
57 my ($port, $address, $expire, $local) = map { $opts->get($_) } qw(port address expire);
58 $address = '127.0.0.1' if !$address || ($address eq 'localhost');
59 $address =~ s/^(\w+)\:\/\///; # strip away any protocol
60 my $route = '/';
61 if ($address =~ s/\/(.+)$//) { # strip away route
62 $route = '/' . $1;
63 }
64 # Local if peerhost is localhost:
65 $local = ($expire && ($expire == -1)) || ($address eq '127.0.0.1');
66 $expire = -1 unless ((defined $expire) && $latexmls);
67 $port = ($local ? 3334 : 80) unless $port; #Fall back if all fails...
68 #***************************************************************************
69 #Add some base, so that relative paths work
70 my $cdir = abs_path(cwd());
71 $cdir =~ s/ /\\ /g;
72 if (!$opts->get('base')) {
73 $opts->set('base', $cdir);
74 push @$keyvals, ['base', $cdir];
75 }
76 # Record if destination exists, for summary
77 my $deststat;
78 $deststat = (stat($opts->get('destination')))[9] if $opts->get('destination');
79 $deststat = 0 unless defined $deststat;
80  
81 push @$keyvals, ['path', $cdir]; #add current path, to ensure never empty
82 push @{ $opts->get('paths') }, $cdir;
83  
84 # Get the full source of interest
85 my $source = $opts->get('source');
86 $opts->delete('source');
87 if (!$source) { print STDERR "Input was empty.\n"; exit 1; }
88 if ($source eq '-') {
89 { local $/ = undef;
90 $source = "literal:" . <STDIN>;
91 # Set the source in the keyvals to be sent over the wire:
92 @$keyvals = grep { $_->[0] !~ /source|tex/ } @$keyvals;
93 push @$keyvals, $source;
94 } }
95 #***************************************************************************
96 # Prepare output variables:
97 my ($result, $status, $log);
98  
99 # TODO: Talk to the web service via HTTP
100 #Setup client and communicate
101 my $sock = $latexmls && IO::Socket::INET->new(
102 PeerAddr => $address,
103 PeerPort => $port,
104 Proto => 'tcp',
105 ); #Attempt connecting to a service
106 if ((!$sock) && $local && ($expire == -1)) {
107 # Don't boot a server, single job requested:
108 require LaTeXML;
109 $opts->set('local', 1);
110 $opts->push('debug', 'LaTeXML') unless $opts->get('log'); # If we don't request log, print to STDERR
111 my $converter = LaTeXML->get_converter($opts);
112 $converter->prepare_session($opts);
113 my $response = $converter->convert($source);
114 ($result, $status, $log) = map { $$response{$_} } qw(result status log) if defined $response;
115 } else {
116 my $message = q{};
117 foreach my $entry (@$keyvals) {
118 my ($key, $value) = ($$entry[0], $$entry[1]);
119 $message .= uri_escape($key) . ($value ? '=' . uri_escape($value) : '') . '&';
120 }
121 chop $message;
122 #Startup daemon and feed in args, if needed
123 system($latexmls, "--port=$port",
124 "--expire=$expire", "--autoflush=" . $opts->get('input_limit')) if !$sock && $local;
125 my $http_response = ($local
126 ? process_local($address, $port, $route, $message, $sock)
127 : process_remote($address, $port, $route, $message, $sock));
128 if ($http_response->is_success) {
129 my $response = decode_json($http_response->content);
130 ($result, $status, $log) = map { $$response{$_} } qw(result status log) if defined $response;
131 } else {
132 print STDERR "Fatal:HTTP:" . $http_response->code() . " " . $http_response->message() . "\n"; exit 1;
133 }
134 }
135  
136 #***************************************************************************
137 ### Common treatment of output:
138  
139 # Special features for latexmls:
140 my $whatsout = $opts->get('whatsout');
141 my $is_archive = $whatsout && ($whatsout =~ /^archive/);
142 if ($log) {
143 if ($opts->get('log')) {
144 if (!$is_archive) { # archives only have the archive file
145 my $clog = $opts->get('log');
146 my $log_handle;
147 if (!open($log_handle, ">", $clog)) {
148 print STDERR "Fatal:I/O:forbidden Couldn't open log file $clog : $!\n";
149 exit 1;
150 }
151 print $log_handle $log;
152 close $log_handle;
153 }
154 } else { print STDERR $log, "\n"; } #STDERR log otherwise
155 }
156  
157 if ($result) {
158 # NOTE that we are serializing the XML::LibXML::Document whose toString
159 # has ALREADY encoded (in this case to utf8), so NO encode is needed!
160 if ($opts->get('destination')) {
161 my $output_handle;
162 if (!open($output_handle, ">", $opts->get('destination'))) {
163 print STDERR "Fatal:I/O:forbidden Couldn't open output file " . $opts->get('destination') . ": $!";
164 exit 1; }
165 if ($whatsout eq 'archive') {
166 binmode($output_handle, ':raw');
167 }
168 print $output_handle $result;
169 close $output_handle;
170 } else {
171 print STDOUT $result, "\n"; } #Output to STDOUT
172 }
173  
174 # Print summary, if requested, to STDERR
175 if ($opts->get('destination')) {
176 print STDERR $status;
177 print STDERR summary($opts->get('destination'), $deststat);
178 }
179  
180 if ($status =~ /fatal error/) { # non-zero exit code for fatal conversions
181 exit 1;
182 }
183  
184 # == Helpers ==
185 sub summary {
186 my ($destination, $prior_stat) = @_;
187 my $new_stat = (stat($destination))[9] || 0;
188 return ($new_stat && ($prior_stat != $new_stat)) ? "\nWrote $destination\n" :
189 "\nError! Did not write file $destination\n";
190 }
191  
192 sub process_local {
193 my ($req_address, $req_port, $req_route, $req_message, $req_sock) = @_;
194 #daemon is running, reconnect and feed in request
195 $req_sock = IO::Socket::INET->new(
196 PeerAddr => $req_address,
197 PeerPort => $req_port,
198 Proto => 'tcp',
199 ) unless $req_sock;
200 if (!$req_sock) {
201 print STDERR "Fatal:perl:socket-create Could not create socket: $!\n";
202 exit 1; }
203 my $req_message_length = length($req_message);
204 $req_route = "$req_address:$req_port" unless $req_route;
205 my $payload = <<"PAYLOADEND";
206 POST $req_route HTTP/1.0
207 Host: $req_address:$req_port
208 User-Agent: latexmlc
209 Content-Type: application/x-www-form-urlencoded
210 Content-Length: $req_message_length
211  
212 $req_message
213 PAYLOADEND
214 $req_sock->send($payload);
215 my $response_string = q{};
216 { local $/ = undef;
217 $response_string = <$req_sock>; }
218 close($req_sock);
219 return ($response_string
220 ? HTTP::Response->parse($response_string)
221 : HTTP::Response->new(500, 'Internal Server Error')); }
222  
223 sub process_remote {
224 my ($req_address, $req_port, $req_route, $req_message, $req_sock) = @_;
225 $req_sock->close if $req_sock; # No need of the socket here, using LWP instead
226 my $payload = HTTP::Request->new(POST => "http://$req_address:$req_port$req_route");
227 $payload->header('User-Agent', 'latexmlc');
228 $payload->header('Content-Type', 'application/x-www-form-urlencoded');
229 $payload->content($req_message);
230 require LWP::UserAgent;
231 my $ua = LWP::UserAgent->new;
232 $ua->timeout(10);
233 return $ua->request($payload); }
234  
235 #**********************************************************************
236 __END__
« lib/LaTeXML/Core/Definition/CharDef.pm ↑ Summary lib/LaTeXML/Common/Color/cmy.pm »