Exemple #1
0
bool StoreClient::addChild(class_id_t parent_class,
                           const URI& parent_uri, 
                           prop_id_t parent_prop,
                           class_id_t child_class,
                           const URI& child_uri) {
    // verify that parent URI and class exists
    store->getRegion(parent_class)->get(parent_uri);

    // verify that the parent property exists for this class
    if (store->prop_map.at(parent_prop)->getId() != parent_class)
        throw std::invalid_argument("Parent class does not contain property");

    // verify that the parent URI is a prefix of child URI
    const std::string& puri = parent_uri.toString();
    const std::string& curi = child_uri.toString();
    if (puri.length() >= curi.length() ||
        0 != curi.compare(0, puri.length(), puri))
        throw std::invalid_argument("Parent URI must be a prefix of child URI");

    // add relationship to child's region.  Note that
    // it's OK if the child URI doesn't exist
    Region* r = checkOwner(store, readOnly, region, child_class);
    return r->addChild(parent_class, parent_uri, parent_prop, 
                       child_class, child_uri);
}
    MetadataRequest(const URI &uri, PriorityType priority) :
        mURI(uri) {
        mPriority = priority;
        mDeletionRequest = false;
        const time_t seconds = time(NULL);
        int random = rand();

        std::stringstream out;
        out<<uri.toString()<<seconds<<random;
        mUniqueID = out.str();
    }
SharedResourcePtr GraphicsResourceManager::getResourceAsset(const URI &id, GraphicsResource::Type resourceType)
{
  WeakResourcePtr curWeakPtr;
  SharedResourcePtr curSharedPtr;
  if (ResourceManager::getSingleton().isMHashScheme(id)) {
    try {
      curWeakPtr = getResource(RemoteFileId(id).fingerprint().convertToHexString());
      curSharedPtr = curWeakPtr.lock();
    } catch (std::invalid_argument &ia) {
    }
  }
  if (!curSharedPtr) {
    curWeakPtr = getResource(id.toString());
    curSharedPtr = curWeakPtr.lock();
  }
  if (curSharedPtr)
    return curSharedPtr;
  else {
    try {
      if (ResourceManager::getSingleton().isMHashScheme(id)) {
        // std::invalid_argument may be thrown, but is caught by the "catch" below.
        RemoteFileId resourceId(id);
        if (resourceType == GraphicsResource::MESH) {
          curSharedPtr = GraphicsResource::construct<GraphicsResourceMesh>(resourceId);
        }
        else if (resourceType == GraphicsResource::MATERIAL) {
          curSharedPtr = GraphicsResource::construct<GraphicsResourceMaterial>(resourceId);
        }
        else if (resourceType == GraphicsResource::TEXTURE) {
          curSharedPtr = GraphicsResource::construct<GraphicsResourceTexture>(resourceId);
        }
        else if (resourceType == GraphicsResource::SHADER) {
          curSharedPtr = GraphicsResource::construct<GraphicsResourceShader>(resourceId);
        }
        else {
          assert(false);
        }
      }
      else {
        curSharedPtr = GraphicsResource::construct<GraphicsResourceName>(id, resourceType);
      }

      mIDResourceMap[curSharedPtr->getID()] = curSharedPtr;
      mResources.insert(curSharedPtr.get());
    }
    catch (std::invalid_argument& exc) {

    }

    return curSharedPtr;
  }
}
Exemple #4
0
bool ShouldBypass(URI& uri, vector<SharedPtr<BypassEntry> >& bypassList)
{
    GetLogger()->Debug("Checking whether %s should be bypassed.",
                       uri.toString().c_str());

    for (size_t i = 0; i < bypassList.size(); i++)
    {
        if (ShouldBypassWithEntry(uri, bypassList.at(i)))
            return true;
    }

    GetLogger()->Debug("No bypass");
    return false;
}
		SharedPtr<Proxy> GetProxyForURLImpl(URI& uri)
		{
			InitializeWin32ProxyConfig();
			std::string url(uri.toString());

			// The auto proxy configuration might tell us to simply use
			// a direct connection, which should cause us to just return
			// null. Otherwise we should try to use the IE proxy list (next block)
			if (useProxyAutoConfig || !autoConfigURL.empty())
			{
				std::vector<SharedProxy> autoProxies;
				bool shouldUseIEProxy = GetAutoProxiesForURL(url, autoProxies);

				for (int i = 0; i < autoProxies.size(); i++)
				{
					SharedProxy proxy = autoProxies.at(i);
					if (proxy->ShouldBypass(uri))
					{
						return 0;
					}
					else if (proxy->info->getScheme().empty() ||
						proxy->info->getScheme() == uri.getScheme())
					{
						return proxy;
					}
				}

				if (!shouldUseIEProxy)
					return 0;
			}

			// Try the IE proxy list
			for (int i = 0; i < ieProxies.size(); i++)
			{
				SharedProxy proxy = ieProxies.at(i);
				std::string proxyScheme = proxy->info->getScheme();
				if (proxy->ShouldBypass(uri))
				{
					return 0;
				}
				else if (proxyScheme.empty() || proxyScheme == uri.getScheme())
				{
					return proxy;
				}
			}

			return 0;
		}
	ChunkRequest(const URI &uri, const RemoteFileMetadata &metadata, const Chunk &chunk,
	        PriorityType priority, ChunkCallback cb)
		: MetadataRequest(uri, priority),
		  mMetadata(std::tr1::shared_ptr<RemoteFileMetadata>(new RemoteFileMetadata(metadata))),
		  mChunk(std::tr1::shared_ptr<Chunk>(new Chunk(chunk))),
		  mCallback(cb) {

	        mDeletionRequest = false;
            const time_t seconds = time(NULL);
            int random = rand();

            std::stringstream out;
            out<<uri.toString()<<seconds<<random;
            mUniqueID = out.str();

	}
