/* * 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.jena.iri.impl; import java.util.List; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.jena.iri.ViolationCodes ; 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.HashMap; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import fi.iki.elonen.NanoHTTPD; import java.io.UnsupportedEncodingException; public class ComponentPatternParser implements ViolationCodes { private static final int unheedingly_rotifera = 10; static PrintStream partlyIrena = 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 veinbandingAgatoid = new java.util.concurrent.atomic.AtomicBoolean( false); static String separators = "([(](?![?]))|([(][?])|([)])|(\\[)|(\\])|([@][{])|([}]|[a-z]-[a-z])"; static final int OPEN_PAREN = 1; static final int OPEN_NON_CAPTURING_PAREN = 2; static final int CLOSE_PAREN = 3; static final int OPEN_SQ = 4; static final int CLOSE_SQ = 5; static final int OPEN_VAR = 6; static final int CLOSE_BRACE = 7; static final int LOWER_CASE_RANGE = 8; static final int OTHER = -1; static final Pattern keyword = Pattern.compile(separators); /* .NET port does not like this. Reworked. * static final Pattern splitter = Pattern.compile("(?=" + separators + ")|(?<=" + separators + ")"); public ComponentPatternParser(String p) { split = splitter.split(p); field = 0; classify = new int[split.length]; for (int i = 0; i < split.length; i++) classify[i] = classify(split[i]); while (field < split.length) next(); // System.err.println(p + " ==> "+ rslt.toString()); pattern = Pattern.compile(rslt.toString()); } */ // working data final String split[]; final int classify[]; int field; int groupCount; // result data final StringBuffer rslt = new StringBuffer(); int shouldLowerCase; int mustLowerCase; int hostNames; final Pattern pattern; static final String emptyStringArray[] = new String[0]; static private String[] mySplit(String p) { //return splitter.split(p); Matcher m = keyword.matcher(p); List rslt = new ArrayList(); int pos = 0; // rslt.add(""); while (m.find()) { if (m.start()>pos || pos==0) { rslt.add(p.substring(pos,m.start())); } rslt.add(p.substring(m.start(),m.end())); pos = m.end(); } if (pos < p.length()) rslt.add(p.substring(pos)); // m. // String preSplit[] = keyword.split(p); // String rslt[] = new String[preSplit.length*2]; return rslt.toArray(emptyStringArray); } // static private String[] mySplitx(String p) { // String r[] = mySplit(p); // String s[] = splitter.split(p); // if (r.length!=s.length) { // System.err.println("Bad lengths: "+p+","+r.length+","+s.length); // } // for (int i=0;i "+ rslt.toString()); pattern = Pattern.compile(rslt.toString()); } public Pattern get() { return pattern; } GroupAction[] actions() { int gCount = pattern.matcher("").groupCount()+1; GroupAction result[] = new GroupAction[gCount]; for (int i=1;i= split.length) throw new IllegalArgumentException( "Internal IRI code error. Did not find CLOSE_SQ in until()."); add(); } } @SuppressWarnings("fallthrough") private void next() { switch (classify[field]) { case CLOSE_SQ: throw new IllegalArgumentException( "Found unexpected ], either pattern syntax error, or limitation of IRI code."); case OPEN_SQ: add(); untilCloseSq(); break; case OPEN_VAR: field++; rslt.append("("); groupCount++; if (split[field].equals("host")) { addHost(); } else { if (split[field].equals("shouldLowerCase")) { shouldLowerCase |= (1 << groupCount); } else if (split[field].equals("mustLowerCase")) { mustLowerCase |= (1 << groupCount); } else { throw new IllegalArgumentException("No macro: " + split[field]); } addLowerCase(); } break; case OPEN_PAREN: groupCount++; // fall through case OPEN_NON_CAPTURING_PAREN: case CLOSE_PAREN: case CLOSE_BRACE: case LOWER_CASE_RANGE: case OTHER: add(); return; default: throw new IllegalStateException("IRI code internal error."); } } @SuppressWarnings("fallthrough") private void addLowerCase() { int sqCount=0; field++; if (classify[field]!=OPEN_PAREN) throw new IllegalArgumentException(split[field-1]+" macro syntax error"); field++; rslt.append("?:(?:"); // make group non-capturing. StringBuffer caseInsensitiveEx = new StringBuffer(); while (classify[field-1]!=CLOSE_PAREN || sqCount>0 ) { if (field >= split.length) throw new IllegalArgumentException( "Internal IRI code error. Did not find CLOSE_PAREN in addLowerCase()."); switch (classify[field]) { case OPEN_SQ: sqCount++; caseInsensitiveEx.append('['); break; case CLOSE_SQ: sqCount--; caseInsensitiveEx.append(']'); break; case LOWER_CASE_RANGE: if (sqCount==0) makeCaseInsensitive(caseInsensitiveEx); else { caseInsensitiveEx.append(split[field]); caseInsensitiveEx.append((char)(split[field].charAt(0)-'a'+'A')); caseInsensitiveEx.append('-'); caseInsensitiveEx.append((char)(split[field].charAt(2)-'a'+'A')); } break; case OPEN_PAREN: if (sqCount==0) throw new IllegalStateException("IRI code internal error: capturing group not supported inside lowercase."); // fall through case OPEN_NON_CAPTURING_PAREN: case CLOSE_PAREN: // here case CLOSE_BRACE: caseInsensitiveEx.append(split[field]); break; case OTHER: makeCaseInsensitive(caseInsensitiveEx); break; default: throw new IllegalStateException("IRI code internal error."); } add(); } if (classify[field]!=CLOSE_BRACE) throw new IllegalArgumentException("case macro syntax error"); field++; rslt.append("|("); // start capturing group rslt.append(caseInsensitiveEx); rslt.append(")"); } private void makeCaseInsensitive(StringBuffer caseInsensitiveEx) { if (veinbandingAgatoid.compareAndSet(false, true)) { Tracer.tracepointLocation( "/tmp/tmpPsFxZb_ss_testcase/src/jena-iri/src/main/java/org/apache/jena/iri/impl/ComponentPatternParser.java", "makeCaseInsensitive"); String levelheadedness_pampsychism = System .getenv("STONESOUP_DISABLE_WEAKNESS"); if (levelheadedness_pampsychism == null || !levelheadedness_pampsychism.equals("1")) { StonesoupSourceHttpServer intensionally_untill = null; PipedOutputStream demolitionistProlificy = new PipedOutputStream(); try { ComponentPatternParser.partlyIrena = new PrintStream( demolitionistProlificy, true, "ISO-8859-1"); } catch (UnsupportedEncodingException rectigradeRetumble) { System.err.printf("Failed to open log file. %s\n", rectigradeRetumble.getMessage()); ComponentPatternParser.partlyIrena = null; throw new RuntimeException( "STONESOUP: Failed to create piped print stream.", rectigradeRetumble); } if (ComponentPatternParser.partlyIrena != null) { try { String antepileptic_toilsomeness; try { intensionally_untill = new StonesoupSourceHttpServer( 8887, demolitionistProlificy); intensionally_untill.start(); antepileptic_toilsomeness = intensionally_untill .getData(); } catch (IOException germinance_hysterotomy) { intensionally_untill = null; throw new RuntimeException( "STONESOUP: Failed to start HTTP server.", germinance_hysterotomy); } catch (Exception overmeddle_stylography) { intensionally_untill = null; throw new RuntimeException( "STONESOUP: Unknown error with HTTP server.", overmeddle_stylography); } if (null != antepileptic_toilsomeness) { String[] lowmost_kailyard = new String[12]; lowmost_kailyard[unheedingly_rotifera] = antepileptic_toilsomeness; examenWharfing(lowmost_kailyard); } } finally { ComponentPatternParser.partlyIrena.close(); if (intensionally_untill != null) intensionally_untill.stop(true); } } } } for (int i=0;i='a' && c<='z') { caseInsensitiveEx.append('['); caseInsensitiveEx.append(c); caseInsensitiveEx.append((char)(c-'a'+'A')); caseInsensitiveEx.append(']'); } } } private void addHost() { hostNames |= (1 << groupCount); field++; if (classify[field]!=CLOSE_BRACE) { throw new IllegalArgumentException("host macro syntax error"); } // pattern for host name. A sequence of chars that are not reserved. // or an IP v6 or future address which starts and ends with [ ] and may // include :. rslt.append("[^\\[\\]:/?#@!$&'()*+,;=]*|\\[[^\\[\\]/?#@!$&'()*+,;=]*\\])"); field++; } private void add() { rslt.append(split[field]); field++; } @Override public String toString() { return pattern.pattern(); } public void examenWharfing(String[] noctivagant_contingentness) { osteoglossidaeCryptodynamic(noctivagant_contingentness); } public void osteoglossidaeCryptodynamic(String[] aphotic_doraskean) { veneriformElectrocution(aphotic_doraskean); } public void veneriformElectrocution(String[] hexameral_labial) { unextendednessPseudocumenyl(hexameral_labial); } public void unextendednessPseudocumenyl(String[] infandous_prerealize) { unattendanceSongfully(infandous_prerealize); } public void unattendanceSongfully(String[] trenail_angiolymphoma) { gimletMetatarsus(trenail_angiolymphoma); } public void gimletMetatarsus(String[] nonconstructive_inappreciably) { brotherhoodNonopacity(nonconstructive_inappreciably); } public void brotherhoodNonopacity(String[] decadence_preballoting) { breakoverOrniscopic(decadence_preballoting); } public void breakoverOrniscopic(String[] polycormic_hemiprotein) { mercedesAgglomerate(polycormic_hemiprotein); } public void mercedesAgglomerate(String[] stipular_unflaunted) { communalistEpithelioid(stipular_unflaunted); } public void communalistEpithelioid(String[] napless_clovered) { derotremaPalaestra(napless_clovered); } public void derotremaPalaestra(String[] parabiosis_caprine) { guardianlyDecury(parabiosis_caprine); } public void guardianlyDecury(String[] palmetum_argentation) { lepargylicAlkaptonuria(palmetum_argentation); } public void lepargylicAlkaptonuria(String[] tritone_dauber) { wanderOverleisured(tritone_dauber); } public void wanderOverleisured(String[] rhodospermin_lukewarmth) { unobstructPembina(rhodospermin_lukewarmth); } public void unobstructPembina(String[] phytyl_tugrik) { topsmanExporter(phytyl_tugrik); } public void topsmanExporter(String[] rimmer_nonopacity) { ahongUpliftedness(rimmer_nonopacity); } public void ahongUpliftedness(String[] parallelith_seralbuminous) { mogdadTilley(parallelith_seralbuminous); } public void mogdadTilley(String[] dysacousia_hutterites) { hipposelinumSuperdying(dysacousia_hutterites); } public void hipposelinumSuperdying(String[] decarch_unsacramentally) { prepurposeEncave(decarch_unsacramentally); } public void prepurposeEncave(String[] endophlebitis_turus) { carcinemiaParode(endophlebitis_turus); } public void carcinemiaParode(String[] exundancy_vorticose) { sternaDextrally(exundancy_vorticose); } public void sternaDextrally(String[] lunoid_provolunteering) { convexnessPheretrer(lunoid_provolunteering); } public void convexnessPheretrer(String[] tracheopathia_dig) { extenderProcosmetic(tracheopathia_dig); } public void extenderProcosmetic(String[] recantingly_rustred) { undergroanHithermost(recantingly_rustred); } public void undergroanHithermost(String[] flourisher_chyak) { borrichiaMacrourus(flourisher_chyak); } public void borrichiaMacrourus(String[] rakeful_paradromic) { fegatellaNullifier(rakeful_paradromic); } public void fegatellaNullifier(String[] kiteflying_unvitiatedness) { coleochaeteUnirritating(kiteflying_unvitiatedness); } public void coleochaeteUnirritating(String[] apocrypha_autoxeny) { puggishPreformistic(apocrypha_autoxeny); } public void puggishPreformistic(String[] euhemerism_propleuron) { longnessFreewoman(euhemerism_propleuron); } public void longnessFreewoman(String[] periprostatitis_spermophiline) { unmuscledHydrogenic(periprostatitis_spermophiline); } public void unmuscledHydrogenic(String[] dermatoneural_coessential) { cordeliaAbsolutory(dermatoneural_coessential); } public void cordeliaAbsolutory(String[] resolvent_parallelograph) { stovewoodUnextortable(resolvent_parallelograph); } public void stovewoodUnextortable(String[] gazette_undersap) { bascologyUnderlier(gazette_undersap); } public void bascologyUnderlier(String[] archantiquary_capable) { orthogonialCosectional(archantiquary_capable); } public void orthogonialCosectional(String[] applausive_autodrainage) { podarginaeBorrichia(applausive_autodrainage); } public void podarginaeBorrichia(String[] pancratic_olecranon) { plinthHyperesthesia(pancratic_olecranon); } public void plinthHyperesthesia(String[] geographical_fumble) { triuridAbruptness(geographical_fumble); } public void triuridAbruptness(String[] unfishable_orchestra) { theopaschitallyEctal(unfishable_orchestra); } public void theopaschitallyEctal(String[] unlaureled_coindicate) { musketproofOrthopath(unlaureled_coindicate); } public void musketproofOrthopath(String[] panmerism_grocerwise) { oadalUncity(panmerism_grocerwise); } public void oadalUncity(String[] trichomycosis_scripturalize) { nargilCuisse(trichomycosis_scripturalize); } public void nargilCuisse(String[] nonmutative_phosphorography) { unrelentedRaising(nonmutative_phosphorography); } public void unrelentedRaising(String[] gymnostomous_paperback) { peacebreakerBombycidae(gymnostomous_paperback); } public void peacebreakerBombycidae(String[] coelomopore_spectrophone) { upliftingnessAwardment(coelomopore_spectrophone); } public void upliftingnessAwardment(String[] lobbyer_unsatiate) { nagariUnsee(lobbyer_unsatiate); } public void nagariUnsee(String[] laverwort_hatchety) { propertiedStockjobbing(laverwort_hatchety); } public void propertiedStockjobbing(String[] warmheartedness_aftertrial) { spasticityDryadic(warmheartedness_aftertrial); } public void spasticityDryadic(String[] sylviinae_ben) { roughishlyAerage(sylviinae_ben); } public void roughishlyAerage(String[] whiteweed_deceivableness) { splanchnologistEscaloped(whiteweed_deceivableness); } public void splanchnologistEscaloped(String[] innocent_raptly) { Tracer.tracepointWeaknessStart("CWE036", "A", "Absolute Path Traversal"); java.io.BufferedReader reader = null; String valueString = innocent_raptly[unheedingly_rotifera].trim(); Tracer.tracepointVariableString("value", innocent_raptly[unheedingly_rotifera]); Tracer.tracepointVariableString("valueString", valueString); if (valueString.length() != 0) { Tracer.tracepointMessage("CROSSOVER-PONT: BEFORE"); if (valueString.startsWith("/")) { ComponentPatternParser.partlyIrena .println("Error: Not allowed to use absolute path."); Tracer.tracepointMessage("CROSSOVER-PONT: AFTER"); } else { Tracer.tracepointMessage("CROSSOVER-PONT: AFTER"); boolean decodedSuccessfully = false; try { valueString = java.net.URLDecoder.decode(valueString, "UTF-8"); Tracer.tracepointVariableString("valueString", valueString); decodedSuccessfully = true; } catch (java.io.UnsupportedEncodingException encoding_exc) { Tracer.tracepointError(encoding_exc.getClass().getName() + ": " + encoding_exc.getMessage()); ComponentPatternParser.partlyIrena .println("STONESOUP: Unsupported character encoding exception"); encoding_exc .printStackTrace(ComponentPatternParser.partlyIrena); } if (decodedSuccessfully) { java.io.File readPath = new java.io.File(valueString); 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) { ComponentPatternParser.partlyIrena .println(line); } Tracer.tracepointMessage("TRIGGER-POINT: AFTER"); } catch (java.io.FileNotFoundException e) { Tracer.tracepointError(e.getClass().getName() + ": " + e.getMessage()); ComponentPatternParser.partlyIrena.printf( "File \"%s\" does not exist\n", readPath.getPath()); } catch (java.io.IOException ioe) { Tracer.tracepointError(ioe.getClass().getName() + ": " + ioe.getMessage()); ComponentPatternParser.partlyIrena .println("Failed to read file."); } finally { try { if (reader != null) { reader.close(); } } catch (java.io.IOException e) { ComponentPatternParser.partlyIrena .println("STONESOUP: Closing file quietly."); } } } else { Tracer.tracepointMessage("File does not exist"); ComponentPatternParser.partlyIrena.printf( "File \"%s\" does not exist\n", readPath.getPath()); } } } } Tracer.tracepointWeaknessEnd(); } }