/**
 * Create or find already existing application info for specified command
 * and application name.
 * @param cmd command to execute
 * @param appName application name
 * @param appInfo location where created GAppInfo is stored
 * @return NS_OK when object is created, NS_ERROR_FAILURE otherwise.
 */
NS_IMETHODIMP
nsGIOService::CreateAppFromCommand(nsACString const& cmd,
                                   nsACString const& appName,
                                   nsIGIOMimeApp**   appInfo)
{
  GError *error = NULL;
  *appInfo = nsnull;

  GAppInfo *app_info = NULL, *app_info_from_list = NULL;
  GList *apps = g_app_info_get_all();
  GList *apps_p = apps;
  get_commandline_t g_app_info_get_commandline_ptr;

  void *libHandle = dlopen("libgio-2.0.so", RTLD_LAZY);
  if (!libHandle) {
    return NS_ERROR_FAILURE;
  }
  dlerror(); /* clear any existing error */
  g_app_info_get_commandline_ptr =
    (get_commandline_t) dlsym(libHandle, "g_app_info_get_commandline");
  if (dlerror() != NULL) {
    g_app_info_get_commandline_ptr = NULL;
  }

  // Try to find relevant and existing GAppInfo in all installed application
  while (apps_p) {
    app_info_from_list = (GAppInfo*) apps_p->data;
    /* This is  a silly test. It just compares app names but not
     * commands. This is due to old version of Glib/Gio. The required
     * function which allows to do a regular check of existence of desktop file
     * is possible by using function g_app_info_get_commandline. This function
     * has been introduced in Glib 2.20. */
    if (app_info_from_list && strcmp(g_app_info_get_name(app_info_from_list),
                                     PromiseFlatCString(appName).get()) == 0 )
    {
      if (g_app_info_get_commandline_ptr)
      {
        /* Following test is only possible with Glib >= 2.20.
         * Compare path only by using strncmp */
        if (strncmp(g_app_info_get_commandline_ptr(app_info_from_list),
                    PromiseFlatCString(cmd).get(),
                    strlen(PromiseFlatCString(cmd).get())) == 0)
        {
          app_info = app_info_from_list;
          break;
        } else {
          g_object_unref(app_info_from_list);
        }
      } else {
        app_info = app_info_from_list;
        break;
      }
    } else {
      g_object_unref(app_info_from_list);
    }
    apps_p = apps_p->next;
  }
  g_list_free(apps);

  if (!app_info) {
    app_info = g_app_info_create_from_commandline(PromiseFlatCString(cmd).get(),
                                                  PromiseFlatCString(appName).get(),
                                                  G_APP_INFO_CREATE_SUPPORTS_URIS,
                                                  &error);
  }

  if (!app_info) {
    g_warning("Cannot create application info from command: %s", error->message);
    g_error_free(error);
    dlclose(libHandle);
    return NS_ERROR_FAILURE;
  }
  nsGIOMimeApp *mozApp = new nsGIOMimeApp(app_info);
  NS_ENSURE_TRUE(mozApp, NS_ERROR_OUT_OF_MEMORY);
  NS_ADDREF(*appInfo = mozApp);
  dlclose(libHandle);
  return NS_OK;
}
void
nsUrlClassifierUtils::ParseIPAddress(const nsACString & host,
                                     nsACString & _retval)
{
  _retval.Truncate();
  nsACString::const_iterator iter, end;
  host.BeginReading(iter);
  host.EndReading(end);

  if (host.Length() <= 15) {
    // The Windows resolver allows a 4-part dotted decimal IP address to
    // have a space followed by any old rubbish, so long as the total length
    // of the string doesn't get above 15 characters. So, "10.192.95.89 xy"
    // is resolved to 10.192.95.89.
    // If the string length is greater than 15 characters, e.g.
    // "10.192.95.89 xy.wildcard.example.com", it will be resolved through
    // DNS.

    if (FindCharInReadable(' ', iter, end)) {
      end = iter;
    }
  }

  for (host.BeginReading(iter); iter != end; iter++) {
    if (!(isxdigit(*iter) || *iter == 'x' || *iter == 'X' || *iter == '.')) {
      // not an IP
      return;
    }
  }

  host.BeginReading(iter);
  nsTArray<nsCString> parts;
  ParseString(PromiseFlatCString(Substring(iter, end)), '.', parts);
  if (parts.Length() > 4) {
    return;
  }

  // If any potentially-octal numbers (start with 0 but not hex) have
  // non-octal digits, no part of the ip can be in octal
  // XXX: this came from the old javascript implementation, is it really
  // supposed to be like this?
  bool allowOctal = true;
  uint32_t i;

  for (i = 0; i < parts.Length(); i++) {
    const nsCString& part = parts[i];
    if (part[0] == '0') {
      for (uint32_t j = 1; j < part.Length(); j++) {
        if (part[j] == 'x') {
          break;
        }
        if (part[j] == '8' || part[j] == '9') {
          allowOctal = false;
          break;
        }
      }
    }
  }

  for (i = 0; i < parts.Length(); i++) {
    nsAutoCString canonical;

    if (i == parts.Length() - 1) {
      CanonicalNum(parts[i], 5 - parts.Length(), allowOctal, canonical);
    } else {
      CanonicalNum(parts[i], 1, allowOctal, canonical);
    }

    if (canonical.IsEmpty()) {
      _retval.Truncate();
      return;
    }

    if (_retval.IsEmpty()) {
      _retval.Assign(canonical);
    } else {
      _retval.Append('.');
      _retval.Append(canonical);
    }
  }
  return;
}
// wrapper for ldap_simple_bind()
//
NS_IMETHODIMP
nsLDAPOperation::SimpleBind(const nsACString& passwd)
{
    nsRefPtr<nsLDAPConnection> connection = mConnection;
    // There is a possibilty that mConnection can be cleared by another
    // thread. Grabbing a local reference to mConnection may avoid this.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=557928#c1
    nsresult rv;
    nsAutoCString bindName;
    int32_t originalMsgID = mMsgID;
    // Ugly hack alert:
    // the first time we get called with a passwd, remember it.
    // Then, if we get called again w/o a password, use the
    // saved one. Getting called again means we're trying to
    // fall back to VERSION2.
    // Since LDAP operations are thrown away when done, it won't stay
    // around in memory.
    if (!passwd.IsEmpty())
      mSavePassword = passwd;

    NS_PRECONDITION(mMessageListener != 0, "MessageListener not set");

    rv = connection->GetBindName(bindName);
    if (NS_FAILED(rv))
        return rv;

    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG,
           ("nsLDAPOperation::SimpleBind(): called; bindName = '%s'; ",
            bindName.get()));

    // If this is a second try at binding, remove the operation from pending ops
    // because msg id has changed...
    if (originalMsgID)
      connection->RemovePendingOperation(originalMsgID);

    mMsgID = ldap_simple_bind(mConnectionHandle, bindName.get(),
                              PromiseFlatCString(mSavePassword).get());

    if (mMsgID == -1) {
      // XXX Should NS_ERROR_LDAP_SERVER_DOWN cause a rebind here?
      return TranslateLDAPErrorToNSError(ldap_get_lderrno(mConnectionHandle,
                                                          0, 0));
    }

    // make sure the connection knows where to call back once the messages
    // for this operation start coming in
    rv = connection->AddPendingOperation(mMsgID, this);
    switch (rv) {
    case NS_OK:
        break;

        // note that the return value of ldap_abandon_ext() is ignored, as
        // there's nothing useful to do with it

    case NS_ERROR_OUT_OF_MEMORY:
        (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
        return NS_ERROR_OUT_OF_MEMORY;
        break;

    case NS_ERROR_UNEXPECTED:
    case NS_ERROR_ILLEGAL_VALUE:
    default:
        (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
        return NS_ERROR_UNEXPECTED;
    }

    return NS_OK;
}
NS_IMETHODIMP
nsLDAPOperation::SearchExt(const nsACString& aBaseDn, int32_t aScope,
                           const nsACString& aFilter,
                           const nsACString &aAttributes,
                           PRIntervalTime aTimeOut, int32_t aSizeLimit)
{
    if (!mMessageListener) {
        NS_ERROR("nsLDAPOperation::SearchExt(): mMessageListener not set");
        return NS_ERROR_NOT_INITIALIZED;
    }

    // XXX add control logging
    PR_LOG(gLDAPLogModule, PR_LOG_DEBUG,
           ("nsLDAPOperation::SearchExt(): called with aBaseDn = '%s'; "
            "aFilter = '%s'; aAttributes = %s; aSizeLimit = %d",
            PromiseFlatCString(aBaseDn).get(),
            PromiseFlatCString(aFilter).get(),
            PromiseFlatCString(aAttributes).get(), aSizeLimit));

    LDAPControl **serverctls = 0;
    nsresult rv;
    if (mServerControls) {
        rv = convertControlArray(mServerControls, &serverctls);
        if (NS_FAILED(rv)) {
            PR_LOG(gLDAPLogModule, PR_LOG_ERROR,
                   ("nsLDAPOperation::SearchExt(): error converting server "
                    "control array: %x", rv));
            return rv;
        }
    }

    LDAPControl **clientctls = 0;
    if (mClientControls) {
        rv = convertControlArray(mClientControls, &clientctls);
        if (NS_FAILED(rv)) {
            PR_LOG(gLDAPLogModule, PR_LOG_ERROR,
                   ("nsLDAPOperation::SearchExt(): error converting client "
                    "control array: %x", rv));
            ldap_controls_free(serverctls);
            return rv;
        }
    }

    // Convert our comma separated string to one that the C-SDK will like, i.e.
    // convert to a char array and add a last NULL element.
    nsTArray<nsCString> attrArray;
    ParseString(aAttributes, ',', attrArray);
    char **attrs = nullptr;
    uint32_t origLength = attrArray.Length();
    if (origLength)
    {
      attrs = static_cast<char **> (NS_Alloc((origLength + 1) * sizeof(char *)));
      if (!attrs)
        return NS_ERROR_OUT_OF_MEMORY;

      for (uint32_t i = 0; i < origLength; ++i)
        attrs[i] = ToNewCString(attrArray[i]);

      attrs[origLength] = 0;
    }

    // XXX deal with timeout here
    int retVal = ldap_search_ext(mConnectionHandle,
                                 PromiseFlatCString(aBaseDn).get(),
                                 aScope, PromiseFlatCString(aFilter).get(),
                                 attrs, 0, serverctls, clientctls, 0,
                                 aSizeLimit, &mMsgID);

    // clean up
    ldap_controls_free(serverctls);
    ldap_controls_free(clientctls);
    // The last entry is null, so no need to free that.
    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(origLength, attrs);

    rv = TranslateLDAPErrorToNSError(retVal);
    NS_ENSURE_SUCCESS(rv, rv);

    // make sure the connection knows where to call back once the messages
    // for this operation start coming in
    //
    rv = mConnection->AddPendingOperation(mMsgID, this);
    if (NS_FAILED(rv)) {
        switch (rv) {
        case NS_ERROR_OUT_OF_MEMORY:
            (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
            return NS_ERROR_OUT_OF_MEMORY;

        default:
            (void)ldap_abandon_ext(mConnectionHandle, mMsgID, 0, 0);
            NS_ERROR("nsLDAPOperation::SearchExt(): unexpected error in "
                     "mConnection->AddPendingOperation");
            return NS_ERROR_UNEXPECTED;
        }
    }

    return NS_OK;
}
inline void nsCollationUnix::DoRestoreLocale()
{
  if (!mSavedLocale.EqualsIgnoreCase(mLocale.get())) { 
    (void) setlocale(LC_COLLATE, PromiseFlatCString(Substring(mSavedLocale,0,MAX_LOCALE_LEN)).get());
  }
}
Beispiel #6
0
RefPtr<NrIceCtx> NrIceCtx::Create(const std::string& name,
                                  bool offerer,
                                  bool allow_loopback,
                                  bool tcp_enabled,
                                  bool allow_link_local,
                                  bool hide_non_default,
                                  Policy policy) {
   RefPtr<NrIceCtx> ctx = new NrIceCtx(name, offerer, policy);

  // Initialize the crypto callbacks and logging stuff
  if (!initialized) {
    NR_reg_init(NR_REG_MODE_LOCAL);
    nr_crypto_vtbl = &nr_ice_crypto_nss_vtbl;
    initialized = true;

    // Set the priorites for candidate type preferences.
    // These numbers come from RFC 5245 S. 4.1.2.2
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX, 100);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX, 110);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST, 126);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED, 5);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX_TCP, 99);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX_TCP, 109);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST_TCP, 125);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED_TCP, 0);

    int32_t stun_client_maximum_transmits = 7;
    int32_t ice_trickle_grace_period = 5000;
    int32_t ice_tcp_so_sock_count = 3;
    int32_t ice_tcp_listen_backlog = 10;
    nsAutoCString force_net_interface;