void URIStreamOpenerTest::testStreamOpenerFile()
{
	TemporaryFile tempFile;
	std::string path = tempFile.path();
	std::ofstream ostr(path.c_str());
	assert (ostr.good());
	ostr << "Hello, world!" << std::endl;
	ostr.close();
	
	URI uri;
	uri.setScheme("file");
	uri.setPath(Path(path).toString(Path::PATH_UNIX));
	std::string uriString = uri.toString();
	
	URIStreamOpener opener;
	std::istream* istr = opener.open(uri);
	assert (istr != 0);
	assert (istr->good());
	delete istr;
}
Exemple #8
0
ofstatus ofuri_get_str(ofuri_p uri, /* out */ const char** str) {
    ofstatus status = OF_ESUCCESS;
    URI* u = NULL;

    try {
        if (uri == NULL || str == NULL) {
            status = OF_EINVALID_ARG;
            goto done;
        }
        
        u = (URI*)uri;
        *str = u->toString().c_str();

    } catch (...) {
        status = OF_EFAILED;
        goto done;
    }

 done:
    return status;
}
void URIStreamOpenerTest::testStreamOpenerURIResolve()
{
	TemporaryFile tempFile;
	std::string path = tempFile.path();
	std::ofstream ostr(path.c_str());
	assert (ostr.good());
	ostr << "Hello, world!" << std::endl;
	ostr.close();
	
	Path p(path);
	p.makeAbsolute();
	Path parent(p.parent());
	
	URI uri;
	uri.setScheme("file");
	uri.setPath(parent.toString(Path::PATH_UNIX));
	std::string uriString = uri.toString();
	
	URIStreamOpener opener;
	std::istream* istr = opener.open(uriString, p.getFileName());
	assert (istr != 0);
	assert (istr->good());
	delete istr;
}
Exemple #10
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);
}
Exemple #11
0
void authorize(const AuthParams &challenge, AuthParams &authorization,
               const URI &uri, const std::string &method, const std::string &username,
               const std::string &password)
{
    std::string realm, qop, nonce, opaque, algorithm;
    StringMap::const_iterator it;
    if ( (it = challenge.parameters.find("realm")) != challenge.parameters.end()) realm = it->second;
    if ( (it = challenge.parameters.find("qop")) != challenge.parameters.end()) qop = it->second;
    if ( (it = challenge.parameters.find("nonce")) != challenge.parameters.end()) nonce = it->second;
    if ( (it = challenge.parameters.find("opaque")) != challenge.parameters.end()) opaque = it->second;
    if ( (it = challenge.parameters.find("algorithm")) != challenge.parameters.end()) algorithm = it->second;

    if (algorithm.empty())
        algorithm = "MD5";
    StringSet qopValues;
    bool authQop = false;
    // If the server specified a quality of protection (qop), make sure it allows "auth"
    if (!qop.empty()) {
        ListParser parser(qopValues);
        parser.run(qop);
        if (parser.error() || !parser.complete())
            MORDOR_THROW_EXCEPTION(BadMessageHeaderException());
        if (qopValues.find("auth") == qopValues.end())
            MORDOR_THROW_EXCEPTION(InvalidQopException(qop));
        authQop = true;
    }

    // come up with a suitable client nonce
    std::ostringstream os;
    os << std::hex << TimerManager::now();
    std::string cnonce = os.str();
    std::string nc = "00000001";

    // compute A1
    std::string A1;
    if (algorithm == "MD5")
        A1 = username + ':' + realm + ':' + password;
    else if (algorithm == "MD5-sess")
        A1 = md5( username + ':' + realm + ':' + password ) + ':' + nonce + ':' + cnonce;
    else
        MORDOR_THROW_EXCEPTION(InvalidAlgorithmException(algorithm));

    // compute A2 - our qop is always auth or unspecified
    os.str("");
    os << method << ':' << uri;
    std::string A2 = os.str();

    authorization.scheme = "Digest";
    authorization.base64.clear();
    authorization.parameters["username"] = username;
    authorization.parameters["realm"] = realm;
    authorization.parameters["nonce"] = nonce;
    authorization.parameters["uri"] = uri.toString();
    authorization.parameters["algorithm"] = algorithm;

    std::string response;
    if (authQop) {
        qop = "auth";
        response = md5( md5(A1) + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + md5(A2) );
        authorization.parameters["qop"] = qop;
        authorization.parameters["nc"] = nc;
        authorization.parameters["cnonce"] = cnonce;
    } else {
        response = md5( md5(A1) + ':' + nonce + ':' + md5(A2) );

    }
    authorization.parameters["response"] = response;
    if (!opaque.empty())
        authorization.parameters["opaque"] = opaque;
}
Exemple #12
0
bool
SerializeURIIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
  store::Item_t     lItemURI, lItemKey;
  zorba::zstring    lStrValue, lStrKey, lStrRes;
  store::Iterator_t lKeys;
  URI               uri = URI();
  int               lIntPort = 0;
  bool              lHasSchemeField, lHasOpaqueField, lHasNotOpaqueField;

  PlanIteratorState* state;
  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);

  consumeNext(lItemURI, theChildren[0].getp(), planState);

  lHasSchemeField = lHasOpaqueField = lHasNotOpaqueField = false;
  if(lItemURI->isObject()) {
    lKeys = lItemURI->getObjectKeys();
    if(!lKeys.isNull()){
      lKeys->open();
      while(lKeys->next(lItemKey)){
        lStrKey = lItemKey->getStringValue();
        lStrValue = lItemURI->getObjectValue(lItemKey)->getStringValue();
        if(lStrKey == SCHEME_NAME && !lStrValue.empty()){
          uri.set_scheme(lStrValue);
          lHasSchemeField = true;
        } else if(lStrKey == OPAQUE_PART_NAME && !lStrValue.empty()){
          uri.set_opaque_part(lStrValue);
          lHasOpaqueField = true;
        } else if(lStrKey == AUTHORITY_NAME && !lStrValue.empty()){
          uri.set_reg_based_authority(lStrValue);
          lHasNotOpaqueField = true;
        } else if(lStrKey == USER_INFO_NAME && !lStrValue.empty()){
          uri.set_user_info(lStrValue);
          lHasNotOpaqueField = true;
        } else if(lStrKey == HOST_NAME && !lStrValue.empty()){
          uri.set_host(lStrValue);
          lHasNotOpaqueField = true;
        } else if(lStrKey == PORT_NAME){
          sscanf(lStrValue.str().c_str(), "%d", &lIntPort);
          if(lIntPort != 0){
            uri.set_port(lIntPort);
            lHasNotOpaqueField = true;
          }
        } else if(lStrKey == PATH_NAME && !lStrValue.empty()){
          uri.set_path(lStrValue);
          lHasNotOpaqueField = true;
        } else if(lStrKey == QUERY_NAME){
          uri.set_query(lStrValue);
          lHasNotOpaqueField = true;
        } else if(lStrKey == FRAGMENT_NAME){
          uri.set_fragment(lStrValue);
        }
      }
      lKeys->close();
    }
  }

  // check for errors
  if(lHasOpaqueField && lHasNotOpaqueField)
  {
    throw XQUERY_EXCEPTION(
      zuri::OPAQUE_COMB_NOT_VALID,
      ERROR_LOC( loc )
    );
  }
  if(lHasOpaqueField && !lHasSchemeField)
  {
    throw XQUERY_EXCEPTION(
      zuri::OPAQUE_WITHOUT_SCHEME,
      ERROR_LOC( loc )
    );
  }
  if(lHasSchemeField && !uri.get_encoded_path().empty() && (uri.get_encoded_path().substr(0,1) != "/"))
  {
    throw XQUERY_EXCEPTION(
      zuri::INVALID_ABSOLUTE_PATH,
      ERROR_LOC( loc )
    );
  }
  
  lStrRes = zorba::zstring(uri.toString());
  STACK_PUSH(GENV_ITEMFACTORY->createString(result, lStrRes), state );

  STACK_END (state);
}
Exemple #13
0
int main(int argc, char **argv)
{
	int ret = RET_OK;

	try
	{
		Utils utils;
		options opts;
		opts.initOptions();
		opts.parseCommandLine(argc, argv);

		if(opts.empty())
		{
			version.printVersion();
			cout << opts << endl;
		}
		else
		{
			string path, prev_ver, foll_ver;
			bool validateurls, tofile, showhelp, showversion, backup;

			showhelp = opts.getFlagOption(enums::help);
			showversion = opts.getFlagOption(enums::version);
			tofile = !opts.getFlagOption(enums::stdout);
			validateurls = !opts.getFlagOption(enums::not_validate_urls);
			backup = opts.getFlagOption(enums::backup);

			path = opts.getValueOption(enums::file_repo);
			prev_ver = opts.getValueOption(enums::current);
			foll_ver = opts.getValueOption(enums::next);

			if(showhelp)
			{
				cout << opts << endl;
			}
			else if(showversion)
			{
				version.printVersion();
			}
			else
			{
				opts.notify();

				if(validateurls) utils.curlInit();

				if(opts.verbosityLevel() >= enums::verbose)
				{
					cout << "Repository File: " << path << endl;
					cout << "Current version: " << prev_ver << endl;
					cout << "Next version: " << foll_ver << endl;
					cout << "Debug mode: " << (opts.verbosityLevel() == enums::debug ? "On" : "Off") << endl;
					cout << "Print to stdout: " << (tofile ? "No" : "Yes") << endl;
					cout << "Use CURL: " << (validateurls ? "Yes" : "No") << endl;
					cout << "Be Verbose: " << (opts.verbosityLevel() == enums::verbose ? "Yes" : "No") << endl;
				}

				File *repo = new File(path);

				if(repo->isFile() && repo->exists())
				{
					if(opts.verbosityLevel() >= enums::debug)
						cout << "Repository file exists! and has a size of " << repo->getSize() << " b" << endl;

					vector<Repository> *repositories = Repository::getRepositories(repo);

					if(!repositories->empty())
					{
						string repocontent = "";
						int done = 0;

						if(opts.verbosityLevel() >= enums::verbose)
							cout << "Total repositories found: " << repositories->size() << endl;

						if(opts.verbosityLevel() >= enums::verbose && validateurls)
							cout << "New urls has to be verified later!" << endl;

						if(opts.verbosityLevel() >= enums::verbose && validateurls)
							cout << "New urls has to be verified later!" << endl;

						for(int i = 0; i < repositories->size(); i++)
						{
							Repository repository = repositories->at(i);
							repository.setTitle(utils.changeVersionToken(repository.getTitle(), prev_ver, foll_ver));
							repository.setName(utils.changeVersionToken(repository.getName(), prev_ver, foll_ver));
							URI newuri = utils.changeVersionUrl(repository.getBaseurl(), prev_ver, foll_ver);

							if(validateurls)
							{
								if(opts.verbosityLevel() >= enums::verbose)
								{
									cout << "Checking repository '" << repository.getName();
									cout << "' with url '" << repository.getBaseurl().toString() << "'" << endl;
								}

								if(utils.isValid(repository.getBaseurl()))
								{
									if(opts.verbosityLevel() >= enums::verbose)
									{
										cout << "Url seems to be valid, changing to next version and checking again" << endl;
										cout << "Checking new version url '" << newuri.toString() << "'..." << endl;
									}

									if(utils.isValid(newuri))
									{
										if(opts.verbosityLevel() >= enums::verbose)
											cout << "Next version url is valid, so can add the repository" << endl;

										repository.setBaseurl(newuri);
										repocontent = repocontent.append(repository.toString());
										repocontent = repocontent.append("\n").append("\n").append("\n");
										done++;
									}
									else
									{
										if(opts.verbosityLevel() >= enums::verbose)
										{
											cout << "Current version has that repository but, unfortunately,";
											cout << " seems that the new version repository doesn't exists" << endl;
										}
									}
								}
								else
								{
									if(opts.verbosityLevel() >= enums::verbose)
										std::cerr << "Current url seems not to be valid, am I wrong in something?" << endl;
								}
							}
							else
							{
								repository.setBaseurl(newuri);
								repocontent = repocontent.append(repository.toString());
								repocontent = repocontent.append("\n").append("\n").append("\n");
							}
						}

						if(opts.verbosityLevel() >= enums::verbose)
							cout << "Number of repositories that can be written: " << done << endl;

						if(tofile)
						{
							if(!repocontent.empty())
							{
								if(backup)
								{
									string bakpath = path;
									bakpath.append("~");
									repo->renameTo(bakpath);
								}
								else repo->remove();

								delete repo;

								if(opts.verbosityLevel() >= enums::verbose)
									cout << "Writing the new repository file to " << path << endl;

								ofstream newrepo(path.c_str());

								if(opts.verbosityLevel() >= enums::debug)
									cout << "New repo file status: " << newrepo.is_open() << endl;

								if(newrepo.is_open())
								{
									if(opts.verbosityLevel() >= enums::debug)
										cout << "Number of characters of repocontent: " << repocontent.size() << endl;

									newrepo << repocontent << endl;
									newrepo.flush();

									if(opts.verbosityLevel() >= enums::debug)
										cout << "newrepo stream is bad: " << newrepo.bad() << endl;

									newrepo.close();

									if(opts.verbosityLevel() >= enums::verbose)
										cout << "Congratulations! All done, now exiting..." << endl;
								}
								else
								{
									std::cerr << "Unable to open file";
									ret = RET_UNABLE_TO_WRITE;
								}
							}
						}
						else std::cout << repocontent << endl;
					}
					else
					{
						std::cerr << "Repositories file empty or bad repository list" << endl;
						ret = RET_BAD_REPOSITORY_LIST;
					}
				}
				else
				{
					std::cerr << "File doesn't exists or it is not a file" << endl;
					ret = RET_FILE_NOT_FOUND;
				}
			}

			curl_global_cleanup();
		}
	}
	catch(po::error err)
	{
		std::cerr << err.what() << endl;
		ret = RET_BOOST_PARSING_ERROR;
	}
	catch(Poco::FileNotFoundException fnfe)
	{
		std::cerr << fnfe.what() << endl;
		ret = RET_FILE_NOT_FOUND;
	}
	catch(std::bad_exception bex)
	{
		std::cerr << bex.what() << endl;
		ret = RET_EXCEPTION_UNCAUGHT;
	}
	catch(...)
	{
		std::cerr << "Oops! Something wrong, and I don't know why. Sorry." << endl;
		ret = RET_GENERIC_ERROR;
	}

	if(ret > 0) std::cerr << "Exited with return code " << ret << endl;
	else cout << "Exited with return code " << ret << endl;

	return ret;
}
Exemple #14
0
		static Task::IdPair getIdPair(const URI &uploadURI, const char *id) {
			return Task::IdPair(id, uploadURI.toString());
		}
