Beispiel #1
0
CString WebKitTestServer::getURIForPath(const char* path)
{
    SoupURI* uri = soup_uri_new_with_base(m_baseURI, path);
    GUniquePtr<gchar> uriString(soup_uri_to_string(uri, FALSE));
    soup_uri_free(uri);
    return uriString.get();
}
Beispiel #2
0
static CString soupURIToStringPreservingPassword(SoupURI* soupURI)
{
    if (!soupURI->password) {
        GOwnPtr<char> uriString(soup_uri_to_string(soupURI, FALSE));
        return uriString.get();
    }

    // soup_uri_to_string does not insert the password into the string, so we need to create the
    // URI string and then reinsert any credentials that were present in the SoupURI. All tests that
    // use URL-embedded credentials use HTTP, so it's safe here.
    GOwnPtr<char> password(soupURI->password);
    GOwnPtr<char> user(soupURI->user);
    soupURI->password = 0;
    soupURI->user = 0;

    GOwnPtr<char> uriString(soup_uri_to_string(soupURI, FALSE));
    String absoluteURIWithoutCredentialString = String::fromUTF8(uriString.get());
    String protocolAndCredential = String::format("http://%s:%s@", user ? user.get() : "", password.get());
    return absoluteURIWithoutCredentialString.replace("http://", protocolAndCredential).utf8();
}
void WebSoupRequestManager::send(GTask* task)
{
    WebKitSoupRequestGeneric* request = WEBKIT_SOUP_REQUEST_GENERIC(g_task_get_source_object(task));
    SoupRequest* soupRequest = SOUP_REQUEST(request);
    GUniquePtr<char> uriString(soup_uri_to_string(soup_request_get_uri(soupRequest), FALSE));

    uint64_t requestID = generateSoupRequestID();
    m_requestMap.set(requestID, adoptPtr(new WebSoupRequestAsyncData(task, request)));

    uint64_t initiatingPageID = WebCore::ResourceHandle::getSoupRequestInitiatingPageID(soupRequest);
    m_process->parentProcessConnection()->send(Messages::WebPageProxy::DidReceiveURIRequest(String::fromUTF8(uriString.get()), requestID), initiatingPageID);
}
void WebSoupRequestManager::send(GSimpleAsyncResult* result, GCancellable* cancellable)
{
    GRefPtr<WebKitSoupRequestGeneric> request = adoptGRef(WEBKIT_SOUP_REQUEST_GENERIC(g_async_result_get_source_object(G_ASYNC_RESULT(result))));
    SoupRequest* soupRequest = SOUP_REQUEST(request.get());
    GOwnPtr<char> uriString(soup_uri_to_string(soup_request_get_uri(soupRequest), FALSE));

    uint64_t requestID = generateSoupRequestID();
    m_requestMap.set(requestID, adoptPtr(new WebSoupRequestAsyncData(result, request.get(), cancellable)));

    uint64_t initiatingPageID = WebCore::ResourceHandle::getSoupRequestInitiatingPageID(soupRequest);
    m_process->connection()->send(Messages::WebPageProxy::DidReceiveURIRequest(String::fromUTF8(uriString.get()), requestID), initiatingPageID);
}
Beispiel #5
0
nsresult
ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
                                const nsCString &aTestHost,
                                nsACString &result)
{
  if (mJSNeedsSetup)
    SetupJS();

  if (!mJSRuntime || !mJSRuntime->IsOK())
    return NS_ERROR_NOT_AVAILABLE;

  JSContext *cx = mJSRuntime->Context();
  JSAutoRequest ar(cx);
  JSAutoCompartment ac(cx, mJSRuntime->Global());

  // the sRunning flag keeps a new PAC file from being installed
  // while the event loop is spinning on a DNS function. Don't early return.
  sRunning = this;
  mRunningHost = aTestHost;

  nsresult rv = NS_ERROR_FAILURE;
  JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get()));
  JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));

  if (uriString && hostString) {
    JS::AutoValueArray<2> args(cx);
    args[0].setString(uriString);
    args[1].setString(hostString);

    JS::Rooted<JS::Value> rval(cx);
    bool ok = JS_CallFunctionName(cx, mJSRuntime->Global(),
                                  "FindProxyForURL", args, rval.address());

    if (ok && rval.isString()) {
      nsDependentJSString pacString;
      if (pacString.init(cx, rval.toString())) {
        CopyUTF16toUTF8(pacString, result);
        rv = NS_OK;
      }
    }
  }

  mRunningHost.Truncate();
  sRunning = nullptr;
  return rv;
}
nsresult
ProxyAutoConfig::GetProxyForURI(const nsCString &aTestURI,
                                const nsCString &aTestHost,
                                nsACString &result)
{
  if (mJSNeedsSetup)
    SetupJS();

  if (!mJSRuntime || !mJSRuntime->IsOK())
    return NS_ERROR_NOT_AVAILABLE;

  JSContext *cx = mJSRuntime->Context();
  JSAutoRequest ar(cx);

  // the sRunning flag keeps a new PAC file from being installed
  // while the event loop is spinning on a DNS function. Don't early return.
  sRunning = this;
  mRunningHost = aTestHost;

  nsresult rv = NS_ERROR_FAILURE;
  js::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get()));
  js::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));

  if (uriString && hostString) {
    js::RootedValue uriValue(cx, STRING_TO_JSVAL(uriString));
    js::RootedValue hostValue(cx, STRING_TO_JSVAL(hostString));

    jsval argv[2] = { uriValue, hostValue };
    jsval rval;
    JSBool ok = JS_CallFunctionName(cx, mJSRuntime->Global(),
                                    "FindProxyForURL", 2, argv, &rval);

    if (ok && rval.isString()) {
      nsDependentJSString pacString;
      if (pacString.init(cx, rval.toString())) {
        CopyUTF16toUTF8(pacString, result);
        rv = NS_OK;
      }
    }
  }

  mRunningHost.Truncate();
  sRunning = nullptr;
  return rv;
}
nsresult nsMailboxService::FetchMessage(const char* aMessageURI,
                                        nsISupports * aDisplayConsumer, 
                                        nsIMsgWindow * aMsgWindow,
                                        nsIUrlListener * aUrlListener,
                                        const char * aFileName, /* only used by open attachment... */
                                        nsMailboxAction mailboxAction,
                                        const char * aCharsetOverride,
                                        nsIURI ** aURL)
{
  nsresult rv = NS_OK;
  nsCOMPtr<nsIMailboxUrl> mailboxurl;
  
  nsMailboxAction actionToUse = mailboxAction;
  
  nsCOMPtr <nsIURI> url;

  nsCAutoString uriString(aMessageURI);

  if (!strncmp(aMessageURI, "file:", 5))
  {
    PRInt64 fileSize;
    nsCOMPtr<nsIURI> fileUri;
    rv = NS_NewURI(getter_AddRefs(fileUri), aMessageURI);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFileURL> fileUrl = do_QueryInterface(fileUri, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFile> file;
    rv = fileUrl->GetFile(getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);
    file->GetFileSize(&fileSize);
    nsCAutoString uriString(aMessageURI);
    uriString.ReplaceSubstring(NS_LITERAL_CSTRING("file:"), NS_LITERAL_CSTRING("mailbox:"));
    uriString.Append(NS_LITERAL_CSTRING("&number=0"));
    rv = NS_NewURI(getter_AddRefs(url), uriString);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIMsgMailNewsUrl> msgurl = do_QueryInterface(url);
    if (msgurl)
    {
      msgurl->SetMsgWindow(aMsgWindow);
      nsCOMPtr <nsIMailboxUrl> mailboxUrl = do_QueryInterface(msgurl, &rv);
      mailboxUrl->SetMessageSize((PRUint32) fileSize);
      nsCOMPtr <nsIMsgHeaderSink> headerSink;
       // need to tell the header sink to capture some headers to create a fake db header
       // so we can do reply to a .eml file or a rfc822 msg attachment.
      if (aMsgWindow)
        aMsgWindow->GetMsgHeaderSink(getter_AddRefs(headerSink));
      if (headerSink)
      {
        nsCOMPtr <nsIMsgDBHdr> dummyHeader;
        headerSink->GetDummyMsgHeader(getter_AddRefs(dummyHeader));
        if (dummyHeader)
          dummyHeader->SetMessageSize((PRUint32) fileSize);
      }
    }
  }
  else
  {

    // this happens with forward inline of message/rfc822 attachment
    // opened in a stand-alone msg window.
    PRInt32 typeIndex = typeIndex = uriString.Find("&type=application/x-message-display");
    if (typeIndex != kNotFound)
    {
      uriString.Cut(typeIndex, sizeof("&type=application/x-message-display") - 1);
      rv = NS_NewURI(getter_AddRefs(url), uriString.get());
      mailboxurl = do_QueryInterface(url);
    }
    else
      rv = PrepareMessageUrl(aMessageURI, aUrlListener, actionToUse , getter_AddRefs(mailboxurl), aMsgWindow);
  
    if (NS_SUCCEEDED(rv))
    {
      url = do_QueryInterface(mailboxurl);
      nsCOMPtr<nsIMsgMailNewsUrl> msgUrl (do_QueryInterface(url));
      msgUrl->SetMsgWindow(aMsgWindow);
      nsCOMPtr<nsIMsgI18NUrl> i18nurl (do_QueryInterface(msgUrl));
      i18nurl->SetCharsetOverRide(aCharsetOverride);
      if (aFileName)
        msgUrl->SetFileName(nsDependentCString(aFileName));
    }
  }
    
  // instead of running the mailbox url like we used to, let's try to run the url in the docshell...
  nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(aDisplayConsumer, &rv));
  // if we were given a docShell, run the url in the docshell..otherwise just run it normally.
  if (NS_SUCCEEDED(rv) && docShell)
  {
    nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
    // DIRTY LITTLE HACK --> if we are opening an attachment we want the docshell to
    // treat this load as if it were a user click event. Then the dispatching stuff will be much
    // happier.
    if (mailboxAction == nsIMailboxUrl::ActionFetchPart)
    {
      docShell->CreateLoadInfo(getter_AddRefs(loadInfo));
      loadInfo->SetLoadType(nsIDocShellLoadInfo::loadLink);
    }
    rv = docShell->LoadURI(url, loadInfo, nsIWebNavigation::LOAD_FLAGS_NONE, PR_FALSE);
  }
  else
    rv = RunMailboxUrl(url, aDisplayConsumer); 
 
  if (aURL && mailboxurl)
    mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL);
  
  return rv;
}
/* nsIURI createFixupURI (in nsAUTF8String aURIText, in unsigned long aFixupFlags); */
NS_IMETHODIMP
nsDefaultURIFixup::CreateFixupURI(const nsACString& aStringURI, PRUint32 aFixupFlags, nsIURI **aURI)
{
    NS_ENSURE_ARG(!aStringURI.IsEmpty());
    NS_ENSURE_ARG_POINTER(aURI);

    nsresult rv;
    *aURI = nsnull;

    nsCAutoString uriString(aStringURI);
    uriString.Trim(" ");  // Cleanup the empty spaces that might be on each end.

    // Eliminate embedded newlines, which single-line text fields now allow:
    uriString.StripChars("\r\n");

    NS_ENSURE_TRUE(!uriString.IsEmpty(), NS_ERROR_FAILURE);

    nsCOMPtr<nsIIOService> ioService = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCAutoString scheme;
    ioService->ExtractScheme(aStringURI, scheme);
    
    // View-source is a pseudo scheme. We're interested in fixing up the stuff
    // after it. The easiest way to do that is to call this method again with the
    // "view-source:" lopped off and then prepend it again afterwards.

    if (scheme.LowerCaseEqualsLiteral("view-source"))
    {
        nsCOMPtr<nsIURI> uri;
        PRUint32 newFixupFlags = aFixupFlags & ~FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;

        rv =  CreateFixupURI(Substring(uriString,
                                       sizeof("view-source:") - 1,
                                       uriString.Length() -
                                         (sizeof("view-source:") - 1)),
                             newFixupFlags, getter_AddRefs(uri));
        if (NS_FAILED(rv))
            return NS_ERROR_FAILURE;
        nsCAutoString spec;
        uri->GetSpec(spec);
        uriString.Assign(NS_LITERAL_CSTRING("view-source:") + spec);
    }
    else {
        // Check for if it is a file URL
        FileURIFixup(uriString, aURI);
        if(*aURI)
            return NS_OK;

#if defined(XP_WIN) || defined(XP_OS2)
        // Not a file URL, so translate '\' to '/' for convenience in the common protocols
        // e.g. catch
        //
        //   http:\\broken.com\address
        //   http:\\broken.com/blah
        //   broken.com\blah
        //
        // Code will also do partial fix up the following urls
        //
        //   http:\\broken.com\address/somewhere\image.jpg (stops at first forward slash)
        //   http:\\broken.com\blah?arg=somearg\foo.jpg (stops at question mark)
        //   http:\\broken.com#odd\ref (stops at hash)
        //  
        if (scheme.IsEmpty() ||
            scheme.LowerCaseEqualsLiteral("http") ||
            scheme.LowerCaseEqualsLiteral("https") ||
            scheme.LowerCaseEqualsLiteral("ftp"))
        {
            // Walk the string replacing backslashes with forward slashes until
            // the end is reached, or a question mark, or a hash, or a forward
            // slash. The forward slash test is to stop before trampling over
            // URIs which legitimately contain a mix of both forward and
            // backward slashes.
            nsCAutoString::iterator start;
            nsCAutoString::iterator end;
            uriString.BeginWriting(start);
            uriString.EndWriting(end);
            while (start != end) {
                if (*start == '?' || *start == '#' || *start == '/')
                    break;
                if (*start == '\\')
                    *start = '/';
                ++start;
            }
        }
#endif
    }

    // For these protocols, use system charset instead of the default UTF-8,
    // if the URI is non ASCII.
    PRBool bAsciiURI = IsASCII(uriString);
    PRBool bUseNonDefaultCharsetForURI =
                        !bAsciiURI &&
                        (scheme.IsEmpty() ||
                         scheme.LowerCaseEqualsLiteral("http") ||
                         scheme.LowerCaseEqualsLiteral("https") ||
                         scheme.LowerCaseEqualsLiteral("ftp") ||
                         scheme.LowerCaseEqualsLiteral("file"));

    // Now we need to check whether "scheme" is something we don't
    // really know about.
    nsCOMPtr<nsIProtocolHandler> ourHandler, extHandler;
    
    ioService->GetProtocolHandler(scheme.get(), getter_AddRefs(ourHandler));
    extHandler = do_GetService(NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default");
    
    if (ourHandler != extHandler || !PossiblyHostPortUrl(uriString)) {
        // Just try to create an URL out of it
        rv = NS_NewURI(aURI, uriString,
                       bUseNonDefaultCharsetForURI ? GetCharsetForUrlBar() : nsnull);

        if (!*aURI && rv != NS_ERROR_MALFORMED_URI) {
            return rv;
        }
    }
    
    if (*aURI) {
        if (aFixupFlags & FIXUP_FLAGS_MAKE_ALTERNATE_URI)
            MakeAlternateURI(*aURI);
        return NS_OK;
    }

    // See if it is a keyword
    // Test whether keywords need to be fixed up
    PRBool fixupKeywords = PR_FALSE;
    if (aFixupFlags & FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP) {
        if (mPrefBranch)
        {
            NS_ENSURE_SUCCESS(mPrefBranch->GetBoolPref("keyword.enabled", &fixupKeywords), NS_ERROR_FAILURE);
        }
        if (fixupKeywords)
        {
            KeywordURIFixup(uriString, aURI);
            if(*aURI)
                return NS_OK;
        }
    }

    // Prune duff protocol schemes
    //
    //   ://totallybroken.url.com
    //   //shorthand.url.com
    //
    if (StringBeginsWith(uriString, NS_LITERAL_CSTRING("://")))
    {
        uriString = StringTail(uriString, uriString.Length() - 3);
    }
    else if (StringBeginsWith(uriString, NS_LITERAL_CSTRING("//")))
    {
        uriString = StringTail(uriString, uriString.Length() - 2);
    }

    // Add ftp:// or http:// to front of url if it has no spec
    //
    // Should fix:
    //
    //   no-scheme.com
    //   ftp.no-scheme.com
    //   ftp4.no-scheme.com
    //   no-scheme.com/query?foo=http://www.foo.com
    //
    PRInt32 schemeDelim = uriString.Find("://",0);
    PRInt32 firstDelim = uriString.FindCharInSet("/:");
    if (schemeDelim <= 0 ||
        (firstDelim != -1 && schemeDelim > firstDelim)) {
        // find host name
        PRInt32 hostPos = uriString.FindCharInSet("/:?#");
        if (hostPos == -1) 
            hostPos = uriString.Length();

        // extract host name
        nsCAutoString hostSpec;
        uriString.Left(hostSpec, hostPos);

        // insert url spec corresponding to host name
        if (IsLikelyFTP(hostSpec))
            uriString.Assign(NS_LITERAL_CSTRING("ftp://") + uriString);
        else 
            uriString.Assign(NS_LITERAL_CSTRING("http://") + uriString);

        // For ftp & http, we want to use system charset.
        if (!bAsciiURI)
          bUseNonDefaultCharsetForURI = PR_TRUE;
    } // end if checkprotocol

    rv = NS_NewURI(aURI, uriString, bUseNonDefaultCharsetForURI ? GetCharsetForUrlBar() : nsnull);

    // Did the caller want us to try an alternative URI?
    // If so, attempt to fixup http://foo into http://www.foo.com

    if (*aURI && aFixupFlags & FIXUP_FLAGS_MAKE_ALTERNATE_URI) {
        MakeAlternateURI(*aURI);
    }

    // If we still haven't been able to construct a valid URI, try to force a
    // keyword match.  This catches search strings with '.' or ':' in them.
    if (!*aURI && fixupKeywords)
    {
        KeywordToURI(aStringURI, aURI);
        if(*aURI)
            return NS_OK;
    }

    return rv;
}
Beispiel #9
0
const char * handleHTTPPost(http_conn* conn, int *replyLen) {
	string uriString(conn->uri), retString, incomingData, jsonData, postType;
	incomingData.append(conn->rx_rd_pos, conn->content_length);
	retString = "{\"success\":false}";
	jsonData = getPOSTPayload(incomingData, "json");
	postType = getPOSTPayload(incomingData, "type");
	RestAPI api(&getCurrentFingerprintId);
	if (uriString.compare(0, 6, "/users") == 0) {
		if (postType == "delete"){
			User user;
			user.loadFromJson(jsonData);
			retString = api.deleteUser(user.id);
		} else if (postType == "insert"){
			retString = api.insertUser(jsonData);
		} else if (postType == "enable"){
			retString = api.enableUser(jsonData);
		} else if (postType == "update"){
			retString = api.updateUser(jsonData);
		}
	} else if (uriString.compare(0, 6, "/roles") == 0) {
		if (postType == "delete"){
			Role role;
			role.loadFromJson(jsonData);
			retString = api.deleteRole(role.id);
		} else if (postType == "insert"){
			retString = api.insertRole(jsonData);
		} else if (postType == "update"){
			retString = api.updateRole(jsonData);
		}
	} else if (uriString.compare(0, 14, "/roleSchedules") == 0) {
		if (postType == "delete"){
			RoleSchedule schedule;
			schedule.loadFromJson(jsonData);
			retString = api.deleteRoleSchedule(schedule.id, schedule.rid);
		} else if (postType == "insert"){
			retString = api.insertRoleSchedule(jsonData);
		} else if (postType == "update"){
			retString = api.updateRoleSchedule(jsonData);
		}
	} else if (uriString.compare(0, 9, "/userRole") == 0) {
		if (postType == "delete"){
			UserRole userrole;
			userrole.loadFromJson(jsonData);
			retString = api.deleteUserRole(userrole.id, userrole.uid, userrole.rid);
		} else if (postType == "insert"){
			retString = api.insertUserRole(jsonData);
		} else if (postType == "update"){
			retString = api.updateUserRole(jsonData);
		}
	}else if (uriString.compare(0, 8, "/history") == 0) {
		//retString = api.insertHistory(jsonData);
	} else if (uriString.compare(0, 7, "/prints") == 0) {
		if (postType == "delete"){
			UserPrint print;
			print.loadFromJson(jsonData);
			retString = api.deletePrint(print.id, print.uid);
		} else if (postType == "insert"){
			retString = api.insertPrint(jsonData);
		} else if (postType == "update"){
			retString = api.updatePrint(jsonData);
		}
	} else if (uriString.compare(0, 5, "/time") == 0) {
		if (postType == "update"){
			istringstream reader(jsonData);
			INT32U time;
			reader >> time;
			retString = api.setSystemTime(time);
		}
	}else {
Beispiel #10
0
Lv2Plugin *Lv2PluginCache::getPlugin(const char *uri, const char *preset, Lv2State *state) {
    // create a unique key for uri/preset/state
    std::string keyString(uri);
    if(preset) {
        keyString.append(":");
        keyString.append(preset);
    }
    std::size_t hash = std::hash<std::string>()(keyString);
    if(state) {
        hash = hash ^ (state->getHash() << 1);
    }

    // count tells how many instances of this type of plugin
    int count = ++instanceCount[hash];

    // return cached plugin instance if available
    int key = hash + count;
    Lv2Plugin *cachedPlugin = findObject(key);
    if(cachedPlugin) {
        cachedPlugin->restore();
        return cachedPlugin;
    }

    // look in cache for plugin type by uri
    std::string uriString(uri);
    const LilvPlugin *lilvPlugin = pluginMap[uriString];
    if(!lilvPlugin) {
        // find lv2 plugin in lilv
        LilvNode *lilvUri = lilv_new_uri(world, uri);
        lilvPlugin = lilv_plugins_get_by_uri(plugins, lilvUri);
        lilv_node_free(lilvUri);

        if(!lilvPlugin) {
            throw std::logic_error(std::string("Plugin is not installed on this system: ") + uriString);
        }

        // check that required features are supported
        LilvNodes* features = lilv_plugin_get_required_features(lilvPlugin);
        for (LilvIter* f = lilv_nodes_begin(features); !lilv_nodes_is_end(features, f); f = lilv_nodes_next(features, f)) {
            const char* featureUri = lilv_node_as_uri(lilv_nodes_get(features, f));
            if(!supported[featureUri]) {
                throw std::logic_error(std::string("Plugin ") + uriString + " requires unsupported feature: " + featureUri);
            }
        }
        lilv_nodes_free(features);
        pluginMap[uriString] = lilvPlugin;
    }

    // create worker if required
    Lv2Worker *worker = 0;
    if (lilv_plugin_has_feature(lilvPlugin, lv2Constants.lv2WorkerSchedule)
        && lilv_plugin_has_extension_data(lilvPlugin, lv2Constants.lv2WorkerInterface)) {
        worker = new Lv2Worker();
        ((LV2_Worker_Schedule*)lv2Features[5]->data)->handle = worker;
    }

    // instantiate
    LilvInstance *instance = lilv_plugin_instantiate(lilvPlugin, sampleRate, lv2Features);

    // connect worker with plugin instance
    if(worker) {
        worker->setInstance(instance);
    }

    // create plugin object
    Lv2Plugin *plugin = new Lv2Plugin(lilvPlugin, instance, lv2Constants, worker);

    // restore baseline default state
    LilvState *defaultState =  lilv_state_new_from_world(world, &map, lilv_plugin_get_uri(lilvPlugin));
    lilv_state_restore(defaultState, instance, setPortValue, plugin, 0, lv2Features);

    // find and restore preset
    if(preset) {
        LilvNodes* presets = lilv_plugin_get_related(lilvPlugin, lv2Constants.lv2Presets);
        LilvNode *myPreset = 0;
        LILV_FOREACH(nodes, i, presets) {
            const LilvNode* presetNode = lilv_nodes_get(presets, i);
            lilv_world_load_resource(world, presetNode);
            LilvNodes* labels = lilv_world_find_nodes(world, presetNode, lv2Constants.lv2RdfsLabel, NULL);
            if (labels) {
                const LilvNode* label = lilv_nodes_get_first(labels);
                const char *labelString = lilv_node_as_string(label); // TODO: free?
                if(!strcmp(labelString, preset)) {
                    myPreset = lilv_node_duplicate(presetNode);
                }
                lilv_nodes_free(labels);
            }
        }
        lilv_nodes_free(presets);
        if(myPreset) {
            LilvState* presetState = lilv_state_new_from_world(world, &map, myPreset);
            lilv_state_restore(presetState, instance, setPortValue, plugin, 0, NULL);
            // lilv_state_free(state); // TODO
        }
        else {
            throw std::logic_error(std::string("Plugin ") + uriString + " has no such preset: " + preset);
        }
    }
    // restore state
    else if(state) {    // TODO: what if state is requested on a plugin that doesn't support?