#ifndef MOZILLA_XPCOMRT_API
    nsresult res;
    nsCOMPtr<nsIPrefService> prefs =
      do_GetService("@mozilla.org/preferences-service;1", &res);

    if (NS_SUCCEEDED(res)) {
      nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(prefs);
      if (branch) {
        branch->GetIntPref(
            "media.peerconnection.ice.stun_client_maximum_transmits",
            &stun_client_maximum_transmits);
        branch->GetIntPref(
            "media.peerconnection.ice.trickle_grace_period",
            &ice_trickle_grace_period);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_so_sock_count",
            &ice_tcp_so_sock_count);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_listen_backlog",
            &ice_tcp_listen_backlog);
        branch->GetCharPref(
            "media.peerconnection.ice.force_interface",
            getter_Copies(force_net_interface));
      }
    }
#endif
    NR_reg_set_uint4((char *)"stun.client.maximum_transmits",
                     stun_client_maximum_transmits);
    NR_reg_set_uint4((char *)NR_ICE_REG_TRICKLE_GRACE_PERIOD,
                     ice_trickle_grace_period);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_SO_SOCK_COUNT,
                     ice_tcp_so_sock_count);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_LISTEN_BACKLOG,
                     ice_tcp_listen_backlog);

    NR_reg_set_char((char *)NR_ICE_REG_ICE_TCP_DISABLE, !tcp_enabled);

    if (allow_loopback) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LOOPBACK_ADDRS, 1);
    }

    if (allow_link_local) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LINK_LOCAL_ADDRS, 1);
    }
    if (force_net_interface.Length() > 0) {
      // Stupid cast.... but needed
      const nsCString& flat = PromiseFlatCString(static_cast<nsACString&>(force_net_interface));
      NR_reg_set_string((char *)NR_ICE_REG_PREF_FORCE_INTERFACE_NAME, const_cast<char*>(flat.get()));
    }
  }

  // Create the ICE context
  int r;

  UINT4 flags = offerer ? NR_ICE_CTX_FLAGS_OFFERER:
      NR_ICE_CTX_FLAGS_ANSWERER;
  flags |= NR_ICE_CTX_FLAGS_AGGRESSIVE_NOMINATION;
  if (policy == ICE_POLICY_RELAY) {
    flags |= NR_ICE_CTX_FLAGS_RELAY_ONLY;
  }

  if (hide_non_default)
    flags |= NR_ICE_CTX_FLAGS_ONLY_DEFAULT_ADDRS;

  r = nr_ice_ctx_create(const_cast<char *>(name.c_str()), flags,
                        &ctx->ctx_);
  if (r) {
    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE ctx for '" << name << "'");
    return nullptr;
  }

  nr_interface_prioritizer *prioritizer = CreateInterfacePrioritizer();
  if (!prioritizer) {
    MOZ_MTLOG(LogLevel::Error, "Couldn't create interface prioritizer.");
    return nullptr;
  }

  r = nr_ice_ctx_set_interface_prioritizer(ctx->ctx_, prioritizer);
  if (r) {
    MOZ_MTLOG(LogLevel::Error, "Couldn't set interface prioritizer.");
    return nullptr;
  }

  if (ctx->generating_trickle()) {
    r = nr_ice_ctx_set_trickle_cb(ctx->ctx_, &NrIceCtx::trickle_cb, ctx);
    if (r) {
      MOZ_MTLOG(ML_ERROR, "Couldn't set trickle cb for '" << name << "'");
      return nullptr;
    }
  }

  // Create the handler objects
  ctx->ice_handler_vtbl_ = new nr_ice_handler_vtbl();
  ctx->ice_handler_vtbl_->select_pair = &NrIceCtx::select_pair;
  ctx->ice_handler_vtbl_->stream_ready = &NrIceCtx::stream_ready;
  ctx->ice_handler_vtbl_->stream_failed = &NrIceCtx::stream_failed;
  ctx->ice_handler_vtbl_->ice_completed = &NrIceCtx::ice_completed;
  ctx->ice_handler_vtbl_->msg_recvd = &NrIceCtx::msg_recvd;
  ctx->ice_handler_vtbl_->ice_checking = &NrIceCtx::ice_checking;

  ctx->ice_handler_ = new nr_ice_handler();
  ctx->ice_handler_->vtbl = ctx->ice_handler_vtbl_;
  ctx->ice_handler_->obj = ctx;

  // Create the peer ctx. Because we do not support parallel forking, we
  // only have one peer ctx.
  std::string peer_name = name + ":default";
  r = nr_ice_peer_ctx_create(ctx->ctx_, ctx->ice_handler_,
                             const_cast<char *>(peer_name.c_str()),
                             &ctx->peer_);
  if (r) {
    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE peer ctx for '" << name << "'");
    return nullptr;
  }

  nsresult rv;
  ctx->sts_target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);

  if (!NS_SUCCEEDED(rv))
    return nullptr;

  return ctx;
}
/**
 * The Xalan testcases app
 */