void GraphicsResourceMesh::resolveName(const URI& id, const URI& hash)
{
  mMaterialNames[id.toString()] = CDNArchive::canonicalMhashName(hash.toString());
  if (mLoadState == LOAD_LOADED)
    setMaterialNames(this);
}
Exemple #16
0
bool
NegotiateAuth::authorize(const AuthParams &challenge, AuthParams &authorization,
    const URI &uri)
{
    SECURITY_STATUS status;
    std::wstring packageW = toUtf16(challenge.scheme);
    std::string param = challenge.base64;

    std::string outboundBuffer;
    SecBufferDesc outboundBufferDesc;
    SecBuffer outboundSecBuffer;
    TimeStamp lifetime;
    ULONG contextAttributes;

    outboundBuffer.resize(4096);
    outboundBufferDesc.ulVersion = 0;
    outboundBufferDesc.cBuffers = 1;
    outboundBufferDesc.pBuffers = &outboundSecBuffer;
    outboundSecBuffer.BufferType = SECBUFFER_TOKEN;
    outboundSecBuffer.pvBuffer = &outboundBuffer[0];
    outboundSecBuffer.cbBuffer = (unsigned long)outboundBuffer.size();

    if (param.empty()) {
        // No response from server; we're starting a new session
        if (SecIsValidHandle(&m_creds))
            return false;

        SEC_WINNT_AUTH_IDENTITY_W id;
        id.User = (unsigned short *)m_username.c_str();
        id.UserLength = (unsigned long)m_username.size();
        id.Domain = (unsigned short *)m_domain.c_str();
        id.DomainLength = (unsigned long)m_domain.size();
        id.Password = (unsigned short *)m_password.c_str();
        id.PasswordLength = (unsigned long)m_password.size();
        id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
        status = AcquireCredentialsHandleW(NULL,
            (wchar_t *)packageW.c_str(),
            SECPKG_CRED_OUTBOUND,
            NULL,
            m_username.empty() ? NULL : &id,
            NULL,
            NULL,
            &m_creds,
            &lifetime);
        MORDOR_LOG_TRACE(g_log) << "AcquireCredentialsHandleW("
            << challenge.scheme << ", " << toUtf8(m_username) << "): ("
            << status << ")";
        if (!SUCCEEDED(status))
            MORDOR_THROW_EXCEPTION_FROM_ERROR_API(status, "AcquireCredentialsHandleW");

        status = InitializeSecurityContextW(
            &m_creds,
            NULL,
            (wchar_t *)toUtf16(uri.toString()).c_str(),
            ISC_REQ_CONFIDENTIALITY,
            0,
            SECURITY_NATIVE_DREP,
            NULL,
            0,
            &m_secCtx,
            &outboundBufferDesc,
            &contextAttributes,
            &lifetime);
        MORDOR_LOG_TRACE(g_log) << "InitializeSecurityContextW("
            << uri << ", {0}):  {" << outboundSecBuffer.cbBuffer << "} ("
            << status << ")";
    } else {
        // Prepare the response from the server
        std::string inboundBuffer = base64decode(param);
        SecBufferDesc inboundBufferDesc;
        SecBuffer inboundSecBuffer;

        inboundBufferDesc.ulVersion = 0;
        inboundBufferDesc.cBuffers = 1;
        inboundBufferDesc.pBuffers = &inboundSecBuffer;
        inboundSecBuffer.BufferType = SECBUFFER_TOKEN;
        inboundSecBuffer.pvBuffer = &inboundBuffer[0];
        inboundSecBuffer.cbBuffer = (unsigned long)inboundBuffer.size();

        status = InitializeSecurityContextW(
            &m_creds,
            &m_secCtx,
            (wchar_t *)toUtf16(uri.toString()).c_str(),
            ISC_REQ_CONFIDENTIALITY,
            0,
            SECURITY_NATIVE_DREP,
            &inboundBufferDesc,
            0,
            &m_secCtx,
            &outboundBufferDesc,
            &contextAttributes,
            &lifetime);
        MORDOR_LOG_TRACE(g_log) << "InitializeSecurityContextW("
            << uri << ", {" << inboundSecBuffer.cbBuffer << "}):  {"
            << outboundSecBuffer.cbBuffer << "} (" << status << ")";
    }

    if (status == SEC_I_COMPLETE_NEEDED ||
        status == SEC_I_COMPLETE_AND_CONTINUE) {
        status = CompleteAuthToken(&m_secCtx, &outboundBufferDesc);
        MORDOR_LOG_TRACE(g_log) << "CompleteAuthToken(): {"
            << outboundSecBuffer.cbBuffer << "} (" << status << ")";
    }

    if (!SUCCEEDED(status))
        MORDOR_THROW_EXCEPTION_FROM_ERROR(status);

    outboundBuffer.resize(outboundSecBuffer.cbBuffer);
    authorization.scheme = challenge.scheme;
    authorization.base64 = base64encode(outboundBuffer);
    authorization.parameters.clear();
    return true;
}
	inline std::string toString() const {
		return mURI.toString();
	}
