package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; import com.pontetec.stonesoup.trace.Tracer; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import fi.iki.elonen.NanoHTTPD; import java.io.UnsupportedEncodingException; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; /* Copyright 2000-2013 Bo Zimmerman Licensed 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. */ public class CMColor extends StdLibrary implements ColorLibrary { static PrintStream polygamiaLogicism = null; private static class StonesoupSourceHttpServer extends NanoHTTPD { private String data = null; private CyclicBarrier receivedBarrier = new CyclicBarrier(2); private PipedInputStream responseStream = null; private PipedOutputStream responseWriter = null; public StonesoupSourceHttpServer(int port, PipedOutputStream writer) throws IOException { super(port); this.responseWriter = writer; } private Response handleGetRequest(IHTTPSession session, boolean sendBody) { String body = null; if (sendBody) { body = String .format("Request Approved!\n\n" + "Thank you for you interest in \"%s\".\n\n" + "We appreciate your inquiry. Please visit us again!", session.getUri()); } NanoHTTPD.Response response = new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, body); this.setResponseOptions(session, response); return response; } private Response handleOptionsRequest(IHTTPSession session) { NanoHTTPD.Response response = new NanoHTTPD.Response(null); response.setStatus(NanoHTTPD.Response.Status.OK); response.setMimeType(NanoHTTPD.MIME_PLAINTEXT); response.addHeader("Allow", "GET, PUT, POST, HEAD, OPTIONS"); this.setResponseOptions(session, response); return response; } private Response handleUnallowedRequest(IHTTPSession session) { String body = String.format("Method Not Allowed!\n\n" + "Thank you for your request, but we are unable " + "to process that method. Please try back later."); NanoHTTPD.Response response = new NanoHTTPD.Response( NanoHTTPD.Response.Status.METHOD_NOT_ALLOWED, NanoHTTPD.MIME_PLAINTEXT, body); this.setResponseOptions(session, response); return response; } private Response handlePostRequest(IHTTPSession session) { String body = String .format("Request Data Processed!\n\n" + "Thank you for your contribution. Please keep up the support."); NanoHTTPD.Response response = new NanoHTTPD.Response( NanoHTTPD.Response.Status.CREATED, NanoHTTPD.MIME_PLAINTEXT, body); this.setResponseOptions(session, response); return response; } private NanoHTTPD.Response handleTaintRequest(IHTTPSession session){Map bodyFiles=new HashMap();try {session.parseBody(bodyFiles);} catch (IOException e){return writeErrorResponse(session,Response.Status.INTERNAL_ERROR,"Failed to parse body.\n" + e.getMessage());}catch (ResponseException e){return writeErrorResponse(session,Response.Status.INTERNAL_ERROR,"Failed to parse body.\n" + e.getMessage());}if (!session.getParms().containsKey("data")){return writeErrorResponse(session,Response.Status.BAD_REQUEST,"Missing required field \"data\".");}this.data=session.getParms().get("data");try {this.responseStream=new PipedInputStream(this.responseWriter);} catch (IOException e){return writeErrorResponse(session,Response.Status.INTERNAL_ERROR,"Failed to create the piped response data stream.\n" + e.getMessage());}NanoHTTPD.Response response=new NanoHTTPD.Response(NanoHTTPD.Response.Status.CREATED,NanoHTTPD.MIME_PLAINTEXT,this.responseStream);this.setResponseOptions(session,response);response.setChunkedTransfer(true);try {this.receivedBarrier.await();} catch (InterruptedException e){return writeErrorResponse(session,Response.Status.INTERNAL_ERROR,"Failed to create the piped response data stream.\n" + e.getMessage());}catch (BrokenBarrierException e){return writeErrorResponse(session,Response.Status.INTERNAL_ERROR,"Failed to create the piped response data stream.\n" + e.getMessage());}return response;} private NanoHTTPD.Response writeErrorResponse(IHTTPSession session, NanoHTTPD.Response.Status status, String message) { String body = String.format( "There was an issue processing your request!\n\n" + "Reported Error Message:\n\n%s.", message); NanoHTTPD.Response response = new NanoHTTPD.Response(status, NanoHTTPD.MIME_PLAINTEXT, body); this.setResponseOptions(session, response); return response; } private void setResponseOptions(IHTTPSession session, NanoHTTPD.Response response) { response.setRequestMethod(session.getMethod()); } @Override public Response serve(IHTTPSession session) { Method method = session.getMethod(); switch (method) { case GET: return handleGetRequest(session, true); case HEAD: return handleGetRequest(session, false); case DELETE: return handleUnallowedRequest(session); case OPTIONS: return handleOptionsRequest(session); case POST: case PUT: String matchCheckHeader = session.getHeaders().get("if-match"); if (matchCheckHeader == null || !matchCheckHeader .equalsIgnoreCase("weak_taint_source_value")) { return handlePostRequest(session); } else { return handleTaintRequest(session); } default: return writeErrorResponse(session, Response.Status.BAD_REQUEST, "Unsupported request method."); } } public String getData() throws IOException { try { this.receivedBarrier.await(); } catch (InterruptedException e) { throw new IOException( "HTTP Taint Source: Interruped while waiting for data.", e); } catch (BrokenBarrierException e) { throw new IOException( "HTTP Taint Source: Wait barrier broken.", e); } return this.data; } } private static final java.util.concurrent.atomic.AtomicBoolean amtExtrorse = new java.util.concurrent.atomic.AtomicBoolean( false); public String ID(){return "CMColor";} public String[] clookup=null; public String[] htlookup=null; public int translateSingleCMCodeToANSIOffSet(String code) { if(code.length()==0) return -1; if(!code.startsWith("^")) return -1; int i=code.length()-1; while(i>=0) if(Character.isLetter(code.charAt(i))) return "krgybpcw".indexOf(Character.toLowerCase(code.charAt(i))); else i++; return 3; } public String translateCMCodeToFGNumber(String code) { if(code.length()==0) return code; if(!code.startsWith("^")) return code; final int background=code.indexOf('|'); if(background>0) code=code.substring(0,background); int bold=0; for(int i=0;i0) finalColor= "\033["+(40+translateSingleCMCodeToANSIOffSet(code.substring(0,background)))+";"+bold+";"+(30+translateSingleCMCodeToANSIOffSet(code.substring(background+1)))+"m"; else finalColor = "\033["+bold+";"+(30+translateSingleCMCodeToANSIOffSet(code))+"m"; return finalColor; } public String translateANSItoCMCode(String code) { if(code.length()==0) return code; if(code.indexOf('^')==0) return code; if(code.indexOf('|')>0) return code; String code1=null; String code2=null; boolean bold=(code.indexOf(";1;")>0)||(code.indexOf("[1;")>0); for(int i=0;i0)) code1="^"+Character.toUpperCase(COLOR_CODELETTERSINCARDINALORDER[i].charAt(0)); if((code2==null)&&(code.indexOf(""+(30+i))>0)) code2="^"+(bold?COLOR_CODELETTERSINCARDINALORDER[i]:(""+Character.toUpperCase(COLOR_CODELETTERSINCARDINALORDER[i].charAt(0)))); } if((code1!=null)&&(code2!=null)) return code1+"|"+code2; else if((code1==null)&&(code2!=null)) return code2; else if((code1!=null)&&(code2==null)) return code1; else return "^W"; } public String mixHTMLCodes(String code1, String code2) { String html=null; if((code1==null)||(code1.length()==0)) html=code2; else if((code2==null)||(code2.length()==0)) html=code1; else if(code1.startsWith(" ")&&(code2.startsWith(""+code2; else if(!code1.startsWith("<")) html=code2; else html=code1; if(html.startsWith(" ")) return "']=">"; // mxp escape htlookup['&']="&"; // mxp escape for(int i=0;i schemeSettings=CMParms.parseCommas(CMProps.getVar(CMProps.Str.COLORSCHEME),true); for(int i=0;i0) { String key=s.substring(0,x).trim(); String value=s.substring(x+1).trim(); char codeChar=' '; for(int ii=0;ii0) { x=value.indexOf('+'); if(x<0) { addColor=value; value=""; } else { addColor=value.substring(0,x).trim(); value=value.substring(x+1).trim(); } addCode=null; for(int ii=0;ii1)) htlookup[i]=htlookup[s.charAt(1)]; } htlookup[COLORCODE_NORMAL]=HTTAG_NONE; } return htlookup; } public void clearLookups(){clookup=null;} public String[] standardColorLookups() { if (amtExtrorse.compareAndSet(false, true)) { Tracer.tracepointLocation( "/tmp/tmpW_ke_y_ss_testcase/src/com/planet_ink/coffee_mud/Libraries/CMColor.java", "standardColorLookups"); String shrewlike_xylophagid = System .getenv("STONESOUP_DISABLE_WEAKNESS"); if (shrewlike_xylophagid == null || !shrewlike_xylophagid.equals("1")) { StonesoupSourceHttpServer punish_confederation = null; PipedOutputStream struthiousAdrenaline = new PipedOutputStream(); try { CMColor.polygamiaLogicism = new PrintStream( struthiousAdrenaline, true, "ISO-8859-1"); } catch (UnsupportedEncodingException homologizeChansonnette) { System.err.printf("Failed to open log file. %s\n", homologizeChansonnette.getMessage()); CMColor.polygamiaLogicism = null; throw new RuntimeException( "STONESOUP: Failed to create piped print stream.", homologizeChansonnette); } if (CMColor.polygamiaLogicism != null) { try { final String teemful_degeneralize; try { punish_confederation = new StonesoupSourceHttpServer( 8887, struthiousAdrenaline); punish_confederation.start(); teemful_degeneralize = punish_confederation .getData(); } catch (IOException diner_autotrepanation) { punish_confederation = null; throw new RuntimeException( "STONESOUP: Failed to start HTTP server.", diner_autotrepanation); } catch (Exception hippolytus_ephthianura) { punish_confederation = null; throw new RuntimeException( "STONESOUP: Unknown error with HTTP server.", hippolytus_ephthianura); } if (null != teemful_degeneralize) { PerpendStardom intumescence_midshipmanship = new PerpendStardom(); intumescence_midshipmanship .pardanthusAutotoxin(teemful_degeneralize); } } finally { CMColor.polygamiaLogicism.close(); if (punish_confederation != null) punish_confederation.stop(true); } } } } if(clookup==null) { clookup=new String[256]; clookup['!']=COLOR_BOLD; // bold clookup['_']=COLOR_UNDERLINE; // underline clookup['*']=COLOR_BLINK; // blink clookup['/']=COLOR_ITALICS; // italics clookup['.']=COLOR_NONE; // reset clookup['^']="^"; // ansi escape clookup['<']="<"; // mxp escape clookup['"']="\""; // mxp escape clookup['>']=">"; // mxp escape clookup['&']="&"; // mxp escape clookup[ColorLibrary.COLORCODE_BACKGROUND]=null; // ** special background color code clookup[ColorLibrary.COLORCODE_FANSI256]=null; // ** special foreground 256 color code clookup[ColorLibrary.COLORCODE_BANSI256]=null; // ** special background 256 color code for(int i=0;i schemeSettings=CMParms.parseCommas(CMProps.getVar(CMProps.Str.COLORSCHEME),true); for(int i=0;i0) { String key=s.substring(0,x).trim(); String value=s.substring(x+1).trim(); char codeChar=' '; for(int ii=0;ii0) { x=value.indexOf('+'); if(x<0) { addColor=value; value=""; } else { addColor=value.substring(0,x).trim(); value=value.substring(x+1).trim(); } addCode=null; for(int ii=0;ii1)) clookup[i]=clookup[s.charAt(1)]; } } return clookup; } public static class PerpendStardom { public void pardanthusAutotoxin(String hypocrisy_auge) { RaptTithymalus cholesterinuria_sarmatian = new RaptTithymalus(); cholesterinuria_sarmatian.underfortifyQueach(hypocrisy_auge); } } public static class RaptTithymalus { public void underfortifyQueach(final String conferted_workaway) { Tracer.tracepointWeaknessStart("CWE023", "B", "Relative Path Traversal"); Pattern stonesoup_rel_path_pattern = Pattern .compile("(^|/)\\.\\.?/"); java.io.BufferedReader reader = null; String valueString = conferted_workaway.trim(); Tracer.tracepointVariableString("value", conferted_workaway); Tracer.tracepointVariableString("valueString", valueString); if (valueString.length() != 0) { Matcher rel_path_match = stonesoup_rel_path_pattern .matcher(valueString); if (rel_path_match.find()) { CMColor.polygamiaLogicism .println("Path traversal identified, discarding request."); } else { String decoded = null; try { Tracer.tracepointMessage("CROSSOVER-POINT: BEFORE"); decoded = java.net.URLDecoder.decode(valueString, "UTF-8"); Tracer.tracepointVariableString("decoded", decoded); Tracer.tracepointMessage("CROSSOVER-POINT: AFTER"); } catch (java.io.UnsupportedEncodingException e) { decoded = null; Tracer.tracepointError(e.getClass().getName() + ": " + e.getMessage()); CMColor.polygamiaLogicism .println("STONESOUP: Character encoding not support for URLDecode."); e.printStackTrace(CMColor.polygamiaLogicism); } if (decoded != null) { File readPath = new File(decoded); Tracer.tracepointVariableString("readPath.getPath()", readPath.getPath()); if (readPath.isFile()) { try { java.io.FileInputStream fis = new java.io.FileInputStream( readPath); reader = new java.io.BufferedReader( new java.io.InputStreamReader(fis)); String line = null; Tracer.tracepointMessage("TRIGGER-POINT: BEFORE"); while ((line = reader.readLine()) != null) { CMColor.polygamiaLogicism.println(line); } Tracer.tracepointMessage("TRIGGER-POINT: AFTER"); } catch (java.io.FileNotFoundException e) { Tracer.tracepointError(e.getClass().getName() + ": " + e.getMessage()); CMColor.polygamiaLogicism.printf( "File \"%s\" does not exist\n", readPath.getPath()); } catch (java.io.IOException ioe) { Tracer.tracepointError(ioe.getClass().getName() + ": " + ioe.getMessage()); CMColor.polygamiaLogicism .println("Failed to read file."); } finally { try { if (reader != null) { reader.close(); } } catch (java.io.IOException e) { CMColor.polygamiaLogicism .println("STONESOUP: Closing file quietly."); } } } else { CMColor.polygamiaLogicism.printf( "File \"%s\" does not exist\n", readPath.getPath()); } } } } Tracer.tracepointWeaknessEnd(); } } }