int main(int argc, char** argv)
{
#ifdef NS_TRACE_MALLOC
    NS_TraceMallocStartupArgs(argc, argv);
#endif
#ifdef MOZ_JPROF
    setupProfilingStuff();
#endif
    char* xalan = PR_GetEnv("XALAN_DIR");
    if (!xalan) {
        printHelp();
        return 1;
    }
    nsresult rv;
    rv = NS_InitXPCOM2(nsnull, nsnull, nsnull);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIFile> conf, gold, resFile;
    rv = setupXalan(xalan, getter_AddRefs(conf), getter_AddRefs(gold),
                    getter_AddRefs(resFile));
    if (NS_FAILED(rv)) {
        NS_ShutdownXPCOM(nsnull);
        printHelp();
        return -1;
    }

    //-- handle output stream
    ostream* resultOutput = &cout;
    ofstream resultFileStream;

    int argn = 1;
    // skip -- gnu style options
    while (argn < argc) {
        nsDependentCString opt(argv[argn]);
        if (!Substring(opt, 0, 2).EqualsLiteral("--")) {
            break;
        }
        ++argn;
    }
    if (argn < argc) {
        nsDependentCString opt(argv[argn]);
        if (Substring(opt, 0, 2).EqualsLiteral("-o")) {
            if (opt.Length() > 2) {
                const nsAFlatCString& fname = 
                    PromiseFlatCString(Substring(opt, 2, opt.Length()-2));
                resultFileStream.open(fname.get(), ios::out);
            }
            else {
                ++argn;
                if (argn < argc) {
                    resultFileStream.open(argv[argn], ios::out);
                }
            }
            if (!resultFileStream) {
                cerr << "error opening output file" << endl;
                PRBool exists;
                if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
                    resFile->Remove(PR_FALSE);
                NS_ShutdownXPCOM(nsnull);
                return -1;
            }
            ++argn;
            resultOutput = &resultFileStream;
        }
    }

    if (!txXSLTProcessor::init()) {
        PRBool exists;
        if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
            resFile->Remove(PR_FALSE);
        NS_ShutdownXPCOM(nsnull);
        return 1;
    }

    *resultOutput << "<?xml version=\"1.0\"?>\n" << 
        "<RDF:RDF xmlns:NC=\"http://home.netscape.com/NC-rdf#\"\n" <<
        "         xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" << endl;

    txRDFOut* rdfOut = new txRDFOut(resultOutput);
    nsCOMPtr<nsIFile> tempFile;
    if (argn < argc) {
        // categories are specified
        while (argn < argc) {
            nsDependentCString cat(argv[argn++]);
            rv = conf->AppendNative(cat);
            if (NS_SUCCEEDED(rv)) {
                rv = gold->AppendNative(cat);
                if (NS_SUCCEEDED(rv)) {
                    runCategory(conf, gold, resFile, rdfOut);
                    rv = gold->GetParent(getter_AddRefs(tempFile));
                    NS_ASSERTION(NS_SUCCEEDED(rv), "can't go back?");
                    gold = tempFile;
                }
                rv = conf->GetParent(getter_AddRefs(tempFile));
                NS_ASSERTION(NS_SUCCEEDED(rv), "can't go back?");
                conf = tempFile;
            }
        }
    }
    else {
        // no category specified, do everything
        nsCOMPtr<nsISimpleEnumerator> cats;
        rv = conf->GetDirectoryEntries(getter_AddRefs(cats));
        PRBool hasMore, isDir;
        nsCAutoString leaf;
        while (NS_SUCCEEDED(cats->HasMoreElements(&hasMore)) && hasMore) {
            nsCOMPtr<nsILocalFile> cat;
            cats->GetNext(getter_AddRefs(cat));
            rv = cat->IsDirectory(&isDir);
            if (NS_SUCCEEDED(rv) && isDir) {
                rv = cat->GetNativeLeafName(leaf);
                if (NS_SUCCEEDED(rv) && 
                    !leaf.EqualsLiteral("CVS")) {
                    rv = gold->AppendNative(leaf);
                    if (NS_SUCCEEDED(rv)) {
                        runCategory(cat, gold, resFile, rdfOut);
                        rv = gold->GetParent(getter_AddRefs(tempFile));
                        gold = tempFile;
                    }
                }
            }
        }
    }
    delete rdfOut;
    rdfOut = nsnull;
    *resultOutput << "</RDF:RDF>" << endl;
    PRBool exists;
    if (NS_SUCCEEDED(resFile->Exists(&exists)) && exists)
        resFile->Remove(PR_FALSE);
    resultFileStream.close();
    txXSLTProcessor::shutdown();
    rv = NS_ShutdownXPCOM(nsnull);
#ifdef NS_TRACE_MALLOC
    NS_TraceMallocShutdown();
#endif
    NS_ENSURE_SUCCESS(rv, rv);
    return 0;
}
Beispiel #8
0
PLDHashOperator
nsCEnum(const nsACString& aKey, nsAutoPtr<TestUniChar>& aData, void* userArg) {
    printf("  enumerated \"%s\" = %c\n", 
           PromiseFlatCString(aKey).get(), aData->GetChar());
  return PL_DHASH_NEXT;
}
nsresult
nsUnixSystemProxySettings::GetProxyForURI(nsIURI* aURI, nsACString& aResult)
{
  nsresult rv;

  if (!mProxyFactory) {
    mProxyFactory = px_proxy_factory_new();
  }
  NS_ENSURE_TRUE(mProxyFactory, NS_ERROR_NOT_AVAILABLE);

  nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString spec;
  rv = aURI->GetSpec(spec);
  NS_ENSURE_SUCCESS(rv, rv);

  char **proxyArray = nsnull;
  proxyArray = px_proxy_factory_get_proxies(mProxyFactory, (char*)(spec.get()));
  NS_ENSURE_TRUE(proxyArray, NS_ERROR_NOT_AVAILABLE);

  // Translate libproxy's output to PAC string as expected
  // libproxy returns an array of proxies in the format:
  // <procotol>://[username:password@]proxy:port
  // or
  // direct://
  //
  // PAC format: "PROXY proxy1.foo.com:8080; PROXY proxy2.foo.com:8080; DIRECT"
  int c = 0;
  while (proxyArray[c] != NULL) {
    if (!aResult.IsEmpty()) {
      aResult.AppendLiteral("; ");
    }

    bool isScheme = false;
    nsXPIDLCString schemeString;
    nsXPIDLCString hostPortString;
    nsCOMPtr<nsIURI> proxyURI;

    rv = ios->NewURI(nsDependentCString(proxyArray[c]),
                                        nsnull,
                                        nsnull,
                                        getter_AddRefs(proxyURI));
    if (NS_FAILED(rv)) {
      c++;
      continue;
    }

    proxyURI->GetScheme(schemeString);
    if (NS_SUCCEEDED(proxyURI->SchemeIs("http", &isScheme)) && isScheme) {
      schemeString.AssignLiteral("proxy");
    }
    aResult.Append(schemeString);
    if (NS_SUCCEEDED(proxyURI->SchemeIs("direct", &isScheme)) && !isScheme) {
      // Add the proxy URI only if it's not DIRECT
      proxyURI->GetHostPort(hostPortString);
      aResult.AppendLiteral(" ");
      aResult.Append(hostPortString);
    }

    c++;
  }

#ifdef DEBUG
  printf("returned PAC proxy string: %s\n", PromiseFlatCString(aResult).get());
#endif

  PR_Free(proxyArray);
  return NS_OK;
}
/*
 * This will consume+delete updates from the passed nsTArray.
*/
nsresult
Classifier::ApplyTableUpdates(nsTArray<TableUpdate*>* aUpdates,
                              const nsACString& aTable)
{
  LOG(("Classifier::ApplyTableUpdates(%s)",
       PromiseFlatCString(aTable).get()));

  nsAutoPtr<HashStore> store(new HashStore(aTable, mStoreDirectory));

  if (!store)
    return NS_ERROR_FAILURE;

  // take the quick exit if there is no valid update for us
  // (common case)
  uint32 validupdates = 0;

  for (uint32 i = 0; i < aUpdates->Length(); i++) {
    TableUpdate *update = aUpdates->ElementAt(i);
    if (!update || !update->TableName().Equals(store->TableName()))
      continue;
    if (update->Empty()) {
      aUpdates->ElementAt(i) = nullptr;
      delete update;
      continue;
    }
    validupdates++;
  }

  if (!validupdates) {
    return NS_OK;
  }

  nsresult rv = store->Open();
  NS_ENSURE_SUCCESS(rv, rv);
  rv = store->BeginUpdate();
  NS_ENSURE_SUCCESS(rv, rv);

  // Read the part of the store that is (only) in the cache
  LookupCache *prefixSet = GetLookupCache(store->TableName());
  if (!prefixSet) {
    return NS_ERROR_FAILURE;
  }
  nsTArray<PRUint32> AddPrefixHashes;
  rv = prefixSet->GetPrefixes(&AddPrefixHashes);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = store->AugmentAdds(AddPrefixHashes);
  NS_ENSURE_SUCCESS(rv, rv);
  AddPrefixHashes.Clear();

  uint32 applied = 0;
  bool updateFreshness = false;

  for (uint32 i = 0; i < aUpdates->Length(); i++) {
    TableUpdate *update = aUpdates->ElementAt(i);
    if (!update || !update->TableName().Equals(store->TableName()))
      continue;

    rv = store->ApplyUpdate(*update);
    NS_ENSURE_SUCCESS(rv, rv);

    applied++;

    LOG(("Applied update to table %s:", store->TableName().get()));
    LOG(("  %d add chunks", update->AddChunks().Length()));
    LOG(("  %d add prefixes", update->AddPrefixes().Length()));
    LOG(("  %d add completions", update->AddCompletes().Length()));
    LOG(("  %d sub chunks", update->SubChunks().Length()));
    LOG(("  %d sub prefixes", update->SubPrefixes().Length()));
    LOG(("  %d sub completions", update->SubCompletes().Length()));
    LOG(("  %d add expirations", update->AddExpirations().Length()));
    LOG(("  %d sub expirations", update->SubExpirations().Length()));

    if (!update->IsLocalUpdate()) {
      updateFreshness = true;
      LOG(("Remote update, updating freshness"));
    }

    aUpdates->ElementAt(i) = nullptr;
    delete update;
  }

  LOG(("Applied %d update(s) to %s.", applied, store->TableName().get()));

  rv = store->Rebuild();
  NS_ENSURE_SUCCESS(rv, rv);

  LOG(("Table %s now has:", store->TableName().get()));
  LOG(("  %d add chunks", store->AddChunks().Length()));
  LOG(("  %d add prefixes", store->AddPrefixes().Length()));
  LOG(("  %d add completions", store->AddCompletes().Length()));
  LOG(("  %d sub chunks", store->SubChunks().Length()));
  LOG(("  %d sub prefixes", store->SubPrefixes().Length()));
  LOG(("  %d sub completions", store->SubCompletes().Length()));

  rv = store->WriteFile();
  NS_ENSURE_SUCCESS(rv, rv);

  // At this point the store is updated and written out to disk, but
  // the data is still in memory.  Build our quick-lookup table here.
  rv = prefixSet->Build(store->AddPrefixes(), store->AddCompletes());
  NS_ENSURE_SUCCESS(rv, rv);
#if defined(DEBUG) && defined(PR_LOGGING)
  prefixSet->Dump();
#endif
  rv = prefixSet->WriteFile();
  NS_ENSURE_SUCCESS(rv, rv);

  // This will drop all the temporary storage used during the update.
  rv = store->FinishUpdate();
  NS_ENSURE_SUCCESS(rv, rv);

  if (updateFreshness) {
    PRInt64 now = (PR_Now() / PR_USEC_PER_SEC);
    LOG(("Successfully updated %s", store->TableName().get()));
    mTableFreshness.Put(store->TableName(), now);
  }

  return NS_OK;
}
Beispiel #11
0
int MimeWriteAString(MimeObject *obj, const nsACString &string)
{
  const nsCString &flatString = PromiseFlatCString(string);
  return MimeObject_write(obj, flatString.get(), flatString.Length(), PR_TRUE);
}
Beispiel #12
0
/* static */ already_AddRefed<gfx::SourceSurface>
ImageOps::DecodeToSurface(nsIInputStream* aInputStream,
                          const nsACString& aMimeType,
                          uint32_t aFlags)
{
  MOZ_ASSERT(aInputStream);

  nsresult rv;

  // Prepare the input stream.
  nsCOMPtr<nsIInputStream> inputStream = aInputStream;
  if (!NS_InputStreamIsBuffered(aInputStream)) {
    nsCOMPtr<nsIInputStream> bufStream;
    rv = NS_NewBufferedInputStream(getter_AddRefs(bufStream),
                                   aInputStream, 1024);
    if (NS_SUCCEEDED(rv)) {
      inputStream = bufStream;
    }
  }

  // Figure out how much data we've been passed.
  uint64_t length;
  rv = inputStream->Available(&length);
  if (NS_FAILED(rv) || length > UINT32_MAX) {
    return nullptr;
  }

  // Write the data into a SourceBuffer.
  RefPtr<SourceBuffer> sourceBuffer = new SourceBuffer();
  sourceBuffer->ExpectLength(length);
  rv = sourceBuffer->AppendFromInputStream(inputStream, length);
  if (NS_FAILED(rv)) {
    return nullptr;
  }
  sourceBuffer->Complete(NS_OK);

  // Create a decoder.
  DecoderType decoderType =
    DecoderFactory::GetDecoderType(PromiseFlatCString(aMimeType).get());
  RefPtr<Decoder> decoder =
    DecoderFactory::CreateAnonymousDecoder(decoderType,
                                           sourceBuffer,
                                           ToSurfaceFlags(aFlags));
  if (!decoder) {
    return nullptr;
  }

  // Run the decoder synchronously.
  decoder->Decode();
  if (!decoder->GetDecodeDone() || decoder->HasError()) {
    return nullptr;
  }

  // Pull out the surface.
  RawAccessFrameRef frame = decoder->GetCurrentFrameRef();
  if (!frame) {
    return nullptr;
  }

  RefPtr<SourceSurface> surface = frame->GetSurface();
  if (!surface) {
    return nullptr;
  }

  return surface.forget();
}
Beispiel #13
0
/**
 * Given a string which contains a list of Header addresses, returns a
 * comma-separated list of just the `user name' portions.  If any of
 * the addresses doesn't have a name, then the mailbox is used instead.
 *
 * The names are *unquoted* and therefore cannot be re-parsed in any way.
 * They are, however, nice and human-readable.
 */