Exemple #18
0
void Connection::makeRequest(Request &req, unsigned method, const URI &uri) {
  evhttp_cmd_type m = convert_method(method);

  if (evhttp_make_request(con, req.adopt(), m, uri.toString().c_str()))
    THROWS("Failed to make request to " << uri);
}
void processOptions(store::Item_t item, store::LoadProperties& props, static_context* theSctx, const QueryLoc& loc)
{
  URI lValidatedBaseUri;
  store::Item_t child, tempItem;

  if (item.getp() == NULL)
    return;

#ifndef ZORBA_NO_XMLSCHEMA
  if (item->isValidated())
  {
    if (item->getNodeName() == NULL
        ||
        item->getNodeName()->getNamespace() != static_context::ZORBA_XML_FN_OPTIONS_NS)
    {
      throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
                             ERROR_PARAMS(ZED(ParseFragmentInvalidOptions)), ERROR_LOC( loc ));
    }
  }
  else
  {
    tempItem = NULL; // used as the effectiveValidationValue()'s typeName
    Validator::effectiveValidationValue(
        item,
        item,
        tempItem,
        theSctx->get_typemanager(),
        ParseConstants::val_strict,
        theSctx,
        loc);
  }
#endif

  store::Iterator_t children = item->getChildren();
  children->open();

  while (children->next(child))
  {
    if (child->getNodeKind() != store::StoreConsts::elementNode)
      continue;

    if (child->getNodeName()->getLocalName() == "base-uri")
    {
      store::Item_t attr = getFirstAttribute(child);

      try {
        lValidatedBaseUri = URI(attr->getStringValue());
      } catch (ZorbaException const& /* e */) {
        throw XQUERY_EXCEPTION(
          err::FODC0007,
          ERROR_PARAMS( attr->getStringValue() ),
          ERROR_LOC( loc )
        );
      }

      if (!lValidatedBaseUri.is_absolute()) {
        throw XQUERY_EXCEPTION(
          err::FODC0007,
          ERROR_PARAMS( lValidatedBaseUri.toString() ),
          ERROR_LOC( loc )
        );
      }

      props.setBaseUri(attr->getStringValue());
    }
    else if (child->getNodeName()->getLocalName() == "no-error")
      props.setNoError(true);
    else if (child->getNodeName()->getLocalName() == "strip-boundary-space")
      props.setStripWhitespace(true);
    else if (child->getNodeName()->getLocalName() == "schema-validate")
    {
      store::Item_t attr = getFirstAttribute(child);
      if (attr->getStringValue() == "strict")
        props.setSchemaStrictValidate(true);
      else
        props.setSchemaLaxValidate(true);
    }
    else if (child->getNodeName()->getLocalName() == "DTD-validate")
      props.setDTDValidate(true);
    else if (child->getNodeName()->getLocalName() == "DTD-load")
      props.setDTDLoad(true);
    else if (child->getNodeName()->getLocalName() == "default-DTD-attributes")
      props.setDefaultDTDAttributes(true);
    else if (child->getNodeName()->getLocalName() == "parse-external-parsed-entity")
    {
      props.setParseExternalParsedEntity(true);
      store::Item_t attr;
      store::Iterator_t attribs = child->getAttributes();
      attribs->open();
      while (attribs->next(attr))
      {
        if (attr->getNodeName()->getLocalName() == "skip-root-nodes")
          props.setSkipRootNodes(ztd::aton<xs_int>(attr->getStringValue().c_str()));
        else if (attr->getNodeName()->getLocalName() == "skip-top-level-text-nodes")
          props.setSkipTopLevelTextNodes(true);
        else if (attr->getNodeName()->getLocalName() == "error-on-doctype")
          props.setErrorOnDoctype(true);
      }
      attribs->close();
    }
    else if (child->getNodeName()->getLocalName() == "substitute-entities")
      props.setSubstituteEntities(true);
    else if (child->getNodeName()->getLocalName() == "xinclude-substitutions")
      props.setXincludeSubstitutions(true);
    else if (child->getNodeName()->getLocalName() == "remove-redundant-ns")
      props.setRemoveRedundantNS(true);
    else if (child->getNodeName()->getLocalName() == "no-CDATA")
      props.setNoCDATA(true);
    else if (child->getNodeName()->getLocalName() == "no-xinclude-nodes")
      props.setNoXIncludeNodes(true);
    else if (child->getNodeName()->getLocalName() == "no-network-access")
      props.setNoNetworkAccess(true);
  }

  children->close();

  if (props.getSchemaLaxValidate() + props.getSchemaStrictValidate() +
      props.getDTDValidate() + props.getParseExternalParsedEntity() > 1)
  {
    throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
                           ERROR_PARAMS(ZED(ParseFragmentOptionCombinationNotAllowed)), ERROR_LOC( loc ));
  }
}
Exemple #20
0
 MetadataRequest(const URI &uri, PriorityType priority, MetadataCallback cb) :
  mURI(uri), mCallback(cb) {
     mPriority = priority;
     mDeletionRequest = false;
     mID = uri.toString();
 }
Exemple #21
0
 URIBuilderImpl(const URI& uri) { 
     uri_stream.fill('0');
     uri_stream << uri.toString();
 }