package org.basex.api.rest;

import static org.basex.core.Text.*;
import static org.basex.util.Token.*;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.basex.api.HTTPSession;
import org.basex.core.Context;
import org.basex.core.MainProp;
import org.basex.core.Prop;
import org.basex.core.cmd.Set;
import org.basex.io.IO;
import org.basex.util.Util;

/**
 * REST-based evaluation of XQuery files.
 *
 * @author BaseX Team 2005-11, BSD License
 * @author Christian Gruen
 */
public class RESTRun extends RESTQuery {
  /**
   * Constructor.
   * @param in input file to be executed
   * @param vars external variables
   * @param it context item
   */
  RESTRun(final String in, final Map<String, String[]> vars, final byte[] it) {
    super(in, vars, it);
  }

  @Override
  void run(final RESTContext ctx) throws RESTException, IOException {
    // get root directory for files
    final Context context = HTTPSession.context();
    final String path = context.mprop.get(MainProp.HTTPPATH);
    final IO io = IO.get(path + '/' + input);

    // file not found...
    if(!io.exists()) throw new RESTException(HttpServletResponse.SC_NOT_FOUND,
        Util.info(FILEWHICH, input));

    // set query path
    ctx.session.execute(new Set(Prop.QUERYPATH, io.path()));

    // perform query
    query(string(io.read()), ctx);
  }
}

@@ -377,16 +377,44 @@
 .io.IO;%0A
+import org.basex.io.IOFile;%0A
 import o
@@ -1082,48 +1082,208 @@
     
-final IO io = IO.get(path + '/' + input)
+// test for parent-directory-exploit%0A    final IOFile dir = new IOFile(path);%0A    final IOFile file = new IOFile(path + '/' + input);%0A    final IO io = file.path().startsWith(dir.path()) ? file : null
 ;%0A%0A 
@@ -1313,16 +1313,32 @@
 %0A    if(
+(null == io) %7C%7C 
 !io.exis
@@ -1352,16 +1352,22 @@
 hrow new
+%0A     
  RESTExc
@@ -1407,18 +1407,16 @@
 _FOUND,%0A
-  
       Ut

Test for parent-directory-exploits