-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
CGIServlet.java
1946 lines (1707 loc) · 71.4 KB
/
CGIServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.servlets;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.util.IOTools;
/**
* CGI-invoking servlet for web applications, used to execute scripts which
* comply to the Common Gateway Interface (CGI) specification and are named
* in the path-info used to invoke this servlet.
*
* <p>
* <i>Note: This code compiles and even works for simple CGI cases.
* Exhaustive testing has not been done. Please consider it beta
* quality. Feedback is appreciated to the author (see below).</i>
* </p>
* <p>
*
* <b>Example</b>:<br>
* If an instance of this servlet was mapped (using
* <code><web-app>/WEB-INF/web.xml</code>) to:
* </p>
* <p>
* <code>
* <web-app>/cgi-bin/*
* </code>
* </p>
* <p>
* then the following request:
* </p>
* <p>
* <code>
* http://localhost:8080/<web-app>/cgi-bin/dir1/script/pathinfo1
* </code>
* </p>
* <p>
* would result in the execution of the script
* </p>
* <p>
* <code>
* <web-app-root>/WEB-INF/cgi/dir1/script
* </code>
* </p>
* <p>
* with the script's <code>PATH_INFO</code> set to <code>/pathinfo1</code>.
* </p>
* <p>
* Recommendation: House all your CGI scripts under
* <code><webapp>/WEB-INF/cgi</code>. This will ensure that you do not
* accidentally expose your cgi scripts' code to the outside world and that
* your cgis will be cleanly ensconced underneath the WEB-INF (i.e.,
* non-content) area.
* </p>
* <p>
* The default CGI location is mentioned above. You have the flexibility to
* put CGIs wherever you want, however:
* </p>
* <p>
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix
* (or webAppRootDir alone if cgiPathPrefix is
* null).
* </p>
* <p>
* cgiPathPrefix is defined by setting
* this servlet's cgiPathPrefix init parameter
* </p>
*
* <p>
*
* <B>CGI Specification</B>:<br> derived from
* <a href="http://cgi-spec.golux.com">http://cgi-spec.golux.com</a>.
* A work-in-progress & expired Internet Draft. Note no actual RFC describing
* the CGI specification exists. Where the behavior of this servlet differs
* from the specification cited above, it is either documented here, a bug,
* or an instance where the specification cited differs from Best
* Community Practice (BCP).
* Such instances should be well-documented here. Please email the
* <a href="http://tomcat.apache.org/lists.html">Tomcat group</a>
* with amendments.
*
* </p>
* <p>
*
* <b>Canonical metavariables</b>:<br>
* The CGI specification defines the following canonical metavariables:
* <br>
* [excerpt from CGI specification]
* <PRE>
* AUTH_TYPE
* CONTENT_LENGTH
* CONTENT_TYPE
* GATEWAY_INTERFACE
* PATH_INFO
* PATH_TRANSLATED
* QUERY_STRING
* REMOTE_ADDR
* REMOTE_HOST
* REMOTE_IDENT
* REMOTE_USER
* REQUEST_METHOD
* SCRIPT_NAME
* SERVER_NAME
* SERVER_PORT
* SERVER_PROTOCOL
* SERVER_SOFTWARE
* </PRE>
* <p>
* Metavariables with names beginning with the protocol name (<EM>e.g.</EM>,
* "HTTP_ACCEPT") are also canonical in their description of request header
* fields. The number and meaning of these fields may change independently
* of this specification. (See also section 6.1.5 [of the CGI specification].)
* </p>
* [end excerpt]
*
* <h2> Implementation notes</h2>
* <p>
*
* <b>standard input handling</b>: If your script accepts standard input,
* then the client must start sending input within a certain timeout period,
* otherwise the servlet will assume no input is coming and carry on running
* the script. The script's the standard input will be closed and handling of
* any further input from the client is undefined. Most likely it will be
* ignored. If this behavior becomes undesirable, then this servlet needs
* to be enhanced to handle threading of the spawned process' stdin, stdout,
* and stderr (which should not be too hard).
* <br>
* If you find your cgi scripts are timing out receiving input, you can set
* the init parameter <code></code> of your webapps' cgi-handling servlet
* to be
* </p>
* <p>
*
* <b>Metavariable Values</b>: According to the CGI specification,
* implementations may choose to represent both null or missing values in an
* implementation-specific manner, but must define that manner. This
* implementation chooses to always define all required metavariables, but
* set the value to "" for all metavariables whose value is either null or
* undefined. PATH_TRANSLATED is the sole exception to this rule, as per the
* CGI Specification.
*
* </p>
* <p>
*
* <b>NPH -- Non-parsed-header implementation</b>: This implementation does
* not support the CGI NPH concept, whereby server ensures that the data
* supplied to the script are precisely as supplied by the client and
* unaltered by the server.
* </p>
* <p>
* The function of a servlet container (including Tomcat) is specifically
* designed to parse and possible alter CGI-specific variables, and as
* such makes NPH functionality difficult to support.
* </p>
* <p>
* The CGI specification states that compliant servers MAY support NPH output.
* It does not state servers MUST support NPH output to be unconditionally
* compliant. Thus, this implementation maintains unconditional compliance
* with the specification though NPH support is not present.
* </p>
* <p>
*
* The CGI specification is located at
* <a href="http://cgi-spec.golux.com">http://cgi-spec.golux.com</a>.
*
* </p>
* <p>
* <h3>TODO:</h3>
* <ul>
* <li> Support for setting headers (for example, Location headers don't work)
* <li> Support for collapsing multiple header lines (per RFC 2616)
* <li> Ensure handling of POST method does not interfere with 2.3 Filters
* <li> Refactor some debug code out of core
* <li> Ensure header handling preserves encoding
* <li> Possibly rewrite CGIRunner.run()?
* <li> Possibly refactor CGIRunner and CGIEnvironment as non-inner classes?
* <li> Document handling of cgi stdin when there is no stdin
* <li> Revisit IOException handling in CGIRunner.run()
* <li> Better documentation
* <li> Confirm use of ServletInputStream.available() in CGIRunner.run() is
* not needed
* <li> [add more to this TODO list]
* </ul>
*
* @author Martin T Dengler [root@martindengler.com]
* @author Amy Roh
* @since Tomcat 4.0
*/
public final class CGIServlet extends HttpServlet {
/* some vars below copied from Craig R. McClanahan's InvokerServlet */
private static final long serialVersionUID = 1L;
/**
* The debugging detail level for this servlet. Useful values range from 0
* to 5 where 0 means no logging and 5 means maximum logging. Values of 10
* or more mean maximum logging and debug info added to the HTTP response.
* If an error occurs and debug is 10 or more the standard error page
* mechanism will be disabled and a response body with debug information
* will be produced. Note that any value of 10 or more has the same effect
* as a value of 10.
*/
private int debug = 0;
/**
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix
* (or webAppRootDir alone if cgiPathPrefix is
* null)
*/
private String cgiPathPrefix = null;
/** the executable to use with the script */
private String cgiExecutable = "perl";
/** additional arguments for the executable */
private List<String> cgiExecutableArgs = null;
/** the encoding to use for parameters */
private String parameterEncoding =
System.getProperty("file.encoding", "UTF-8");
/**
* The time (in milliseconds) to wait for the reading of stderr to complete
* before terminating the CGI process.
*/
private long stderrTimeout = 2000;
/** object used to ensure multiple threads don't try to expand same file */
private static final Object expandFileLock = new Object();
/** the shell environment variables to be passed to the CGI script */
private final Hashtable<String,String> shellEnv = new Hashtable<>();
/**
* Sets instance variables.
* <P>
* Modified from Craig R. McClanahan's InvokerServlet
* </P>
*
* @param config a <code>ServletConfig</code> object
* containing the servlet's
* configuration and initialization
* parameters
*
* @exception ServletException if an exception has occurred that
* interferes with the servlet's normal
* operation
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Set our properties from the initialization parameters
if (getServletConfig().getInitParameter("debug") != null)
debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));
cgiPathPrefix = getServletConfig().getInitParameter("cgiPathPrefix");
boolean passShellEnvironment =
Boolean.parseBoolean(getServletConfig().getInitParameter("passShellEnvironment"));
if (passShellEnvironment) {
shellEnv.putAll(System.getenv());
}
if (getServletConfig().getInitParameter("executable") != null) {
cgiExecutable = getServletConfig().getInitParameter("executable");
}
if (getServletConfig().getInitParameter("executable-arg-1") != null) {
List<String> args = new ArrayList<>();
for (int i = 1;; i++) {
String arg = getServletConfig().getInitParameter(
"executable-arg-" + i);
if (arg == null) {
break;
}
args.add(arg);
}
cgiExecutableArgs = args;
}
if (getServletConfig().getInitParameter("parameterEncoding") != null) {
parameterEncoding = getServletConfig().getInitParameter("parameterEncoding");
}
if (getServletConfig().getInitParameter("stderrTimeout") != null) {
stderrTimeout = Long.parseLong(getServletConfig().getInitParameter(
"stderrTimeout"));
}
}
/**
* Prints out important Servlet API and container information
*
* <p>
* Copied from SnoopAllServlet by Craig R. McClanahan
* </p>
*
* @param out ServletOutputStream as target of the information
* @param req HttpServletRequest object used as source of information
* @param res HttpServletResponse object currently not used but could
* provide future information
*
* @exception IOException if a write operation exception occurs
*
*/
protected void printServletEnvironment(ServletOutputStream out,
HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Document the properties from ServletRequest
out.println("<h1>ServletRequest Properties</h1>");
out.println("<ul>");
Enumeration<String> attrs = req.getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
out.println("<li><b>attribute</b> " + attr + " = " +
req.getAttribute(attr));
}
out.println("<li><b>characterEncoding</b> = " +
req.getCharacterEncoding());
out.println("<li><b>contentLength</b> = " +
req.getContentLengthLong());
out.println("<li><b>contentType</b> = " +
req.getContentType());
Enumeration<Locale> locales = req.getLocales();
while (locales.hasMoreElements()) {
Locale locale = locales.nextElement();
out.println("<li><b>locale</b> = " + locale);
}
Enumeration<String> params = req.getParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
for (String value : req.getParameterValues(param)) {
out.println("<li><b>parameter</b> " + param + " = " + value);
}
}
out.println("<li><b>protocol</b> = " + req.getProtocol());
out.println("<li><b>remoteAddr</b> = " + req.getRemoteAddr());
out.println("<li><b>remoteHost</b> = " + req.getRemoteHost());
out.println("<li><b>scheme</b> = " + req.getScheme());
out.println("<li><b>secure</b> = " + req.isSecure());
out.println("<li><b>serverName</b> = " + req.getServerName());
out.println("<li><b>serverPort</b> = " + req.getServerPort());
out.println("</ul>");
out.println("<hr>");
// Document the properties from HttpServletRequest
out.println("<h1>HttpServletRequest Properties</h1>");
out.println("<ul>");
out.println("<li><b>authType</b> = " + req.getAuthType());
out.println("<li><b>contextPath</b> = " +
req.getContextPath());
Cookie cookies[] = req.getCookies();
if (cookies!=null) {
for (int i = 0; i < cookies.length; i++)
out.println("<li><b>cookie</b> " + cookies[i].getName() +" = " +cookies[i].getValue());
}
Enumeration<String> headers = req.getHeaderNames();
while (headers.hasMoreElements()) {
String header = headers.nextElement();
out.println("<li><b>header</b> " + header + " = " +
req.getHeader(header));
}
out.println("<li><b>method</b> = " + req.getMethod());
out.println("<li><a name=\"pathInfo\"><b>pathInfo</b></a> = "
+ req.getPathInfo());
out.println("<li><b>pathTranslated</b> = " +
req.getPathTranslated());
out.println("<li><b>queryString</b> = " +
req.getQueryString());
out.println("<li><b>remoteUser</b> = " +
req.getRemoteUser());
out.println("<li><b>requestedSessionId</b> = " +
req.getRequestedSessionId());
out.println("<li><b>requestedSessionIdFromCookie</b> = " +
req.isRequestedSessionIdFromCookie());
out.println("<li><b>requestedSessionIdFromURL</b> = " +
req.isRequestedSessionIdFromURL());
out.println("<li><b>requestedSessionIdValid</b> = " +
req.isRequestedSessionIdValid());
out.println("<li><b>requestURI</b> = " +
req.getRequestURI());
out.println("<li><b>servletPath</b> = " +
req.getServletPath());
out.println("<li><b>userPrincipal</b> = " +
req.getUserPrincipal());
out.println("</ul>");
out.println("<hr>");
// Document the servlet request attributes
out.println("<h1>ServletRequest Attributes</h1>");
out.println("<ul>");
attrs = req.getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
out.println("<li><b>" + attr + "</b> = " +
req.getAttribute(attr));
}
out.println("</ul>");
out.println("<hr>");
// Process the current session (if there is one)
HttpSession session = req.getSession(false);
if (session != null) {
// Document the session properties
out.println("<h1>HttpSession Properties</h1>");
out.println("<ul>");
out.println("<li><b>id</b> = " +
session.getId());
out.println("<li><b>creationTime</b> = " +
new Date(session.getCreationTime()));
out.println("<li><b>lastAccessedTime</b> = " +
new Date(session.getLastAccessedTime()));
out.println("<li><b>maxInactiveInterval</b> = " +
session.getMaxInactiveInterval());
out.println("</ul>");
out.println("<hr>");
// Document the session attributes
out.println("<h1>HttpSession Attributes</h1>");
out.println("<ul>");
attrs = session.getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
out.println("<li><b>" + attr + "</b> = " +
session.getAttribute(attr));
}
out.println("</ul>");
out.println("<hr>");
}
// Document the servlet configuration properties
out.println("<h1>ServletConfig Properties</h1>");
out.println("<ul>");
out.println("<li><b>servletName</b> = " +
getServletConfig().getServletName());
out.println("</ul>");
out.println("<hr>");
// Document the servlet configuration initialization parameters
out.println("<h1>ServletConfig Initialization Parameters</h1>");
out.println("<ul>");
params = getServletConfig().getInitParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
String value = getServletConfig().getInitParameter(param);
out.println("<li><b>" + param + "</b> = " + value);
}
out.println("</ul>");
out.println("<hr>");
// Document the servlet context properties
out.println("<h1>ServletContext Properties</h1>");
out.println("<ul>");
out.println("<li><b>majorVersion</b> = " +
getServletContext().getMajorVersion());
out.println("<li><b>minorVersion</b> = " +
getServletContext().getMinorVersion());
out.println("<li><b>realPath('/')</b> = " +
getServletContext().getRealPath("/"));
out.println("<li><b>serverInfo</b> = " +
getServletContext().getServerInfo());
out.println("</ul>");
out.println("<hr>");
// Document the servlet context initialization parameters
out.println("<h1>ServletContext Initialization Parameters</h1>");
out.println("<ul>");
params = getServletContext().getInitParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
String value = getServletContext().getInitParameter(param);
out.println("<li><b>" + param + "</b> = " + value);
}
out.println("</ul>");
out.println("<hr>");
// Document the servlet context attributes
out.println("<h1>ServletContext Attributes</h1>");
out.println("<ul>");
attrs = getServletContext().getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
out.println("<li><b>" + attr + "</b> = " +
getServletContext().getAttribute(attr));
}
out.println("</ul>");
out.println("<hr>");
}
/**
* Provides CGI Gateway service -- delegates to
* {@link #doGet(HttpServletRequest, HttpServletResponse)}.
*
* @param req HttpServletRequest passed in by servlet container
* @param res HttpServletResponse passed in by servlet container
*
* @exception ServletException if a servlet-specific exception occurs
* @exception IOException if a read/write exception occurs
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doGet(req, res);
}
/**
* Provides CGI Gateway service.
*
* @param req HttpServletRequest passed in by servlet container
* @param res HttpServletResponse passed in by servlet container
*
* @exception ServletException if a servlet-specific exception occurs
* @exception IOException if a read/write exception occurs
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
CGIEnvironment cgiEnv = new CGIEnvironment(req, getServletContext());
if (cgiEnv.isValid()) {
CGIRunner cgi = new CGIRunner(cgiEnv.getCommand(),
cgiEnv.getEnvironment(),
cgiEnv.getWorkingDirectory(),
cgiEnv.getParameters());
if ("POST".equals(req.getMethod())) {
cgi.setInput(req.getInputStream());
}
cgi.setResponse(res);
cgi.run();
} else {
if (setStatus(res, 404)) {
return;
}
}
if (debug >= 10) {
ServletOutputStream out = res.getOutputStream();
out.println("<HTML><HEAD><TITLE>$Name$</TITLE></HEAD>");
out.println("<BODY>$Header$<p>");
if (cgiEnv.isValid()) {
out.println(cgiEnv.toString());
} else {
out.println("<H3>");
out.println("CGI script not found or not specified.");
out.println("</H3>");
out.println("<H4>");
out.println("Check the <b>HttpServletRequest ");
out.println("<a href=\"#pathInfo\">pathInfo</a></b> ");
out.println("property to see if it is what you meant ");
out.println("it to be. You must specify an existant ");
out.println("and executable file as part of the ");
out.println("path-info.");
out.println("</H4>");
out.println("<H4>");
out.println("For a good discussion of how CGI scripts ");
out.println("work and what their environment variables ");
out.println("mean, please visit the <a ");
out.println("href=\"http://cgi-spec.golux.com\">CGI ");
out.println("Specification page</a>.");
out.println("</H4>");
}
printServletEnvironment(out, req, res);
out.println("</BODY></HTML>");
}
}
/*
* Behaviour depends on the status code and the value of debug.
*
* Status < 400 - Always calls setStatus. Returns false. CGI servlet will
* provide the response body.
* Status >= 400 - Depends on debug
* debug < 10 - Calls sendError(status), returns true. Standard error
* page mechanism will provide the response body.
* debug >= 10 - Calls setStatus(status), return false. CGI servlet will
* provide the response body.
*/
private boolean setStatus(HttpServletResponse response, int status) throws IOException {
if (status >= HttpServletResponse.SC_BAD_REQUEST && debug < 10) {
response.sendError(status);
return true;
} else {
response.setStatus(status);
return false;
}
}
/**
* Encapsulates the CGI environment and rules to derive
* that environment from the servlet container and request information.
*
* <p>
* </p>
*
* @since Tomcat 4.0
*/
protected class CGIEnvironment {
/** context of the enclosing servlet */
private ServletContext context = null;
/** context path of enclosing servlet */
private String contextPath = null;
/** servlet URI of the enclosing servlet */
private String servletPath = null;
/** pathInfo for the current request */
private String pathInfo = null;
/** real file system directory of the enclosing servlet's web app */
private String webAppRootDir = null;
/** tempdir for context - used to expand scripts in unexpanded wars */
private File tmpDir = null;
/** derived cgi environment */
private Hashtable<String, String> env = null;
/** cgi command to be invoked */
private String command = null;
/** cgi command's desired working directory */
private final File workingDirectory;
/** cgi command's command line parameters */
private final ArrayList<String> cmdLineParameters = new ArrayList<>();
/** whether or not this object is valid or not */
private final boolean valid;
/**
* Creates a CGIEnvironment and derives the necessary environment,
* query parameters, working directory, cgi command, etc.
*
* @param req HttpServletRequest for information provided by
* the Servlet API
* @param context ServletContext for information provided by the
* Servlet API
*
*/
protected CGIEnvironment(HttpServletRequest req,
ServletContext context) throws IOException {
setupFromContext(context);
setupFromRequest(req);
this.valid = setCGIEnvironment(req);
if (this.valid) {
workingDirectory = new File(command.substring(0,
command.lastIndexOf(File.separator)));
} else {
workingDirectory = null;
}
}
/**
* Uses the ServletContext to set some CGI variables
*
* @param context ServletContext for information provided by the
* Servlet API
*/
protected void setupFromContext(ServletContext context) {
this.context = context;
this.webAppRootDir = context.getRealPath("/");
this.tmpDir = (File) context.getAttribute(ServletContext.TEMPDIR);
}
/**
* Uses the HttpServletRequest to set most CGI variables
*
* @param req HttpServletRequest for information provided by
* the Servlet API
* @throws UnsupportedEncodingException
*/
protected void setupFromRequest(HttpServletRequest req)
throws UnsupportedEncodingException {
boolean isIncluded = false;
// Look to see if this request is an include
if (req.getAttribute(
RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
isIncluded = true;
}
if (isIncluded) {
this.contextPath = (String) req.getAttribute(
RequestDispatcher.INCLUDE_CONTEXT_PATH);
this.servletPath = (String) req.getAttribute(
RequestDispatcher.INCLUDE_SERVLET_PATH);
this.pathInfo = (String) req.getAttribute(
RequestDispatcher.INCLUDE_PATH_INFO);
} else {
this.contextPath = req.getContextPath();
this.servletPath = req.getServletPath();
this.pathInfo = req.getPathInfo();
}
// If getPathInfo() returns null, must be using extension mapping
// In this case, pathInfo should be same as servletPath
if (this.pathInfo == null) {
this.pathInfo = this.servletPath;
}
// If the request method is GET, POST or HEAD and the query string
// does not contain an unencoded "=" this is an indexed query.
// The parsed query string becomes the command line parameters
// for the cgi command.
if (req.getMethod().equals("GET")
|| req.getMethod().equals("POST")
|| req.getMethod().equals("HEAD")) {
String qs;
if (isIncluded) {
qs = (String) req.getAttribute(
RequestDispatcher.INCLUDE_QUERY_STRING);
} else {
qs = req.getQueryString();
}
if (qs != null && qs.indexOf('=') == -1) {
StringTokenizer qsTokens = new StringTokenizer(qs, "+");
while ( qsTokens.hasMoreTokens() ) {
cmdLineParameters.add(URLDecoder.decode(qsTokens.nextToken(),
parameterEncoding));
}
}
}
}
/**
* Resolves core information about the cgi script.
*
* <p>
* Example URI:
* </p>
* <PRE> /servlet/cgigateway/dir1/realCGIscript/pathinfo1 </PRE>
* <ul>
* <LI><b>path</b> = $CATALINA_HOME/mywebapp/dir1/realCGIscript
* <LI><b>scriptName</b> = /servlet/cgigateway/dir1/realCGIscript
* <LI><b>cgiName</b> = /dir1/realCGIscript
* <LI><b>name</b> = realCGIscript
* </ul>
* <p>
* CGI search algorithm: search the real path below
* <my-webapp-root> and find the first non-directory in
* the getPathTranslated("/"), reading/searching from left-to-right.
*</p>
*<p>
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix
* (or webAppRootDir alone if cgiPathPrefix is
* null).
*</p>
*<p>
* cgiPathPrefix is defined by setting
* this servlet's cgiPathPrefix init parameter
*
*</p>
*
* @param pathInfo String from HttpServletRequest.getPathInfo()
* @param webAppRootDir String from context.getRealPath("/")
* @param contextPath String as from
* HttpServletRequest.getContextPath()
* @param servletPath String as from
* HttpServletRequest.getServletPath()
* @param cgiPathPrefix subdirectory of webAppRootDir below which
* the web app's CGIs may be stored; can be null.
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix
* (or webAppRootDir alone if cgiPathPrefix is
* null). cgiPathPrefix is defined by setting
* the servlet's cgiPathPrefix init parameter.
*
*
* @return
* <ul>
* <li>
* <code>path</code> - full file-system path to valid cgi script,
* or null if no cgi was found
* <li>
* <code>scriptName</code> -
* CGI variable SCRIPT_NAME; the full URL path
* to valid cgi script or null if no cgi was
* found
* <li>
* <code>cgiName</code> - servlet pathInfo fragment corresponding to
* the cgi script itself, or null if not found
* <li>
* <code>name</code> - simple name (no directories) of the
* cgi script, or null if no cgi was found
* </ul>
*
* @since Tomcat 4.0
*/
protected String[] findCGI(String pathInfo, String webAppRootDir,
String contextPath, String servletPath,
String cgiPathPrefix) {
String path = null;
String name = null;
String scriptname = null;
if ((webAppRootDir != null)
&& (webAppRootDir.lastIndexOf(File.separator) ==
(webAppRootDir.length() - 1))) {
//strip the trailing "/" from the webAppRootDir
webAppRootDir =
webAppRootDir.substring(0, (webAppRootDir.length() - 1));
}
if (cgiPathPrefix != null) {
webAppRootDir = webAppRootDir + File.separator
+ cgiPathPrefix;
}
if (debug >= 2) {
log("findCGI: path=" + pathInfo + ", " + webAppRootDir);
}
File currentLocation = new File(webAppRootDir);
StringTokenizer dirWalker =
new StringTokenizer(pathInfo, "/");
if (debug >= 3) {
log("findCGI: currentLoc=" + currentLocation);
}
StringBuilder cginameBuilder = new StringBuilder();
while (!currentLocation.isFile() && dirWalker.hasMoreElements()) {
if (debug >= 3) {
log("findCGI: currentLoc=" + currentLocation);
}
String nextElement = (String) dirWalker.nextElement();
currentLocation = new File(currentLocation, nextElement);
cginameBuilder.append("/").append(nextElement);
}
String cginame = cginameBuilder.toString();
if (!currentLocation.isFile()) {
return new String[] { null, null, null, null };
}
if (debug >= 2) {
log("findCGI: FOUND cgi at " + currentLocation);
}
path = currentLocation.getAbsolutePath();
name = currentLocation.getName();
if (".".equals(contextPath)) {
scriptname = servletPath;
} else {
scriptname = contextPath + servletPath;
}
if (!servletPath.equals(cginame)) {
scriptname = scriptname + cginame;
}
if (debug >= 1) {
log("findCGI calc: name=" + name + ", path=" + path
+ ", scriptname=" + scriptname + ", cginame=" + cginame);
}
return new String[] { path, scriptname, cginame, name };
}
/**
* Constructs the CGI environment to be supplied to the invoked CGI
* script; relies heavily on Servlet API methods and findCGI
*
* @param req request associated with the CGI
* Invocation
*
* @return true if environment was set OK, false if there
* was a problem and no environment was set
*/
protected boolean setCGIEnvironment(HttpServletRequest req) throws IOException {
/*
* This method is slightly ugly; c'est la vie.
* "You cannot stop [ugliness], you can only hope to contain [it]"
* (apologies to Marv Albert regarding MJ)
*/
Hashtable<String,String> envp = new Hashtable<>();
// Add the shell environment variables (if any)
envp.putAll(shellEnv);
// Add the CGI environment variables
String sPathInfoOrig = null;
String sPathInfoCGI = null;
String sPathTranslatedCGI = null;
String sCGIFullPath = null;
String sCGIScriptName = null;
String sCGIFullName = null;
String sCGIName = null;
String[] sCGINames;
sPathInfoOrig = this.pathInfo;
sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig;
if (webAppRootDir == null ) {
// The app has not been deployed in exploded form
webAppRootDir = tmpDir.toString();
expandCGIScript();
}
sCGINames = findCGI(sPathInfoOrig,
webAppRootDir,
contextPath,
servletPath,
cgiPathPrefix);
sCGIFullPath = sCGINames[0];
sCGIScriptName = sCGINames[1];
sCGIFullName = sCGINames[2];
sCGIName = sCGINames[3];
if (sCGIFullPath == null
|| sCGIScriptName == null
|| sCGIFullName == null
|| sCGIName == null) {
return false;
}
envp.put("SERVER_SOFTWARE", "TOMCAT");
envp.put("SERVER_NAME", nullsToBlanks(req.getServerName()));
envp.put("GATEWAY_INTERFACE", "CGI/1.1");
envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol()));