Ejemplo n.º 1
0
URI OAuth2::getVerifyURL(const URI &uri, const string &state) const {
  // Check that SID matches state (Confirm anti-forgery state token)
  if (!uri.has("code") || !uri.has("state") || uri.get("state") != state) {
    LOG_DEBUG(3, "Failed anti-forgery check: uri code="
              << (uri.has("code") ? uri.get("code") : "<null>") << " uri state="
              << (uri.has("state") ? uri.get("state") : "<null>")
              << " server state=" << state);
    THROWC("Failed anti-forgery check", Event::HTTPStatus::HTTP_UNAUTHORIZED);
  }

  // Check config
  validateOption(clientID, "client-id");
  validateOption(clientSecret, "client-secret");
  validateOption(redirectBase, "redirect-base");
  validateOption(tokenURL, "token-url");

  // Exchange code for access token and ID token
  URI postURI(tokenURL);

  // Setup Query data
  postURI.set("code", uri.get("code"));
  postURI.set("client_id", clientID);
  postURI.set("client_secret", clientSecret);
  postURI.set("redirect_uri", redirectBase + uri.getPath());
  postURI.set("grant_type", "authorization_code");

  LOG_DEBUG(5, __func__ << ": " << postURI);

  return postURI;
}
bool ResourceWebPageHandler::handlePage(WebContext &ctx, ostream &stream,
                                        const URI &uri) {
  const Resource *res = root->find(uri.getPath());
  if (!res) return false;

  stream.write(res->getData(), res->getLength());

  return true;
}
Ejemplo n.º 3
0
bool WebHandler::handlePage(WebContext &ctx, ostream &stream, const URI &uri) {
  if (WebPageHandlerGroup::handlePage(ctx, stream, uri)) {
    // Tell client to cache static pages
    if (ctx.isStatic()) ctx.getConnection().getResponse().setCacheExpire();

    // Set default content type
    Response &response = ctx.getConnection().getResponse();
    if (!response.has("Content-Type"))
      response.setContentTypeFromExtension(uri.getPath());

    return true;
  }

  return false;
}
Ejemplo n.º 4
0
void WebHandler::buildResponse(HTTP::Context *_ctx) {
  if (!initialized) THROW("Not initialized");

  WebContext *ctx = dynamic_cast<WebContext *>(_ctx);
  if (!ctx) THROW("Expected WebContext");

  Connection &con = ctx->getConnection();

  // Check request method
  Request &request = con.getRequest();
  switch (request.getMethod()) {
    case RequestMethod::HTTP_GET:
    case RequestMethod::HTTP_POST:
      break;
  default: return; // We only handle GET and POST
  }

  try {
    if (!allow(*ctx)) errorPage(*ctx, StatusCode::HTTP_UNAUTHORIZED);
    else {
      URI uri = con.getRequest().getURI();
      const string &path = uri.getPath();
      if (path[path.length() - 1] == '/') uri.setPath(path + "index.html");

      // TODO sanitize path

      if (!handlePage(*ctx, con, uri))
        errorPage(*ctx, StatusCode::HTTP_NOT_FOUND);
    }

  } catch (const Exception &e) {
    StatusCode code = StatusCode::HTTP_INTERNAL_SERVER_ERROR;
    if (0 < e.getCode()) code = (StatusCode::enum_t)e.getCode();

    errorPage(*ctx, code, e.getMessage());

    LOG_ERROR(code << ": " << e);
  }

  con << flush;
}
Ejemplo n.º 5
0
CircuitConfig::CircuitConfig(const URI& uri)
    : impl(new CircuitConfig::Impl(uri.getPath()))
{
}
Ejemplo n.º 6
0
bool JSONAPI::handlePage(HTTP::WebContext &ctx, ostream &stream,
                         const URI &uri) {
  if (!String::startsWith(uri.getPath(), root)) return false;

  string cmd = uri.getPath().substr(root.length());

  // Look up command
  api_t::const_iterator it = api.find(cmd);
  if (it == api.end()) return false;

  ctx.setDynamic(); // Don't cache
  HTTP::Connection &con = ctx.getConnection();

  bool jsonp = !jsonpCB.empty() && uri.has(jsonpCB);

  if (jsonp) {
    con.getResponse().setContentType("application/javascript");
    con << uri.get(jsonpCB) << '(';

  } else con.getResponse().setContentType("application/json");

  JSON::Writer writer(con, 0, !uri.has("pretty"),
                      uri.has("python_mode") ? JSON::Writer::PYTHON_MODE :
                      JSON::Writer::JSON_MODE);

  try {
    // Parse JSON data
    JSON::ValuePtr msg;

    if (con.getRequest().hasContentType() &&
        String::startsWith(con.getRequest().getContentType(),
                           "application/json")) {
      MemoryBuffer &payload = con.getPayload();
      if (payload.getFill()) msg = JSON::Reader(payload).parse();

    } else if (!uri.empty()) {
      msg = new JSON::Dict;

      for (URI::const_iterator it = uri.begin(); it != uri.end(); it++)
        msg->insert(it->first, it->second);
    }

    // Dispatch API command
    if (msg.isNull()) LOG_DEBUG(5, "JSONAPI Call: " << cmd << "()");
    else LOG_DEBUG(5, "JSONAPI Call: " << cmd << '(' << *msg << ')');
    it->second->handle(ctx, cmd, msg, writer);

    // Make sure JSON stream is complete
    writer.close();

  } catch (const Exception &e) {
    LOG_ERROR(e);

    // Clear possibly partial or invalid response
    con.clearResponseBuffer();

    // jsonp header
    if (jsonp) con << uri.get(jsonpCB) << '(';

    // Send error message
    JSON::Writer writer(con, 0, true);
    writer.beginList();
    writer.append("error");
    writer.append(e.getMessage());
    writer.endList();
    writer.close();
  }

  if (jsonp) con << ");";

  return true;
}
Ejemplo n.º 7
0
void URITest::testConstruction()
{
	URI uri;
	assert (uri.getScheme().empty());
	assert (uri.getAuthority().empty());
	assert (uri.getUserInfo().empty());
	assert (uri.getHost().empty());
	assert (uri.getPort() == 0);
	assert (uri.getPath().empty());
	assert (uri.getQuery().empty());
	assert (uri.getFragment().empty());
	
	uri.setScheme("ftp");
	assert (uri.getScheme() == "ftp");
	assert (uri.getPort() == 21);
	
	uri.setScheme("HTTP");
	assert (uri.getScheme() == "http");
	
	uri.setAuthority("www.appinf.com");
	assert (uri.getAuthority() == "www.appinf.com");
	assert (uri.getPort() == 80);
	
	uri.setAuthority("[email protected]:8000");
	assert (uri.getUserInfo() == "user");
	assert (uri.getHost() == "services.appinf.com");
	assert (uri.getPort() == 8000);
	
	uri.setPath("/index.html");
	assert (uri.getPath() == "/index.html");
	
	uri.setPath("/file%20with%20spaces.html");
	assert (uri.getPath() == "/file with spaces.html");
	
	uri.setPathEtc("/query.cgi?query=foo");
	assert (uri.getPath() == "/query.cgi");
	assert (uri.getQuery() == "query=foo");
	assert (uri.getFragment().empty());
	assert (uri.getPathEtc() == "/query.cgi?query=foo");
	assert (uri.getPathAndQuery() == "/query.cgi?query=foo");
	
	uri.setPathEtc("/query.cgi?query=bar#frag");
	assert (uri.getPath() == "/query.cgi");
	assert (uri.getQuery() == "query=bar");
	assert (uri.getFragment() == "frag");
	assert (uri.getPathEtc() == "/query.cgi?query=bar#frag");
	assert (uri.getPathAndQuery() == "/query.cgi?query=bar");
	
	uri.setQuery("query=test");
	assert (uri.getQuery() == "query=test");
	
	uri.setFragment("result");
	assert (uri.getFragment() == "result");
	
	URI uri2("file", "/home/guenter/foo.bar");
	assert (uri2.getScheme() == "file");
	assert (uri2.getPath() == "/home/guenter/foo.bar");
	
	URI uri3("http", "www.appinf.com", "/index.html");
	assert (uri3.getScheme() == "http");
	assert (uri3.getAuthority() == "www.appinf.com");
	assert (uri3.getPath() == "/index.html");
	
	URI uri4("http", "www.appinf.com:8000", "/index.html");
	assert (uri4.getScheme() == "http");
	assert (uri4.getAuthority() == "www.appinf.com:8000");
	assert (uri4.getPath() == "/index.html");

	URI uri5("http", "[email protected]:8000", "/index.html");
	assert (uri5.getScheme() == "http");
	assert (uri5.getUserInfo() == "user");
	assert (uri5.getHost() == "www.appinf.com");
	assert (uri5.getPort() == 8000);
	assert (uri5.getAuthority() == "[email protected]:8000");
	assert (uri5.getPath() == "/index.html");

	URI uri6("http", "[email protected]:80", "/index.html");
	assert (uri6.getScheme() == "http");
	assert (uri6.getUserInfo() == "user");
	assert (uri6.getHost() == "www.appinf.com");
	assert (uri6.getPort() == 80);
	assert (uri6.getAuthority() == "*****@*****.**");
	assert (uri6.getPath() == "/index.html");

	URI uri7("http", "[email protected]:", "/index.html");
	assert (uri7.getScheme() == "http");
	assert (uri7.getUserInfo() == "user");
	assert (uri7.getHost() == "www.appinf.com");
	assert (uri7.getPort() == 80);
	assert (uri7.getAuthority() == "*****@*****.**");
	assert (uri7.getPath() == "/index.html");
	
	URI uri8("http", "www.appinf.com", "/index.html", "query=test");
	assert (uri8.getScheme() == "http");
	assert (uri8.getAuthority() == "www.appinf.com");
	assert (uri8.getPath() == "/index.html");
	assert (uri8.getQuery() == "query=test");

	URI uri9("http", "www.appinf.com", "/index.html", "query=test", "fragment");
	assert (uri9.getScheme() == "http");
	assert (uri9.getAuthority() == "www.appinf.com");
	assert (uri9.getPath() == "/index.html");
	assert (uri9.getPathEtc() == "/index.html?query=test#fragment");
	assert (uri9.getQuery() == "query=test");
	assert (uri9.getFragment() == "fragment");

	uri9.clear();
	assert (uri9.getScheme().empty());
	assert (uri9.getAuthority().empty());
	assert (uri9.getUserInfo().empty());
	assert (uri9.getHost().empty());
	assert (uri9.getPort() == 0);
	assert (uri9.getPath().empty());
	assert (uri9.getQuery().empty());
	assert (uri9.getFragment().empty());

	URI uri10("ldap", "[2001:db8::7]", "/c=GB?objectClass?one");
	assert (uri10.getScheme() == "ldap");
	assert (uri10.getUserInfo().empty());
	assert (uri10.getHost() == "2001:db8::7");
	assert (uri10.getPort() == 389);
	assert (uri10.getAuthority() == "[2001:db8::7]");
	assert (uri10.getPathEtc() == "/c=GB?objectClass?one");
	
	URI uri11("http", "www.appinf.com", "/index.html?query=test#fragment");
	assert (uri11.getScheme() == "http");
	assert (uri11.getAuthority() == "www.appinf.com");
	assert (uri11.getPath() == "/index.html");
	assert (uri11.getPathEtc() == "/index.html?query=test#fragment");
	assert (uri11.getQuery() == "query=test");
	assert (uri11.getFragment() == "fragment");
}
Ejemplo n.º 8
0
Circuit::Circuit( const URI& source )
  : _impl( newImpl( brion::BlueConfig( source.getPath( ))))
{
}
Ejemplo n.º 9
0
int main( int argc, char*argv[] ) {
   LOG_NOTICE( "Test Started" );

   URI u;

   u.setScheme( "http" );
   u.setAuthority( "www.jetheaddev.com" );
   u.setPath( "pages/index.html" );

   string ustr = u.getString();
   LOG_NOTICE( "URI is: %s", ustr.c_str() );

   for (uint32_t i = 0; i < ARRAY_SIZE( test_urls ); i++) {
      bool res = u.setString( test_urls[i] );

#ifdef DEBUG_PRINTS
      cout << "scheme: " << u.getScheme() << endl;
      cout << "authority: " << u.getAuthority() << endl;
      cout << "host: " << u.getHost() << endl;
      cout << "port: " << u.getPort() << endl;
      cout << "query: " << u.getQuery() << endl;
      cout << "path: " << u.getPath() << endl;
      cout << "fragment: " << u.getFragment() << endl;
      cout << "query param \"c\": " << u.getQueryParam( "c" ) << endl;
      cout << "query param \"e\": " << u.getQueryParam( "e" ) << endl;
      cout << "is relative: " << u.isRelative() << endl;
#endif

      if ( not res ) {
         LOG_WARN( "parse uri %s: FAILED", test_urls[i] );
         exit( 1 );
      } else {
         LOG_NOTICE( "parse uri %s: PASSED", test_urls[ i ] );
      }
   }

   u.clear();
   u.setScheme( "http" );
   u.setAuthority( "www.jetheaddev.com" );
   u.setPath( "pages/index.html" );
   u.appendQueryParam( "a", "b" );
   u.appendQueryParam( "c", "d" );
   u.setFragment( "m" );

   URI copy = u;

   ustr = u.getString();
   LOG_NOTICE( "URI is: %s", ustr.c_str() );
   ustr = copy.getString();
   LOG_NOTICE( "Copy is: %s", ustr.c_str() );

#ifdef DEBUG_PRINTS
   cout << "scheme: " << u.getScheme() << endl;
   cout << "scheme: " << copy.getScheme() << endl;
   cout << "authority: " << u.getAuthority() << endl;
   cout << "authority: " << copy.getAuthority() << endl;
   cout << "host: " << u.getHost() << endl;
   cout << "host: " << copy.getHost() << endl;
   cout << "port: " << u.getPort() << endl;
   cout << "port: " << copy.getPort() << endl;
   cout << "query: " << u.getQuery() << endl;
   cout << "query: " << copy.getQuery() << endl;
   cout << "path: " << u.getPath() << endl;
   cout << "path: " << copy.getPath() << endl;
   cout << "fragment: " << u.getFragment() << endl;
   cout << "fragment: " << copy.getFragment() << endl;
   cout << "query param \"a\": " << u.getQueryParam( "a" ) << endl;
   cout << "query param \"a\": " << copy.getQueryParam( "a" ) << endl;
   cout << "query param \"c\": " << u.getQueryParam( "c" ) << endl;
   cout << "query param \"c\": " << copy.getQueryParam( "c" ) << endl;
   cout << "is relative: " << u.isRelative() << endl;
   cout << "is relative: " << copy.isRelative() << endl;
#endif

   if ( u.getScheme() != copy.getScheme()
         or u.getAuthority() != copy.getAuthority()
         or u.getQuery() != copy.getQuery() or u.getPath() != copy.getPath()
         or u.getFragment() != copy.getFragment()
         or u.getQueryParam( "a" ) != copy.getQueryParam( "a" )
         or u.getQueryParam( "c" ) != copy.getQueryParam( "c" )
         or u.isRelative() != copy.isRelative() ) {
      LOG_WARN( "copy of uri: FAILED" );
   } else {
      LOG_NOTICE( "copy of uri: PASSED" );
   }

   return 0;
}
//------------------------------------------------------------------------------
bool ofxWebServerBaseRouteHandler::matchRoute(const URI& uri, const Settings& settings) {
    return RegularExpression(settings.path).match(uri.getPath());
}
Ejemplo n.º 11
0
// This function will take a resolved URI and create a version of it that is relative to
// another existing URI.  The new URI is stored in the "originalURI"
bool URI::makeRelativeTo ( const URI& relativeToURI, bool ignoreCase)
{
    // Can only do this function if both URIs have the same scheme and authority
    if (mScheme != relativeToURI.mScheme  ||  mAuthority != relativeToURI.mAuthority)
        return false;

    // advance till we find a segment that doesn't match
    WideString thisPathWideSring = StringUtils::utf8String2WideString(getPath());
    WideString relativeToPathWideSring = StringUtils::utf8String2WideString(relativeToURI.getPath());
    const wchar_t *this_path        = thisPathWideSring.c_str();
    const wchar_t *relativeTo_path  = relativeToPathWideSring.c_str();
    const wchar_t *this_slash       = this_path;
    const wchar_t *relativeTo_slash = relativeTo_path;
    /*		const char *this_path        = getPath().c_str();
    		const char *relativeTo_path  = relativeToURI.getPath().c_str();
    		const char *this_slash       = this_path;
    		const char *relativeTo_slash = relativeTo_path;
    */
    while( *this_path )
    {

        if  ( ignoreCase )
        {
            wchar_t characters[3];
            characters[0] = *this_path;
            characters[1] = *relativeTo_path;
            characters[2] = 0;

            boost::to_lower(characters);

            if  ( characters[0] != characters[1] )
                break;
        }
        else
        {
            if (*this_path != *relativeTo_path)
                break;
        }

        if(*this_path == '/')
        {
            this_slash = this_path;
            relativeTo_slash = relativeTo_path;
        }
        this_path++;
        relativeTo_path++;
    }

    // Decide how many ../ segments are needed (Filepath should always end in a /)
    int segment_count = 0;
    relativeTo_slash++;
    while(*relativeTo_slash != 0)
    {
        if(*relativeTo_slash == '/')
            segment_count ++;
        relativeTo_slash++;
    }
    this_slash++;

    String newPath;
    if ( segment_count == 0 )
    {
        newPath = "./";
    }
    else
    {
        for (int i = 0; i < segment_count; i++)
            newPath += "../";
    }
    WideString thisSlashWideString(this_slash);
    newPath += StringUtils::wideString2utf8String(thisSlashWideString);

    set("", "", newPath, mQuery, mFragment, 0/*relativeToURI*/);
    return true;
}
Ejemplo n.º 12
0
void URIReference::attach(const URI &uri) throw(BadURIException)
{
    SPDocument *document = NULL;

    // Attempt to get the document that contains the URI
    if (_owner) {
        document = _owner->document;
    } else if (_owner_document) {
        document = _owner_document;
    }

    // createChildDoc() assumes that the referenced file is an SVG.
    // PNG and JPG files are allowed (in the case of feImage).
    gchar *filename = uri.toString();
    bool skip = false;
    if( g_str_has_suffix( filename, ".jpg" ) ||
        g_str_has_suffix( filename, ".JPG" ) ||
        g_str_has_suffix( filename, ".png" ) ||
        g_str_has_suffix( filename, ".PNG" ) ) {
        skip = true;
    }
 
    // The path contains references to separate document files to load.
    if(document && uri.getPath() && !skip ) {
        std::string base = document->getBase() ? document->getBase() : "";
        std::string path = uri.getFullPath(base);
        if(!path.empty()) {
            document = document->createChildDoc(path);
        } else {
            document = NULL;
        }
    }
    if(!document) {
        g_warning("Can't get document for referenced URI: %s", filename);
        g_free( filename );
        return;
    }
    g_free( filename );

    gchar const *fragment = uri.getFragment();
    if ( !uri.isRelative() || uri.getQuery() || !fragment ) {
        throw UnsupportedURIException();
    }

    /* FIXME !!! real xpointer support should be delegated to document */
    /* for now this handles the minimal xpointer form that SVG 1.0
     * requires of us
     */
    gchar *id = NULL;
    if (!strncmp(fragment, "xpointer(", 9)) {
        /* FIXME !!! this is wasteful */
        /* FIXME: It looks as though this is including "))" in the id.  I suggest moving
           the strlen calculation and validity testing to before strdup, and copying just
           the id without the "))".  -- pjrm */
        if (!strncmp(fragment, "xpointer(id(", 12)) {
            id = g_strdup(fragment+12);
            size_t const len = strlen(id);
            if ( len < 3 || strcmp(id+len-2, "))") ) {
                g_free(id);
                throw MalformedURIException();
            }
        } else {
            throw UnsupportedURIException();
        }
    } else {
        id = g_strdup(fragment);
    }

    /* FIXME !!! validate id as an NCName somewhere */

    _connection.disconnect();
    delete _uri;
    _uri = new URI(uri);

    _setObject(document->getObjectById(id));
    _connection = document->connectIdChanged(id, sigc::mem_fun(*this, &URIReference::_setObject));

    g_free(id);
}
Ejemplo n.º 13
0
bool OAuth2SessionLogin::handlePage(HTTP::WebContext &ctx, ostream &stream,
                                    const URI &uri) {
  HTTP::Connection &con = ctx.getConnection();
  HTTP::Request &request = con.getRequest();
  HTTP::Response &response = con.getResponse();

  ctx.setDynamic(); // Don't cache

  // Force secure
  if (!con.isSecure())
    THROWCS("Cannot logon via insecure port",
            HTTP::StatusCode::HTTP_UNAUTHORIZED);

  // Get session ID
  string sid = request.findCookie(sessionManager->getSessionCookie());
  if (sid.empty() && uri.has("state")) sid = uri.get("state");

  HTTP::SessionPtr session = sessionManager->findSession(ctx, sid);

  try {
    if (session.isNull() ||
        (uri.has("state") && uri.get("state") != session->getID()) ||
        (!uri.has("state") && session->getUser().empty())) {
      session = sessionManager->openSession(ctx);
      sid = session->getID();

      URI redirectURL = auth->getRedirectURL(uri.getPath(), sid);
      response.redirect(redirectURL);

    } else if (session->getUser().empty()) {
      // TODO Make sure session is not very old

      URI postURI = auth->getVerifyURL(uri, sid);
      LOG_DEBUG(5, "Token URI: " << postURI);

      // Extract query data
      string data = postURI.getQuery();
      postURI.setQuery("");

      // Verify authorization with OAuth2 server
      HTTP::Transaction tran(sslCtx);
      tran.post(postURI, data.data(), data.length(),
                "application/x-www-form-urlencoded", 1.0);

      // Read response
      tran.receiveHeader();
      JSON::ValuePtr token = JSON::Reader(tran).parse();

      LOG_DEBUG(5, "Token Response: \n" << tran.getResponse() << *token);

      // Verify token
      string accessToken = auth->verifyToken(token);

      // Get profile
      URI profileURL = auth->getProfileURL(accessToken);
      HTTP::Transaction tran2(sslCtx);
      tran2.get(profileURL);

      // Read response
      tran2.receiveHeader();
      JSON::ValuePtr profile = JSON::Reader(tran2).parse();

      // Process profile
      string email = profile->getString("email");
      if (!profile->getBoolean("email_verified"))
        THROWCS("Email not verified", HTTP::StatusCode::HTTP_UNAUTHORIZED);
      session->setUser(email);
      LOG_INFO(1, "Authorized: " << email);

      // Final redirect to remove auth parameters
      response.redirect(uri.getPath());

    } else return false; // Already authorized

    // Make sure session cookie is set
    sessionManager->setSessionCookie(ctx);

  } catch (...) {
    // Close session on error
    if (!sid.empty()) sessionManager->closeSession(ctx, sid);
    throw;
  }

  return true;
}