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/Pair.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 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 ▶use Cwd qw(cwd abs_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 my $RealBin_safe;
20 1 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use File::Spec::Functions;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use File::Which;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 1 ▶BEGIN {
Subroutine BEGIN: called CC=4 SCAR=16.1
25 1 ▶ if ($FindBin::RealBin =~ /^([^\0]+)\z/) { # Valid Unix path TODO: Windows, revisit regexp
Branch: 1 branch
BranchTrueFalseTotal
if ($FindBin::RealBin =~ /^([^\0]+)\z/) 1 0 1
26 1 $RealBin_safe = $1; }
27 1 ▶ die 'Fatal:I/O:tainted RealBin was tainted! Failing...'
Branch: 1 branch
BranchTrueFalseTotal
unless $RealBin_safe and -e catfile($RealBin_safe, "latexmlc") 0 1 1
Condition33%1/3
$RealBin_safe and -e catfile($RealBin_safe, "latexmlc")
!ll&&!rl&&r
001
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 1 ▶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 0 ▶use LaTeXML;
Subroutine BEGIN: called CC=1 SCAR=2.6
36 use LaTeXML::Common::Config;
37 use LaTeXML::Common::Error;
38 use LaTeXML::Util::Pathname;
39 use URI::Escape;
40 use HTTP::Response;
41 use HTTP::Request;
42 use JSON::XS qw(decode_json);
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 # Get the full source of interest
56 my $source = $opts->get('source');
57 $opts->delete('source');
58  
59 # Setup logging messages
60 SetVerbosity($opts->get('verbosity'));
61 UseSTDERR(); # setup for LaTeXML.pm to also use STDERR spinner messages.
62 my $starttime = StartTime();
63  
64 # Client-side options:
65 my ($port, $address, $expire, $local) = map { $opts->get($_) } qw(port address expire);
66 $address = '127.0.0.1' if !$address || ($address eq 'localhost');
67 $address =~ s/^(\w+)\:\/\///; # strip away any protocol
68 my $route = '/';
69 if ($address =~ s/\/(.+)$//) { # strip away route
70 $route = '/' . $1;
71 }
72 # Local if peerhost is localhost:
73 $local = ($expire && ($expire == -1)) || ($address eq '127.0.0.1');
74 $expire = -1 unless ((defined $expire) && $latexmls);
75 $port = ($local ? 3334 : 80) unless $port; #Fall back if all fails...
76 #***************************************************************************
77 #Add some base, so that relative paths work
78 my $cdir = abs_path(cwd());
79 $cdir =~ s/ /\\ /g;
80 if (!$opts->get('base')) {
81 $opts->set('base', $cdir);
82 push @$keyvals, ['base', $cdir];
83 }
84  
85 # Record if destination exists, for summary
86 my $deststat;
87 $deststat = (stat($opts->get('destination')))[9] if $opts->get('destination');
88 $deststat = 0 unless defined $deststat;
89  
90 push @$keyvals, ['path', $cdir]; #add current path, to ensure never empty
91 push @{ $opts->get('paths') }, $cdir;
92  
93 if (!$source) { die "Input was empty.\n"; }
94 if ($source eq '-') {
95 { local $/ = undef;
96 $source = "literal:" . <STDIN>;
97 # Set the source in the keyvals to be sent over the wire:
98 @$keyvals = grep { $_->[0] !~ /source|tex/ } @$keyvals;
99 push @$keyvals, $source;
100 } }
101  
102 # Always create a .log file for tracking the conversion messages
103 # Use $jobname.latexml.log or just latexml.log for logging by default
104 #
105 # In the local conversion case, this can be delegated to LaTeXML.pm
106 my $logfile = $opts->get('log');
107 if (!$logfile) {
108 if (!pathname_is_literaldata($source)) {
109 my ($dir, $name, $ext) = pathname_split($source);
110 if ($name) {
111 $logfile = pathname_make(dir => pathname_cwd(), name => $name, type => 'latexml.log'); }
112 else {
113 $logfile = 'latexml.log';
114 } }
115 else {
116 $logfile = 'latexml.log'; }
117 $opts->set('log', $logfile); }
118 # A bit special: Since LaTeXML.pm will always try to append to the log file
119 # make sure the file is new before we start.
120 unlink($logfile) if (-f $logfile);
121  
122 #***************************************************************************
123 # Prepare output variables:
124 my ($result, $status, $status_code, $log);
125  
126 # TODO: Talk to the web service via HTTP
127 #Setup client and communicate
128 my $sock = $latexmls && IO::Socket::INET->new(
129 PeerAddr => $address,
130 PeerPort => $port,
131 Proto => 'tcp',
132 ); #Attempt connecting to a service
133 if ((!$sock) && $local && ($expire == -1)) {
134 # Don't boot a server, single job requested:
135 require LaTeXML;
136 $opts->set('local', 1);
137 my $converter = LaTeXML->get_converter($opts);
138 $converter->prepare_session($opts);
139 my $response = $converter->convert($source);
140 ($result, $status, $status_code, $log) = map { $$response{$_} } qw(result status status_code log) if defined $response;
141 } else {
142 my $message = q{};
143 foreach my $entry (@$keyvals) {
144 my ($key, $value) = ($$entry[0], $$entry[1]);
145 $message .= uri_escape($key) . ($value ? '=' . uri_escape($value) : '') . '&';
146 }
147 chop $message;
148 ProgressSpinup("Calling out to latexmls");
149 #Startup daemon and feed in args, if needed
150 system($latexmls, "--port=$port",
151 "--expire=$expire", "--autoflush=" . $opts->get('input_limit')) if !$sock && $local;
152 my $http_response = ($local
153 ? process_local($address, $port, $route, $message, $sock)
154 : process_remote($address, $port, $route, $message, $sock));
155 if ($http_response->is_success) {
156 my $response = decode_json($http_response->content);
157 ($result, $status, $log) = map { $$response{$_} } qw(result status log) if defined $response;
158 NoteSTDERR("Conversion complete: " . $$response{status});
159 } else {
160 die("Fatal:HTTP:" . $http_response->code() . " " . $http_response->message() . "\n");
161 }
162 ProgressSpindown("Calling out to latexmls"); }
163  
164 #***************************************************************************
165 ### Common treatment of output:
166 my $destination = $opts->get('destination');
167  
168 # Always write log to a file, either specified via --log or 'latexml.log'
169 # with the exception of *archive* outputs, where the log is in the ZIP
170 my $whatsout = $opts->get('whatsout');
171 my $is_archive = $whatsout && ($whatsout =~ /^archive/);
172  
173 if ($log) {
174 chomp($log);
175 # If we get a log payload in the response, likely from a latexmls call
176 # we need to write it to file from within latexmlc itself:
177 my $logfile = $opts->get('log');
178 UseLog($logfile);
179 NoteLog($log);
180 UseLog(undef);
181 NoteSTDERR("full log written to $logfile."); }
182  
183 if ($result) {
184 # NOTE that we are serializing the XML::LibXML::Document whose toString
185 # has ALREADY encoded (in this case to utf8), so NO encode is needed!
186 if ($destination) {
187 my $output_handle;
188 open($output_handle, ">", $destination) or die("Fatal:I/O:forbidden Couldn't open output file " . $destination . ": $!");
189 if ($whatsout eq 'archive') {
190 binmode($output_handle, ':raw');
191 }
192 print $output_handle $result;
193 close $output_handle;
194 } else {
195 print "\n", $result, "\n"; } }
196  
197 # == End of Program ==
198 # cleanup STDERR e.g. in case of fatals
199 UseSTDERR(undef);
200 if ($status_code == 3 || ($status =~ /fatal error/)) { # non-zero exit code for fatal conversions
201 exit 1;
202 } else {
203 exit 0;
204 }
205  
206 # == Helpers ==
207 sub summary {
208 my ($destination, $prior_stat) = @_;
209 my $new_stat = (stat($destination))[9] || 0;
210 return ($new_stat && ($prior_stat != $new_stat)) ? "\nWrote $destination\n" :
211 "\nError! Did not write file $destination\n"; }
212  
213 sub process_local {
214 my ($req_address, $req_port, $req_route, $req_message, $req_sock) = @_;
215 #daemon is running, reconnect and feed in request
216 $req_sock = $req_sock || IO::Socket::INET->new(
217 PeerAddr => $req_address,
218 PeerPort => $req_port,
219 Proto => 'tcp',
220 ) || die "Fatal:perl:socket-create Could not create socket: $!\n";
221 my $req_message_length = length($req_message);
222 $req_route = "$req_address:$req_port" unless $req_route;
223 my $payload = <<"PAYLOADEND";
224 POST $req_route HTTP/1.0
225 Host: $req_address:$req_port
226 User-Agent: latexmlc
227 Content-Type: application/x-www-form-urlencoded
228 Content-Length: $req_message_length
229  
230 $req_message
231 PAYLOADEND
232 $req_sock->send($payload);
233 my $response_string = q{};
234 { local $/ = undef;
235 $response_string = <$req_sock>; }
236 close($req_sock);
237 return ($response_string
238 ? HTTP::Response->parse($response_string)
239 : HTTP::Response->new(500, 'Internal Server Error')); }
240  
241 sub process_remote {
242 my ($req_address, $req_port, $req_route, $req_message, $req_sock) = @_;
243 $req_sock->close if $req_sock; # No need of the socket here, using LWP instead
244 my $payload = HTTP::Request->new(POST => "http://$req_address:$req_port$req_route");
245 $payload->header('User-Agent', 'latexmlc');
246 $payload->header('Content-Type', 'application/x-www-form-urlencoded');
247 $payload->content($req_message);
248 require LWP::UserAgent;
249 my $ua = LWP::UserAgent->new;
250 $ua->timeout(10);
251 return $ua->request($payload); }
252  
253 #**********************************************************************
254 __END__
« lib/LaTeXML/Core/Pair.pm ↑ Summary lib/LaTeXML/Common/Color/cmy.pm »