NS_IMETHODIMP
nsMsgHeaderParser::ExtractHeaderAddressNames(const nsACString &aLine,
        nsACString &aResult)
{
    if (aLine.IsEmpty())
    {
        aResult.Truncate();
        return NS_OK;
    }

    char *names = 0;
    char *addrs = 0;
    int status = msg_parse_Header_addresses(PromiseFlatCString(aLine).get(),
                                            &names, &addrs);
    if (status <= 0)
        return NS_ERROR_FAILURE;

    PRUint32 len1, len2;
    char *s1, *s2, *out;
    PRUint32 i, size = 0;

    s1 = names;
    s2 = addrs;
    for (i = 0; (int)i < status; i++)
    {
        len1 = strlen(s1);
        len2 = strlen(s2);
        s1 += len1 + 1;
        s2 += len2 + 1;
        size += (len1 ? len1 : len2);
        if ((int)(i + 1) < status)
            size += 2;
    }

    nsCString result;
    result.SetLength(size);

    out = result.BeginWriting();
    s1 = names;
    s2 = addrs;
    for (i = 0; (int)i < status; i++)
    {
        len1 = strlen(s1);
        len2 = strlen(s2);

        if (len1)
        {
            memcpy(out, s1, len1);
            out += len1;
        }
        else
        {
            memcpy(out, s2, len2);
            out += len2;
        }

        if ((int)(i + 1) < status)
        {
            *out++ = ',';
            *out++ = ' ';
        }
        s1 += len1 + 1;
        s2 += len2 + 1;
    }

    PR_Free(names);
    PR_Free(addrs);
    aResult = result;
    return NS_OK;
}
already_AddRefed<nsIMIMEInfo> nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, const nsACString& aFileExt, bool *aFound)
{
  *aFound = true;

  const nsCString& flatType = PromiseFlatCString(aMIMEType);
  const nsCString& flatExt = PromiseFlatCString(aFileExt);

  nsAutoString fileExtension;
  /* XXX The Equals is a gross hack to wallpaper over the most common Win32
   * extension issues caused by the fix for bug 116938.  See bug
   * 120327, comment 271 for why this is needed.  Not even sure we
   * want to remove this once we have fixed all this stuff to work
   * right; any info we get from the OS on this type is pretty much
   * useless....
   * We'll do extension-based lookup for this type later in this function.
   */
  if (!aMIMEType.LowerCaseEqualsLiteral(APPLICATION_OCTET_STREAM)) {
    // (1) try to use the windows mime database to see if there is a mapping to a file extension
    // (2) try to see if we have some left over 4.x registry info we can peek at...
    GetExtensionFromWindowsMimeDatabase(aMIMEType, fileExtension);
    LOG(("Windows mime database: extension '%s'\n", fileExtension.get()));
    if (fileExtension.IsEmpty()) {
      GetExtensionFrom4xRegistryInfo(aMIMEType, fileExtension);
      LOG(("4.x Registry: extension '%s'\n", fileExtension.get()));
    }
  }
  // If we found an extension for the type, do the lookup
  nsRefPtr<nsMIMEInfoWin> mi;
  if (!fileExtension.IsEmpty())
    mi = GetByExtension(fileExtension, flatType.get());
  LOG(("Extension lookup on '%s' found: 0x%p\n", fileExtension.get(), mi.get()));

  bool hasDefault = false;
  if (mi) {
    mi->GetHasDefaultHandler(&hasDefault);
    // OK. We might have the case that |aFileExt| is a valid extension for the
    // mimetype we were given. In that case, we do want to append aFileExt
    // to the mimeinfo that we have. (E.g.: We are asked for video/mpeg and
    // .mpg, but the primary extension for video/mpeg is .mpeg. But because
    // .mpg is an extension for video/mpeg content, we want to append it)
    if (!aFileExt.IsEmpty() && typeFromExtEquals(NS_ConvertUTF8toUTF16(flatExt).get(), flatType.get())) {
      LOG(("Appending extension '%s' to mimeinfo, because its mimetype is '%s'\n",
           flatExt.get(), flatType.get()));
      bool extExist = false;
      mi->ExtensionExists(aFileExt, &extExist);
      if (!extExist)
        mi->AppendExtension(aFileExt);
    }
  }
  if (!mi || !hasDefault) {
    nsRefPtr<nsMIMEInfoWin> miByExt =
      GetByExtension(NS_ConvertUTF8toUTF16(aFileExt), flatType.get());
    LOG(("Ext. lookup for '%s' found 0x%p\n", flatExt.get(), miByExt.get()));
    if (!miByExt && mi)
      return mi.forget();
    if (miByExt && !mi) {
      return miByExt.forget();
    }
    if (!miByExt && !mi) {
      *aFound = false;
      mi = new nsMIMEInfoWin(flatType);
      if (!aFileExt.IsEmpty()) {
        mi->AppendExtension(aFileExt);
      }
      
      return mi.forget();
    }

    // if we get here, mi has no default app. copy from extension lookup.
    nsCOMPtr<nsIFile> defaultApp;
    nsAutoString desc;
    miByExt->GetDefaultDescription(desc);

    mi->SetDefaultDescription(desc);
  }
  return mi.forget();
}
static int MimeInlineTextPlainFlowed_parse_line(const char *aLine,
                                                int32_t length,
                                                MimeObject *obj) {
  int status;
  bool quoting =
      (obj->options &&
       (obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting ||
        obj->options->format_out ==
            nsMimeOutput::nsMimeMessageBodyQuoting));  // see above
  bool plainHTML =
      quoting || (obj->options && obj->options->format_out ==
                                      nsMimeOutput::nsMimeMessageSaveAs);
  // see above

  struct MimeInlineTextPlainFlowedExData *exdata;
  exdata = MimeInlineTextPlainFlowedExDataList;
  while (exdata && (exdata->ownerobj != obj)) {
    exdata = exdata->next;
  }

  NS_ASSERTION(exdata, "The extra data has disappeared!");

  NS_ASSERTION(length > 0, "zero length");
  if (length <= 0) return 0;

  uint32_t linequotelevel = 0;
  nsAutoCString real_line(aLine, length);
  char *line = real_line.BeginWriting();
  const char *linep = real_line.BeginReading();
  // Space stuffed?
  if (' ' == *linep) {
    linep++;
  } else {
    // count '>':s before the first non-'>'
    while ('>' == *linep) {
      linep++;
      linequotelevel++;
    }
    // Space stuffed?
    if (' ' == *linep) {
      linep++;
    }
  }

  // Look if the last character (after stripping ending end
  // of lines and quoting stuff) is a SPACE. If it is, we are looking at a
  // flowed line. Normally we assume that the last two chars
  // are CR and LF as said in RFC822, but that doesn't seem to
  // be the case always.
  bool flowed = false;
  bool sigSeparator = false;
  int32_t index = length - 1;
  while (index >= 0 && ('\r' == line[index] || '\n' == line[index])) {
    index--;
  }
  if (index > linep - line && ' ' == line[index])
  /* Ignore space stuffing, i.e. lines with just
     (quote marks and) a space count as empty */
  {
    flowed = true;
    sigSeparator =
        (index - (linep - line) + 1 == 3) && !strncmp(linep, "-- ", 3);
    if (((MimeInlineTextPlainFlowed *)obj)->delSp && !sigSeparator)
    /* If line is flowed and DelSp=yes, logically
       delete trailing space. Line consisting of
       dash dash space ("-- "), commonly used as
       signature separator, gets special handling
       (RFC 3676) */
    {
      length = index;
      line[index] = '\0';
    }
  }

  if (obj->options && obj->options->decompose_file_p &&
      obj->options->decompose_file_output_fn) {
    return obj->options->decompose_file_output_fn(line, length,
                                                  obj->options->stream_closure);
  }

  mozITXTToHTMLConv *conv = GetTextConverter(obj->options);

  bool skipConversion =
      !conv || (obj->options && obj->options->force_user_charset);

  nsAutoString lineSource;
  nsString lineResult;

  char *mailCharset = NULL;
  nsresult rv;

  if (!skipConversion) {
    // Convert only if the source string is not empty
    if (length - (linep - line) > 0) {
      uint32_t whattodo = obj->options->whattodo;
      if (plainHTML) {
        if (quoting)
          whattodo = 0;
        else
          whattodo = whattodo & ~mozITXTToHTMLConv::kGlyphSubstitution;
        /* Do recognition for the case, the result is viewed in
            Mozilla, but not GlyphSubstitution, because other UAs
            might not be able to display the glyphs. */
      }

      const nsDependentCSubstring &inputStr =
          Substring(linep, linep + (length - (linep - line)));

      // For 'SaveAs', |line| is in |mailCharset|.
      // convert |line| to UTF-16 before 'html'izing (calling ScanTXT())
      if (obj->options->format_out == nsMimeOutput::nsMimeMessageSaveAs) {
        // Get the mail charset of this message.
        MimeInlineText *inlinetext = (MimeInlineText *)obj;
        if (!inlinetext->initializeCharset)
          ((MimeInlineTextClass *)&mimeInlineTextClass)
              ->initialize_charset(obj);
        mailCharset = inlinetext->charset;
        if (mailCharset && *mailCharset) {
          rv = nsMsgI18NConvertToUnicode(nsDependentCString(mailCharset),
                                         PromiseFlatCString(inputStr),
                                         lineSource);
          NS_ENSURE_SUCCESS(rv, -1);
        } else  // this probably never happens...
          CopyUTF8toUTF16(inputStr, lineSource);
      } else  // line is in UTF-8
        CopyUTF8toUTF16(inputStr, lineSource);

      // This is the main TXT to HTML conversion:
      // escaping (very important), eventually recognizing etc.
      rv = conv->ScanTXT(lineSource, whattodo, lineResult);
      NS_ENSURE_SUCCESS(rv, -1);
    }
  } else {
    CopyUTF8toUTF16(nsDependentCString(line, length), lineResult);
    status = 0;
  }

  nsAutoCString preface;

  /* Correct number of blockquotes */
  int32_t quoteleveldiff = linequotelevel - exdata->quotelevel;
  if ((quoteleveldiff != 0) && flowed && exdata->inflow) {
    // From RFC 2646 4.5
    // The receiver SHOULD handle this error by using the 'quote-depth-wins'
    // rule, which is to ignore the flowed indicator and treat the line as
    // fixed.  That is, the change in quote depth ends the paragraph.

    // We get that behaviour by just going on.
  }

  // Cast so we have access to the prefs we need.
  MimeInlineTextPlainFlowed *tObj = (MimeInlineTextPlainFlowed *)obj;
  while (quoteleveldiff > 0) {
    quoteleveldiff--;
    preface += "<blockquote type=cite";

    nsAutoCString style;
    MimeTextBuildPrefixCSS(tObj->mQuotedSizeSetting, tObj->mQuotedStyleSetting,
                           tObj->mCitationColor, style);
    if (!plainHTML && !style.IsEmpty()) {
      preface += " style=\"";
      preface += style;
      preface += '"';
    }
    preface += '>';
  }
  while (quoteleveldiff < 0) {
    quoteleveldiff++;
    preface += "</blockquote>";
  }
  exdata->quotelevel = linequotelevel;

  nsAutoString lineResult2;

  if (flowed) {
    // Check RFC 2646 "4.3. Usenet Signature Convention": "-- "+CRLF is
    // not a flowed line
    if (sigSeparator) {
      if (linequotelevel > 0 || exdata->isSig) {
        preface += "--&nbsp;<br>";
      } else {
        exdata->isSig = true;
        preface +=
            "<div class=\"moz-txt-sig\"><span class=\"moz-txt-tag\">"
            "--&nbsp;<br></span>";
      }
    } else {
      Line_convert_whitespace(lineResult, false /* Allow wraps */, lineResult2);
    }

    exdata->inflow = true;
  } else {
    // Fixed paragraph.
    Line_convert_whitespace(lineResult,
                            !plainHTML && !obj->options->wrap_long_lines_p
                            /* If wrap, convert all spaces but the last in
                               a row into nbsp, otherwise all. */
                            ,
                            lineResult2);
    lineResult2.AppendLiteral("<br>");
    exdata->inflow = false;
  }  // End Fixed line

  if (!(exdata->isSig && quoting && tObj->mStripSig)) {
    status = MimeObject_write(obj, preface.get(), preface.Length(), true);
    if (status < 0) return status;
    nsAutoCString outString;
    if (obj->options->format_out != nsMimeOutput::nsMimeMessageSaveAs ||
        !mailCharset || !*mailCharset)
      CopyUTF16toUTF8(lineResult2, outString);
    else {  // convert back to mailCharset before writing.
      rv = nsMsgI18NConvertFromUnicode(nsDependentCString(mailCharset),
                                       lineResult2, outString);
      NS_ENSURE_SUCCESS(rv, -1);
    }
    status = MimeObject_write(obj, outString.get(), outString.Length(), true);
    return status;
  }
  return 0;
}
Beispiel #16
0
NS_IMETHODIMP nsJPEGEncoder::InitFromData(const PRUint8* aData,
                                          PRUint32 aLength, // (unused, req'd by JS)
                                          PRUint32 aWidth,
                                          PRUint32 aHeight,
                                          PRUint32 aStride,
                                          PRUint32 aInputFormat,
                                          const nsAString& aOutputOptions)
{
  // validate input format
  if (aInputFormat != INPUT_FORMAT_RGB &&
      aInputFormat != INPUT_FORMAT_RGBA &&
      aInputFormat != INPUT_FORMAT_HOSTARGB)
    return NS_ERROR_INVALID_ARG;

  // Stride is the padded width of each row, so it better be longer (I'm afraid
  // people will not understand what stride means, so check it well)
  if ((aInputFormat == INPUT_FORMAT_RGB &&
       aStride < aWidth * 3) ||
      ((aInputFormat == INPUT_FORMAT_RGBA || aInputFormat == INPUT_FORMAT_HOSTARGB) &&
       aStride < aWidth * 4)) {
    NS_WARNING("Invalid stride for InitFromData");
    return NS_ERROR_INVALID_ARG;
  }

  // can't initialize more than once
  if (mImageBuffer != nsnull)
    return NS_ERROR_ALREADY_INITIALIZED;

  // options: we only have one option so this is easy
  int quality = 50;
  if (aOutputOptions.Length() > 0) {
    // have options string
    const nsString qualityPrefix(NS_LITERAL_STRING("quality="));
    if (aOutputOptions.Length() > qualityPrefix.Length()  &&
        StringBeginsWith(aOutputOptions, qualityPrefix)) {
      // have quality string
      nsCString value = NS_ConvertUTF16toUTF8(Substring(aOutputOptions,
                                                        qualityPrefix.Length()));
      int newquality = -1;
      if (PR_sscanf(PromiseFlatCString(value).get(), "%d", &newquality) == 1) {
        if (newquality >= 0 && newquality <= 100) {
          quality = newquality;
        } else {
          NS_WARNING("Quality value out of range, should be 0-100, using default");
        }
      } else {
        NS_WARNING("Quality value invalid, should be integer 0-100, using default");
      }
    }
  }

  jpeg_compress_struct cinfo;

  // We set up the normal JPEG error routines, then override error_exit.
  // This must be done before the call to create_compress
  encoder_error_mgr errmgr;
  cinfo.err = jpeg_std_error(&errmgr.pub);
  errmgr.pub.error_exit = errorExit;
  // Establish the setjmp return context for my_error_exit to use.
  if (setjmp(errmgr.setjmp_buffer)) {
    // If we get here, the JPEG code has signaled an error.
    // We need to clean up the JPEG object, close the input file, and return.
    return NS_ERROR_FAILURE;
  }

  jpeg_create_compress(&cinfo);
  cinfo.image_width = aWidth;
  cinfo.image_height = aHeight;
  cinfo.input_components = 3;
  cinfo.in_color_space = JCS_RGB;
  cinfo.data_precision = 8;

  jpeg_set_defaults(&cinfo);
  jpeg_set_quality(&cinfo, quality, 1); // quality here is 0-100

  // set up the destination manager
  jpeg_destination_mgr destmgr;
  destmgr.init_destination = initDestination;
  destmgr.empty_output_buffer = emptyOutputBuffer;
  destmgr.term_destination = termDestination;
  cinfo.dest = &destmgr;
  cinfo.client_data = this;

  jpeg_start_compress(&cinfo, 1);

  // feed it the rows
  if (aInputFormat == INPUT_FORMAT_RGB) {
    while (cinfo.next_scanline < cinfo.image_height) {
      const PRUint8* row = &aData[cinfo.next_scanline * aStride];
      jpeg_write_scanlines(&cinfo, NS_CONST_CAST(PRUint8**, &row), 1);
    }
  } else if (aInputFormat == INPUT_FORMAT_RGBA) {
Beispiel #17
0
void
NrIceCtx::InitializeGlobals(bool allow_loopback,
                            bool tcp_enabled,
                            bool allow_link_local) {
  // Initialize the crypto callbacks and logging stuff
  if (!initialized) {
    NR_reg_init(NR_REG_MODE_LOCAL);
    nr_crypto_vtbl = &nr_ice_crypto_nss_vtbl;
    initialized = true;

    // Set the priorites for candidate type preferences.
    // These numbers come from RFC 5245 S. 4.1.2.2
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX, 100);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX, 110);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST, 126);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED, 5);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_SRV_RFLX_TCP, 99);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_PEER_RFLX_TCP, 109);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_HOST_TCP, 125);
    NR_reg_set_uchar((char *)NR_ICE_REG_PREF_TYPE_RELAYED_TCP, 0);

    int32_t stun_client_maximum_transmits = 7;
    int32_t ice_trickle_grace_period = 5000;
    int32_t ice_tcp_so_sock_count = 3;
    int32_t ice_tcp_listen_backlog = 10;
    nsAutoCString force_net_interface;
    nsresult res;
    nsCOMPtr<nsIPrefService> prefs =
      do_GetService("@mozilla.org/preferences-service;1", &res);

    if (NS_SUCCEEDED(res)) {
      nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(prefs);
      if (branch) {
        branch->GetIntPref(
            "media.peerconnection.ice.stun_client_maximum_transmits",
            &stun_client_maximum_transmits);
        branch->GetIntPref(
            "media.peerconnection.ice.trickle_grace_period",
            &ice_trickle_grace_period);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_so_sock_count",
            &ice_tcp_so_sock_count);
        branch->GetIntPref(
            "media.peerconnection.ice.tcp_listen_backlog",
            &ice_tcp_listen_backlog);
        branch->GetCharPref(
            "media.peerconnection.ice.force_interface",
            getter_Copies(force_net_interface));
      }
    }

    NR_reg_set_uint4((char *)"stun.client.maximum_transmits",
                     stun_client_maximum_transmits);
    NR_reg_set_uint4((char *)NR_ICE_REG_TRICKLE_GRACE_PERIOD,
                     ice_trickle_grace_period);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_SO_SOCK_COUNT,
                     ice_tcp_so_sock_count);
    NR_reg_set_int4((char *)NR_ICE_REG_ICE_TCP_LISTEN_BACKLOG,
                     ice_tcp_listen_backlog);

    NR_reg_set_char((char *)NR_ICE_REG_ICE_TCP_DISABLE, !tcp_enabled);

    if (allow_loopback) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LOOPBACK_ADDRS, 1);
    }

    if (allow_link_local) {
      NR_reg_set_char((char *)NR_STUN_REG_PREF_ALLOW_LINK_LOCAL_ADDRS, 1);
    }
    if (force_net_interface.Length() > 0) {
      // Stupid cast.... but needed
      const nsCString& flat = PromiseFlatCString(static_cast<nsACString&>(force_net_interface));
      NR_reg_set_string((char *)NR_ICE_REG_PREF_FORCE_INTERFACE_NAME, const_cast<char*>(flat.get()));
    }
  }
}
Beispiel #18
0
NS_IMETHODIMP
nsGopherChannel::GetContentType(nsACString &aContentType)
{
    if (!mContentType.IsEmpty()) {
        aContentType = mContentType;
        return NS_OK;
    }

    switch(mType) {
    case '0':
    case 'h':
        aContentType.AssignLiteral(TEXT_HTML);
        break;
    case '1':
        aContentType.AssignLiteral(APPLICATION_HTTP_INDEX_FORMAT);
        break;
    case '2': // CSO search - unhandled, should not be selectable
        aContentType.AssignLiteral(TEXT_HTML);
        break;
    case '3': // "Error" - should not be selectable
        aContentType.AssignLiteral(TEXT_HTML);
        break;
    case '4': // "BinHexed Macintosh file"
        aContentType.AssignLiteral(APPLICATION_BINHEX);
        break;
    case '5':
        // "DOS binary archive of some sort" - is the mime-type correct?
        aContentType.AssignLiteral(APPLICATION_OCTET_STREAM);
        break;
    case '6':
        aContentType.AssignLiteral(APPLICATION_UUENCODE);
        break;
    case '7': // search - returns a directory listing
        aContentType.AssignLiteral(APPLICATION_HTTP_INDEX_FORMAT);
        break;
    case '8': // telnet - type doesn't make sense
        aContentType.AssignLiteral(TEXT_PLAIN);
        break;
    case '9': // "Binary file!"
        aContentType.AssignLiteral(APPLICATION_OCTET_STREAM);
        break;
    case 'g':
        aContentType.AssignLiteral(IMAGE_GIF);
        break;
    case 'i': // info line- should not be selectable
        aContentType.AssignLiteral(TEXT_HTML);
        break;
    case 'I':
        aContentType.AssignLiteral(IMAGE_GIF);
        break;
    case 'T': // tn3270 - type doesn't make sense
        aContentType.AssignLiteral(TEXT_PLAIN);
        break;
    default:
        if (!mContentTypeHint.IsEmpty()) {
            aContentType = mContentTypeHint;
        } else {
            NS_WARNING("Unknown gopher type");
            aContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
        }
        break;
    }

    PR_LOG(gGopherLog,PR_LOG_DEBUG,
           ("GetContentType returning %s\n", PromiseFlatCString(aContentType).get()));

    // XXX do we want to cache this result?
    return NS_OK;
}
nsresult nsProfileLock::LockWithSymlink(const nsACString& lockFilePath, PRBool aHaveFcntlLock)
{
    nsresult rv;

    struct in_addr inaddr;
    inaddr.s_addr = htonl(INADDR_LOOPBACK);

    char hostname[256];
    PRStatus status = PR_GetSystemInfo(PR_SI_HOSTNAME, hostname, sizeof hostname);
    if (status == PR_SUCCESS)
    {
        char netdbbuf[PR_NETDB_BUF_SIZE];
        PRHostEnt hostent;
        status = PR_GetHostByName(hostname, netdbbuf, sizeof netdbbuf, &hostent);
        if (status == PR_SUCCESS)
            memcpy(&inaddr, hostent.h_addr, sizeof inaddr);
    }

    char *signature =
        PR_smprintf("%s:%s%lu", inet_ntoa(inaddr), aHaveFcntlLock ? "+" : "",
                    (unsigned long)getpid());
    const nsPromiseFlatCString& flat = PromiseFlatCString(lockFilePath);
    const char *fileName = flat.get();
    int symlink_rv, symlink_errno = 0, tries = 0;

    // use ns4.x-compatible symlinks if the FS supports them
    while ((symlink_rv = symlink(signature, fileName)) < 0)
    {
        symlink_errno = errno;
        if (symlink_errno != EEXIST)
            break;

        if (!IsSymlinkStaleLock(&inaddr, fileName, aHaveFcntlLock))
            break;

        // Lock seems to be bogus: try to claim it.  Give up after a large
        // number of attempts (100 comes from the 4.x codebase).
        (void) unlink(fileName);
        if (++tries > 100)
            break;
    }

    PR_smprintf_free(signature);
    signature = nsnull;

    if (symlink_rv == 0)
    {
        // We exclusively created the symlink: record its name for eventual
        // unlock-via-unlink.
        rv = NS_OK;
        mHaveLock = PR_TRUE;
        mPidLockFileName = strdup(fileName);
        if (mPidLockFileName)
        {
            PR_APPEND_LINK(this, &mPidLockList);
            if (!setupPidLockCleanup++)
            {
                // Clean up on normal termination.
                atexit(RemovePidLockFilesExiting);

                // Clean up on abnormal termination, using POSIX sigaction.
                // Don't arm a handler if the signal is being ignored, e.g.,
                // because mozilla is run via nohup.
                if (!sDisableSignalHandling) {
                    struct sigaction act, oldact;
#ifdef SA_SIGINFO
                    act.sa_sigaction = FatalSignalHandler;
                    act.sa_flags = SA_SIGINFO;
#else
                    act.sa_handler = FatalSignalHandler;
#endif
                    sigfillset(&act.sa_mask);

#define CATCH_SIGNAL(signame)                                           \
PR_BEGIN_MACRO                                                          \
  if (sigaction(signame, NULL, &oldact) == 0 &&                         \
      oldact.sa_handler != SIG_IGN)                                     \
  {                                                                     \
      sigaction(signame, &act, &signame##_oldact);                      \
  }                                                                     \
  PR_END_MACRO

                    CATCH_SIGNAL(SIGHUP);
                    CATCH_SIGNAL(SIGINT);
                    CATCH_SIGNAL(SIGQUIT);
                    CATCH_SIGNAL(SIGILL);
                    CATCH_SIGNAL(SIGABRT);
                    CATCH_SIGNAL(SIGSEGV);
                    CATCH_SIGNAL(SIGTERM);

#undef CATCH_SIGNAL
                }
            }
        }
    }
    else if (symlink_errno == EEXIST)
        rv = NS_ERROR_FILE_ACCESS_DENIED;
    else
    {
#ifdef DEBUG
        printf("symlink() failed. errno = %d\n", errno);
#endif
        rv = NS_ERROR_FAILURE;
    }
    return rv;
}
Beispiel #20
0
NS_IMETHODIMP
nsDNSService::Resolve(const nsACString &hostname,
                      PRUint32          flags,
                      nsIDNSRecord    **result)
{
    // grab reference to global host resolver and IDN service.  beware
    // simultaneous shutdown!!
    nsRefPtr<nsHostResolver> res;
    nsCOMPtr<nsIIDNService> idn;
    {
        nsAutoLock lock(mLock);
        res = mResolver;
        idn = mIDN;
    }
    NS_ENSURE_TRUE(res, NS_ERROR_OFFLINE);

    const nsACString *hostPtr = &hostname;

    nsresult rv;
    nsCAutoString hostACE;
    if (idn && !IsASCII(hostname)) {
        if (NS_SUCCEEDED(idn->ConvertUTF8toACE(hostname, hostACE)))
            hostPtr = &hostACE;
    }

    //
    // sync resolve: since the host resolver only works asynchronously, we need
    // to use a mutex and a condvar to wait for the result.  however, since the
    // result may be in the resolvers cache, we might get called back recursively
    // on the same thread.  so, our mutex needs to be re-entrant.  inotherwords,
    // we need to use a monitor! ;-)
    //
    
    PRMonitor *mon = PR_NewMonitor();
    if (!mon)
        return NS_ERROR_OUT_OF_MEMORY;

    PR_EnterMonitor(mon);
    nsDNSSyncRequest syncReq(mon);

    PRUint16 af = GetAFForLookup(*hostPtr);

    rv = res->ResolveHost(PromiseFlatCString(*hostPtr).get(), flags, af, &syncReq);
    if (NS_SUCCEEDED(rv)) {
        // wait for result
        while (!syncReq.mDone)
            PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT);

        if (NS_FAILED(syncReq.mStatus))
            rv = syncReq.mStatus;
        else {
            NS_ASSERTION(syncReq.mHostRecord, "no host record");
            nsDNSRecord *rec = new nsDNSRecord(syncReq.mHostRecord);
            if (!rec)
                rv = NS_ERROR_OUT_OF_MEMORY;
            else
                NS_ADDREF(*result = rec);
        }
    }

    PR_ExitMonitor(mon);
    PR_DestroyMonitor(mon);
    return rv;
}
// Decode a parameter value using the encoding defined in RFC 5987
// 
// charset  "'" [ language ] "'" value-chars
NS_IMETHODIMP 
nsMIMEHeaderParamImpl::DecodeRFC5987Param(const nsACString& aParamVal,
                                          nsACString& aLang,
                                          nsAString& aResult)
{
  nsCAutoString charset;
  nsCAutoString language;
  nsCAutoString value;

  PRUint32 delimiters = 0;
  const char *encoded = PromiseFlatCString(aParamVal).get();
  const char *c = encoded;

  while (*c) {
    char tc = *c++;

    if (tc == '\'') {
      // single quote
      delimiters++;
    } else if (tc >= 128) {
      // fail early, not ASCII
      NS_WARNING("non-US-ASCII character in RFC5987-encoded param");
      return NS_ERROR_INVALID_ARG;
    } else {
      if (delimiters == 0) {
        // valid characters are checked later implicitly
        charset.Append(tc);
      } else if (delimiters == 1) {
        // no value checking for now
        language.Append(tc);
      } else if (delimiters == 2) {
        if (IsRFC5987AttrChar(tc)) {
          value.Append(tc);
        } else if (tc == '%') {
          if (!IsHexDigit(c[0]) || !IsHexDigit(c[1])) {
            // we expect two more characters
            NS_WARNING("broken %-escape in RFC5987-encoded param");
            return NS_ERROR_INVALID_ARG;
          }
          value.Append(tc);
          // we consume two more
          value.Append(*c++);
          value.Append(*c++);
        } else {
          // character not allowed here
          NS_WARNING("invalid character in RFC5987-encoded param");
          return NS_ERROR_INVALID_ARG;
        }      
      }
    }
  }

  if (delimiters != 2) {
    NS_WARNING("missing delimiters in RFC5987-encoded param");
    return NS_ERROR_INVALID_ARG;
  }

  // abort early for unsupported encodings
  if (!charset.LowerCaseEqualsLiteral("utf-8")) {
    NS_WARNING("unsupported charset in RFC5987-encoded param");
    return NS_ERROR_INVALID_ARG;
  }

  // percent-decode
  if (!PercentDecode(value)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // return the encoding
  aLang.Assign(language);

  // finally convert octet sequence to UTF-8 and be done
  nsresult rv = NS_OK;
  nsCOMPtr<nsIUTF8ConverterService> cvtUTF8 =
    do_GetService(NS_UTF8CONVERTERSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCAutoString utf8;
  rv = cvtUTF8->ConvertStringToUTF8(value, charset.get(), true, false, 1, utf8);
  NS_ENSURE_SUCCESS(rv, rv);

  CopyUTF8toUTF16(utf8, aResult);
  return NS_OK;
}
static MediaCodec::LocalRef CreateDecoder(const nsACString& aMimeType)
{
  MediaCodec::LocalRef codec;
  NS_ENSURE_SUCCESS(MediaCodec::CreateDecoderByType(PromiseFlatCString(aMimeType).get(), &codec), nullptr);
  return codec;
}
Beispiel #23
0
NS_IMETHODIMP nsDefaultURIFixup::KeywordToURI(const nsACString& aKeyword,
                                              nsIURI **aURI)
{
    *aURI = nsnull;
    NS_ENSURE_STATE(mPrefBranch);

    nsXPIDLCString url;
    nsCOMPtr<nsIPrefLocalizedString> keywordURL;
    mPrefBranch->GetComplexValue("keyword.URL", 
                                 NS_GET_IID(nsIPrefLocalizedString),
                                 getter_AddRefs(keywordURL));

    if (keywordURL) {
        nsXPIDLString wurl;
        keywordURL->GetData(getter_Copies(wurl));
        CopyUTF16toUTF8(wurl, url);
    } else {
        // Fall back to a non-localized pref, for backwards compat
        mPrefBranch->GetCharPref("keyword.URL", getter_Copies(url));
    }

    // If the pref is set and non-empty, use it.
    if (!url.IsEmpty()) {
        nsCAutoString spec;
        nsresult rv = MangleKeywordIntoURI(PromiseFlatCString(aKeyword).get(),
                                           url.get(), spec);
        if (NS_FAILED(rv)) return rv;

        return NS_NewURI(aURI, spec);
    }

    // Try falling back to the search service's default search engine
    nsCOMPtr<nsIBrowserSearchService> searchSvc = do_GetService("@mozilla.org/browser/search-service;1");
    if (searchSvc) {
        nsCOMPtr<nsISearchEngine> defaultEngine;
        searchSvc->GetOriginalDefaultEngine(getter_AddRefs(defaultEngine));
        if (defaultEngine) {
            nsCOMPtr<nsISearchSubmission> submission;
            // We want to allow default search plugins to specify alternate
            // parameters that are specific to keyword searches. For the moment,
            // do this by first looking for a magic
            // "application/x-moz-keywordsearch" submission type. In the future,
            // we should instead use a solution that relies on bug 587780.
            defaultEngine->GetSubmission(NS_ConvertUTF8toUTF16(aKeyword),
                                         NS_LITERAL_STRING("application/x-moz-keywordsearch"),
                                         getter_AddRefs(submission));
            // If getting the special x-moz-keywordsearch submission type failed,
            // fall back to the default response type.
            if (!submission) {
                defaultEngine->GetSubmission(NS_ConvertUTF8toUTF16(aKeyword),
                                             EmptyString(),
                                             getter_AddRefs(submission));
            }

            if (submission) {
                // The submission depends on POST data (i.e. the search engine's
                // "method" is POST), we can't use this engine for keyword
                // searches
                nsCOMPtr<nsIInputStream> postData;
                submission->GetPostData(getter_AddRefs(postData));
                if (postData) {
                    return NS_ERROR_NOT_AVAILABLE;
                }

                return submission->GetUri(aURI);
            }
        }
    }

    // out of options
    return NS_ERROR_NOT_AVAILABLE;
}
NS_IMETHODIMP
nsPluginStreamListenerPeer::VisitHeader(const nsACString &header, const nsACString &value)
{
  return mPStreamListener->NewResponseHeader(PromiseFlatCString(header).get(),
                                             PromiseFlatCString(value).get());
}
Beispiel #25
0
// submission
// much of this is cut and paste from nsFormFrame::OnSubmit
NS_IMETHODIMP
nsIsIndexFrame::OnSubmit(nsPresContext* aPresContext)
{
  if (!mContent || !mInputContent) {
    return NS_ERROR_UNEXPECTED;
  }

  if (mContent->IsEditable()) {
    return NS_OK;
  }

  nsresult result = NS_OK;

  // Begin ProcessAsURLEncoded
  nsAutoString data;

  nsCOMPtr<nsIUnicodeEncoder> encoder;
  if(NS_FAILED(GetEncoder(getter_AddRefs(encoder))))  // Non-fatal error
     encoder = nsnull;

  nsAutoString value;
  GetInputValue(value);
  URLEncode(value, encoder, data);
  // End ProcessAsURLEncoded

  // make the url string
  nsAutoString href;

  // Get the document.
  // We'll need it now to form the URL we're submitting to.
  // We'll also need it later to get the DOM window when notifying form submit observers (bug 33203)
  nsCOMPtr<nsIDocument> document = mContent->GetDocument();
  if (!document) return NS_OK; // No doc means don't submit, see Bug 28988

  // Resolve url to an absolute url
  nsIURI *baseURI = document->GetDocBaseURI();
  if (!baseURI) {
    NS_ERROR("No Base URL found in Form Submit!");
    return NS_OK; // No base URL -> exit early, see Bug 30721
  }

  // If an action is not specified and we are inside 
  // a HTML document then reload the URL. This makes us
  // compatible with 4.x browsers.
  // If we are in some other type of document such as XML or
  // XUL, do nothing. This prevents undesirable reloading of
  // a document inside XUL.

  nsresult rv;
  nsCOMPtr<nsIHTMLDocument> htmlDoc;
  htmlDoc = do_QueryInterface(document, &rv);
  if (NS_FAILED(rv)) {   
    // Must be a XML, XUL or other non-HTML document type
    // so do nothing.
    return NS_OK;
  } 

  // Necko's MakeAbsoluteURI doesn't reuse the baseURL's rel path if it is
  // passed a zero length rel path.
  nsCAutoString relPath;
  baseURI->GetSpec(relPath);
  if (!relPath.IsEmpty()) {
    CopyUTF8toUTF16(relPath, href);

    // If re-using the same URL, chop off old query string (bug 25330)
    PRInt32 queryStart = href.FindChar('?');
    if (kNotFound != queryStart) {
      href.Truncate(queryStart);
    }
  } else {
    NS_ERROR("Rel path couldn't be formed in form submit!");
    return NS_ERROR_OUT_OF_MEMORY;
  }

  // Add the URI encoded form values to the URI
  // Get the scheme of the URI.
  nsCOMPtr<nsIURI> actionURL;
  nsXPIDLCString scheme;
  PRBool isJSURL = PR_FALSE;
  const nsACString &docCharset = document->GetDocumentCharacterSet();
  const nsPromiseFlatCString& flatDocCharset = PromiseFlatCString(docCharset);

  if (NS_SUCCEEDED(result = NS_NewURI(getter_AddRefs(actionURL), href,
                                      flatDocCharset.get(),
                                      baseURI))) {
    result = actionURL->SchemeIs("javascript", &isJSURL);
  }
  // Append the URI encoded variable/value pairs for GET's
  if (!isJSURL) { // Not for JS URIs, see bug 26917
    if (href.FindChar('?') == kNotFound) { // Add a ? if needed
      href.Append(PRUnichar('?'));
    } else {                              // Adding to existing query string
      if (href.Last() != '&' && href.Last() != '?') {   // Add a & if needed
        href.Append(PRUnichar('&'));
      }
    }
    href.Append(data);
  }
  nsCOMPtr<nsIURI> uri;
  result = NS_NewURI(getter_AddRefs(uri), href,
                     flatDocCharset.get(), baseURI);
  if (NS_FAILED(result)) return result;

  // Now pretend we're triggering a link
  nsContentUtils::TriggerLink(mContent, aPresContext, uri,
                              EmptyString(), PR_TRUE, PR_TRUE);
  return result;
}
nsresult
nsMIMEInfoUnix::LaunchDefaultWithFile(nsIFile *aFile)
{
  // if mDefaultApplication is set, it means the application has been set from
  // either /etc/mailcap or ${HOME}/.mailcap, in which case we don't want to
  // give the GNOME answer.
  if (mDefaultApplication)
    return nsMIMEInfoImpl::LaunchDefaultWithFile(aFile);

  nsAutoCString nativePath;
  aFile->GetNativePath(nativePath);

#if (MOZ_PLATFORM_MAEMO == 5) && defined (MOZ_ENABLE_GNOMEVFS)
  if(NS_SUCCEEDED(LaunchDefaultWithDBus(PromiseFlatCString(nativePath).get())))
    return NS_OK;
#endif

#if defined(MOZ_ENABLE_CONTENTACTION)
  QUrl uri = QUrl::fromLocalFile(QString::fromUtf8(nativePath.get()));
  ContentAction::Action action =
    ContentAction::Action::defaultActionForFile(uri, QString(mSchemeOrType.get()));
  if (action.isValid()) {
    action.trigger();
    return NS_OK;
  }
  return NS_ERROR_FAILURE;
#endif

  nsCOMPtr<nsIGIOService> giovfs = do_GetService(NS_GIOSERVICE_CONTRACTID);
  nsAutoCString uriSpec;
  if (giovfs) {
    // nsGIOMimeApp->Launch wants a URI string instead of local file
    nsresult rv;
    nsCOMPtr<nsIIOService> ioservice = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr<nsIURI> uri;
    rv = ioservice->NewFileURI(aFile, getter_AddRefs(uri));
    NS_ENSURE_SUCCESS(rv, rv);
    uri->GetSpec(uriSpec);
  }

  nsCOMPtr<nsIGnomeVFSService> gnomevfs = do_GetService(NS_GNOMEVFSSERVICE_CONTRACTID);
  if (giovfs) {
    nsCOMPtr<nsIGIOMimeApp> app;
    if (NS_SUCCEEDED(giovfs->GetAppForMimeType(mSchemeOrType, getter_AddRefs(app))) && app)
      return app->Launch(uriSpec);
  } else if (gnomevfs) {
    /* Fallback to GnomeVFS */
    nsCOMPtr<nsIGnomeVFSMimeApp> app;
    if (NS_SUCCEEDED(gnomevfs->GetAppForMimeType(mSchemeOrType, getter_AddRefs(app))) && app)
      return app->Launch(nativePath);
  }

  // If we haven't got an app we try to get a valid one by searching for the
  // extension mapped type
  nsRefPtr<nsMIMEInfoBase> mimeInfo = nsGNOMERegistry::GetFromExtension(nativePath);
  if (mimeInfo) {
    nsAutoCString type;
    mimeInfo->GetType(type);
    if (giovfs) {
      nsCOMPtr<nsIGIOMimeApp> app;
      if (NS_SUCCEEDED(giovfs->GetAppForMimeType(type, getter_AddRefs(app))) && app)
        return app->Launch(uriSpec);
    } else if (gnomevfs) {
      nsCOMPtr<nsIGnomeVFSMimeApp> app;
      if (NS_SUCCEEDED(gnomevfs->GetAppForMimeType(type, getter_AddRefs(app))) && app)
        return app->Launch(nativePath);
    }
  }

  if (!mDefaultApplication)
    return NS_ERROR_FILE_NOT_FOUND;

  return LaunchWithIProcess(mDefaultApplication, nativePath);
}
Beispiel #27
0
NS_IMETHODIMP
calDuration::SetIcalString(const nsACString& aIcalString)
{
    mDuration = icaldurationtype_from_string(PromiseFlatCString(aIcalString).get());
    return NS_OK;
}