package org.w3c.jigsaw.frames ;
import java.io.* ;
import java.util.*;
import java.net.*;
import org.w3c.tools.resources.*;
import org.w3c.tools.resources.ProtocolException;
import org.w3c.www.mime.* ;
import org.w3c.jigsaw.http.* ;
import org.w3c.www.http.*;
import org.w3c.jigsaw.auth.AuthFilter;
class CGIHeaderHolder implements MimeHeaderHolder {
String status = null;
String location = null;
Hashtable headers = null;
MimeParser parser = null;
@param parser@return
public boolean notifyBeginParsing(MimeParser parser)
throws IOException
{
return false;
}
@param parser
public void notifyEndParsing(MimeParser parser)
throws IOException
{
return ;
}
@param name@param buf@param off@param len
public void notifyHeader(String name, byte buf[], int off, int len)
throws MimeParserException
{
if ( name.equalsIgnoreCase("status") ) {
status = new String(buf, 0, off, len);
} else if ( name.equalsIgnoreCase("location") ) {
location = new String(buf, 0, off, len);
} else {
String extraval = new String(buf, 0, off, len);
if ( headers == null ) {
headers = new Hashtable(11);
} else {
String val = (String) headers.get(name.toLowerCase());
if ( val != null )
extraval = val + "," + extraval;
}
headers.put(name.toLowerCase(), extraval);
}
}
public String getStatus() {
return status;
}
public String getLocation() {
return location;
}
@param name@return
public String getValue(String name) {
return (headers == null) ? null : (String) headers.get(name);
}
@return
public Enumeration enumerateHeaders() {
if ( headers == null )
return null;
return headers.keys();
}
public InputStream getInputStream() {
return parser.getInputStream();
}
CGIHeaderHolder(MimeParser parser) {
this.parser = parser;
}
}
class CGIHeaderHolderFactory implements MimeParserFactory {
@param parser@return
public MimeHeaderHolder createHeaderHolder(MimeParser parser) {
return new CGIHeaderHolder(parser);
}
CGIHeaderHolderFactory() {
}
}
class ProcessFeeder extends Thread {
Process proc = null ;
OutputStream out = null ;
InputStream in = null ;
int count = -1 ;
public void run () {
try {
byte buffer[] = new byte[4096] ;
int got = -1 ;
if ( count >= 0 ) {
while ( (count > 0) && ((got = in.read(buffer)) > 0) ) {
out.write (buffer, 0, got) ;
count -= got ;
}
} else {
while ( (got = in.read(buffer)) > 0 ) {
out.write (buffer, 0, got) ;
}
}
} catch (Exception e) {
System.out.println ("ProcessFeeder: caught exception !") ;
e.printStackTrace() ;
} finally {
try { out.flush() ; } catch (IOException ex) {}
try { out.close() ; } catch (IOException ex) {}
try { proc.waitFor() ; } catch (Exception ex) {}
}
}
ProcessFeeder (Process proc, InputStream in) {
this (proc, in, -1) ;
}
ProcessFeeder (Process proc, InputStream in, int count) {
this.proc = proc ;
this.out = proc.getOutputStream() ;
this.in = in ;
this.count = count ;
}
}
public class CgiFrame extends HTTPFrame {
private final static
String STATE_EXTRA_PATH = "org.w3c.jigsaw.frames.CgiFrame.extraPath";
protected static int ATTR_INTERPRETER = -1;
protected static int ATTR_COMMAND = -1 ;
protected static int ATTR_NOHEADER = -1 ;
protected static int ATTR_GENERATES_FORM = -1 ;
protected static int ATTR_REMOTE_HOST = -1;
protected static int ATTR_CGI_DEBUG = -1;
static {
Attribute a = null ;
Class cls = null ;
try {
cls = Class.forName("org.w3c.jigsaw.frames.CgiFrame") ;
} catch (Exception ex) {
ex.printStackTrace() ;
System.exit(1) ;
}
a = new StringAttribute("interpreter"
, null
, Attribute.EDITABLE);
ATTR_INTERPRETER = AttributeRegistry.registerAttribute(cls, a);
a = new StringArrayAttribute("command"
, null
, Attribute.MANDATORY|Attribute.EDITABLE);
ATTR_COMMAND = AttributeRegistry.registerAttribute(cls, a) ;
a = new BooleanAttribute("noheader"
, Boolean.FALSE
, Attribute.EDITABLE) ;
ATTR_NOHEADER = AttributeRegistry.registerAttribute(cls, a) ;
a = new BooleanAttribute("generates-form"
, Boolean.TRUE
, Attribute.EDITABLE) ;
ATTR_GENERATES_FORM = AttributeRegistry.registerAttribute(cls, a);
a = new BooleanAttribute("remote-host"
, null
, Attribute.EDITABLE);
ATTR_REMOTE_HOST = AttributeRegistry.registerAttribute(cls, a);
a = new BooleanAttribute("cgi-debug"
, Boolean.FALSE
, Attribute.EDITABLE);
ATTR_CGI_DEBUG = AttributeRegistry.registerAttribute(cls, a);
}
@return
public String getInterpreter() {
return getString(ATTR_INTERPRETER, null);
}
public String[] getCommand() {
return (String[]) getValue(ATTR_COMMAND, null) ;
}
@return
public boolean checkNoheaderFlag() {
return getBoolean(ATTR_NOHEADER, false) ;
}
@return
public boolean checkGeneratesFormFlag() {
return getBoolean(ATTR_GENERATES_FORM, true) ;
}
@return
public boolean checkRemoteHost() {
return getBoolean(ATTR_REMOTE_HOST, false);
}
@return
public boolean checkCgiDebug() {
return getBoolean(ATTR_CGI_DEBUG, false);
}
@param name@return
public String getEnvName(String name) {
int sl = name.length();
StringBuffer sb = new StringBuffer(5+sl);
sb.append("HTTP_");
for (int i = 0 ; i < sl ; i++) {
char ch = name.charAt(i);
sb.append((ch == '-') ? '_' : Character.toUpperCase(ch));
}
return sb.toString();
}
@param process@param request@exception ProtocolException
protected Reply handleCGIOutput (Process process, Request request)
throws ProtocolException
{
if ( checkNoheaderFlag() ) {
Reply reply = request.makeReply(HTTP.NOHEADER) ;
reply.setStream (process.getInputStream()) ;
return reply ;
}
if ( checkCgiDebug() ) {
Reply reply = request.makeReply(HTTP.OK);
reply.setContentType(MimeType.TEXT_PLAIN);
reply.setStream(process.getInputStream());
return reply;
}
MimeParser p = new MimeParser(process.getInputStream(),
new CGIHeaderHolderFactory());
Reply reply = null ;
try {
CGIHeaderHolder h = (CGIHeaderHolder) p.parse();
String svalue = h.getStatus();
String location = h.getLocation();
if ( svalue != null ) {
int status = -1;
try {
status = Integer.parseInt(svalue);
} catch (Exception ex) {
String msg = ("Emited an invalid status line ["+
svalue + "].");
getServer().errlog(this, msg);
reply = request.makeReply(HTTP.INTERNAL_SERVER_ERROR);
reply.setContent("CGI script emited invalid status.");
throw new HTTPException(reply);
}
reply = request.makeReply(status);
} else {
reply = request.makeReply((location == null)
? HTTP.OK
: HTTP.FOUND);
}
if ( location != null ) {
try {
reply.setLocation(new URL(getURL(request), location));
} catch (MalformedURLException ex) {
getServer().errlog(this, "unable to create location url "+
location+
" in base "+getURL(request));
}
}
Enumeration e = h.enumerateHeaders();
if ( e != null ) {
while ( e.hasMoreElements() ) {
String hname = (String) e.nextElement();
reply.setValue(hname, (String) h.getValue(hname));
}
}
reply.setStream(p.getInputStream()) ;
} catch (IOException ex) {
ex.printStackTrace();
} catch (MimeParserException ex) {
String msg = (getURL(request)
+": emited invalid output ["+
ex.getMessage() +"]");
getServer().errlog(this, msg);
Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
error.setContent("CGI error: unable to parse script headers.") ;
throw new HTTPException (error) ;
}
return reply ;
}
@param name@param val@param into
private void addEnv (String name, String val, Vector into) {
into.addElement (name+"="+val) ;
}
@param request@return @exception HTTPException
protected Process makeCgiCommand (Request request)
throws ProtocolException, IOException
{
String query = null;
String command[] = getCommand() ;
if ( command == null ) {
Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
error.setContent("CgiResource mis-configured: it doesn't have a "
+ " command attribute");
throw new HTTPException(error);
}
Vector env = new Vector(32) ;
httpd server = request.getClient().getServer() ;
InetAddress sadr = server.getInetAddress() ;
String svalue = (String) request.getState(AuthFilter.STATE_AUTHTYPE);
if ( svalue != null )
addEnv("AUTH_TYPE", svalue, env);
svalue = request.getValue("content-length");
if ( svalue != null )
addEnv("CONTENT_LENGTH", svalue, env);
svalue = request.getValue("content-type");
if ( svalue != null )
addEnv("CONTENT_TYPE", svalue, env);
addEnv ("GATEWAY_INTERFACE", "CGI/1.1", env) ;
svalue = (String) request.getState(STATE_EXTRA_PATH);
if ( svalue == null )
addEnv ("PATH_INFO", "/", env) ;
else
addEnv ("PATH_INFO", svalue, env) ;
query = request.getQueryString();
if ( query != null )
addEnv("QUERY_STRING", query, env) ;
svalue = request.getClient().getInetAddress().toString();
addEnv ("REMOTE_ADDR", svalue, env);
svalue = (String) request.getState(AuthFilter.STATE_AUTHUSER);
if ( svalue != null )
addEnv("REMOTE_USER", svalue, env);
if ( checkRemoteHost() ) {
String host = request.getClient().getInetAddress().getHostName();
addEnv("REMOTE_HOST", host, env);
}
addEnv ("REQUEST_METHOD", request.getMethod(), env) ;
addEnv("SCRIPT_NAME", getURLPath(), env);
addEnv ("SERVER_NAME", getServer().getHost(), env) ;
svalue = Integer.toString(getServer().getLocalPort());
addEnv ("SERVER_PORT", svalue, env);
addEnv ("SERVER_PROTOCOL", request.getVersion(), env) ;
addEnv ("SERVER_SOFTWARE", server.getSoftware(), env) ;
Enumeration e = request.enumerateHeaderDescriptions(false);
while ( e.hasMoreElements() ) {
HeaderDescription d = (HeaderDescription) e.nextElement();
addEnv(getEnvName(d.getName())
, request.getHeaderValue(d).toString()
, env);
}
if ( query != null ) {
String querycmd[] = new String[command.length+1] ;
System.arraycopy(command, 0, querycmd, 0, command.length) ;
querycmd[command.length] = query ;
command = querycmd ;
}
String aenv[] = new String[env.size()] ;
env.copyInto (aenv) ;
if ( getInterpreter() != null ) {
String run[] = new String[command.length+1];
run[0] = getInterpreter();
System.arraycopy(command, 0, run, 1, command.length);
return Runtime.getRuntime().exec (run, aenv) ;
} else {
return Runtime.getRuntime().exec (command, aenv) ;
}
}
@param ls@param lr@return
public boolean lookup(LookupState ls, LookupResult lr)
throws ProtocolException
{
String extraPath = ls.getRemainingPath(true);
if ((extraPath == null) || extraPath.equals(""))
extraPath = "/";
Request request = (Request) ls.getRequest();
if ( request != null )
request.setState(STATE_EXTRA_PATH, extraPath);
lr.setTarget(getResource().getResourceReference());
return super.lookup(ls, lr);
}
@param request@exception ProtocolException
public Reply get(Request request)
throws ProtocolException, NotAProtocolException
{
if ( ! checkGeneratesFormFlag() )
return super.get (request) ;
Process process = null ;
try {
process = makeCgiCommand (request) ;
} catch (IOException e) {
Reply error = request.makeReply(HTTP.NOT_FOUND) ;
error.setContent("The resource's script wasn't found.") ;
throw new HTTPException (error) ;
}
return handleCGIOutput (process, request) ;
}
@param request@exception ProtocolException
public Reply post(Request request)
throws ProtocolException, NotAProtocolException
{
Process process = null ;
try {
process = makeCgiCommand(request) ;
} catch (IOException ex) {
String msg = ("The process "+
getCommand()[0] +" couldn't be executed ["+
ex.getMessage() + "]");
getServer().errlog(this, msg);
Reply error = request.makeReply(HTTP.INTERNAL_SERVER_ERROR) ;
error.setContent("CGI script is misconfigured.");
throw new HTTPException (error) ;
}
try {
Client client = request.getClient();
if ( client != null )
client.sendContinue();
InputStream in = request.getInputStream();
if ( in == null ) {
process.getOutputStream().close();
} else {
(new ProcessFeeder(process, in)).start();
}
} catch (IOException ex) {
Reply error = request.makeReply(HTTP.BAD_REQUEST);
error.setContent("The request didn't have a valid input.");
throw new HTTPException(error);
}
return handleCGIOutput(process, request);
}
@param values
public void registerResource(FramedResource resource) {
super.registerResource(resource);
if (getCommand() == null) {
if (getFileResource() != null) {
if (getFileResource().getFile() != null) {
String cmd[] = new String[1];
cmd[0] = getFileResource().getFile().getAbsolutePath();
setValue(ATTR_COMMAND, cmd);
}
}
}
}
}