Exemplo n.º 1
0
/**
 * Display all registered VMs on the screen with some information about each
 *
 * @param virtualBox VirtualBox instance object.
 */
void listVMs(IVirtualBox *virtualBox)
{
    nsresult rc;

    printf("----------------------------------------------------\n");
    printf("VM List:\n\n");

    /*
     * Get the list of all registered VMs
     */
    IMachine **machines = NULL;
    PRUint32 machineCnt = 0;

    rc = virtualBox->GetMachines(&machineCnt, &machines);
    if (NS_SUCCEEDED(rc))
    {
        /*
         * Iterate through the collection
         */
        for (PRUint32 i = 0; i < machineCnt; ++ i)
        {
            IMachine *machine = machines[i];
            if (machine)
            {
                PRBool isAccessible = PR_FALSE;
                machine->GetAccessible(&isAccessible);

                if (isAccessible)
                {
                    nsXPIDLString machineName;
                    machine->GetName(getter_Copies(machineName));
                    char *machineNameAscii = ToNewCString(machineName);
                    printf("\tName:        %s\n", machineNameAscii);
                    free(machineNameAscii);
                }
                else
                {
                    printf("\tName:        <inaccessible>\n");
                }

                nsXPIDLString iid;
                machine->GetId(getter_Copies(iid));
                const char *uuidString = ToNewCString(iid);
                printf("\tUUID:        %s\n", uuidString);
                free((void*)uuidString);

                if (isAccessible)
                {
                    nsXPIDLString configFile;
                    machine->GetSettingsFilePath(getter_Copies(configFile));
                    char *configFileAscii = ToNewCString(configFile);
                    printf("\tConfig file: %s\n", configFileAscii);
                    free(configFileAscii);

                    PRUint32 memorySize;
                    machine->GetMemorySize(&memorySize);
                    printf("\tMemory size: %uMB\n", memorySize);

                    nsXPIDLString typeId;
                    machine->GetOSTypeId(getter_Copies(typeId));
                    IGuestOSType *osType = nsnull;
                    virtualBox->GetGuestOSType (typeId.get(), &osType);
                    nsXPIDLString osName;
                    osType->GetDescription(getter_Copies(osName));
                    char *osNameAscii = ToNewCString(osName);
                    printf("\tGuest OS:    %s\n\n", osNameAscii);
                    free(osNameAscii);
                    osType->Release();
                }

                /* don't forget to release the objects in the array... */
                machine->Release();
            }
        }
    }
    printf("----------------------------------------------------\n\n");
}
Exemplo n.º 2
0
// wrappers for ldap_modify_ext
//
nsresult
nsLDAPOperation::ModifyExt(const char *base,
                           nsIArray *mods,
                           LDAPControl **serverctrls,
                           LDAPControl **clientctrls)
{
  if (mMessageListener == 0) {
    NS_ERROR("nsLDAPOperation::ModifyExt(): mMessageListener not set");
    return NS_ERROR_NOT_INITIALIZED;
  }

  LDAPMod **attrs = 0;
  int retVal = 0;
  PRUint32 modCount = 0;
  nsresult rv = mods->GetLength(&modCount);
  NS_ENSURE_SUCCESS(rv, rv);
  if (modCount && mods) {
    attrs = static_cast<LDAPMod **>(nsMemory::Alloc((modCount + 1) *
                                                       sizeof(LDAPMod *)));
    if (!attrs) {
      NS_ERROR("nsLDAPOperation::ModifyExt: out of memory ");
      return NS_ERROR_OUT_OF_MEMORY;
    }

    nsCAutoString type;
    PRUint32 index;
    for (index = 0; index < modCount && NS_SUCCEEDED(rv); ++index) {
      attrs[index] = new LDAPMod();
      if (!attrs[index])
        return NS_ERROR_OUT_OF_MEMORY;

      nsCOMPtr<nsILDAPModification> modif(do_QueryElementAt(mods, index, &rv));
      if (NS_FAILED(rv))
        break;

      PRInt32 operation;
      nsresult rv = modif->GetOperation(&operation);
      if (NS_FAILED(rv))
        break;

      attrs[index]->mod_op = operation | LDAP_MOD_BVALUES;

      rv = modif->GetType(type);
      if (NS_FAILED(rv))
        break;

      attrs[index]->mod_type = ToNewCString(type);

      rv = CopyValues(modif, &attrs[index]->mod_bvalues);
      if (NS_FAILED(rv))
        break;
    }

    if (NS_SUCCEEDED(rv)) {
      attrs[modCount] = 0;

      retVal = ldap_modify_ext(mConnectionHandle, base, attrs,
                               serverctrls, clientctrls, &mMsgID);
    }
    else
      // reset the modCount so we correctly free the array.
      modCount = index;

  }

  for (PRUint32 counter = 0; counter < modCount; ++counter)
    delete attrs[counter];

  nsMemory::Free(attrs);

  return NS_FAILED(rv) ? rv : TranslateLDAPErrorToNSError(retVal);
}
NS_INTERFACE_MAP_END

//----------------------------------------------------------------------
// nsISVGValue methods:

NS_IMETHODIMP
nsSVGPreserveAspectRatio::SetValueString(const nsAString& aValue)
{
  char* str = ToNewCString(aValue);
  if (!str) return NS_ERROR_OUT_OF_MEMORY;

  nsresult rv = NS_OK;

  char* rest = str;
  char* token;
  const char* delimiters = "\x20\x9\xD\xA";
  PRUint16 align, meetOrSlice;

  token = nsCRT::strtok(rest, delimiters, &rest);

  if (token && !strcmp(token, "defer"))
    // Ignore: only applicable for preserveAspectRatio on 'image' elements
    token = nsCRT::strtok(rest, delimiters, &rest);

  if (token) {
    if (!strcmp(token, "none"))
      align = SVG_PRESERVEASPECTRATIO_NONE;
    else if (!strcmp(token, "xMinYMin"))
      align = SVG_PRESERVEASPECTRATIO_XMINYMIN;
    else if (!strcmp(token, "xMidYMin"))
      align = SVG_PRESERVEASPECTRATIO_XMIDYMIN;
    else if (!strcmp(token, "xMaxYMin"))
      align = SVG_PRESERVEASPECTRATIO_XMAXYMIN;
    else if (!strcmp(token, "xMinYMid"))
      align = SVG_PRESERVEASPECTRATIO_XMINYMID;
    else if (!strcmp(token, "xMidYMid"))
      align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
    else if (!strcmp(token, "xMaxYMid"))
      align = SVG_PRESERVEASPECTRATIO_XMAXYMID;
    else if (!strcmp(token, "xMinYMax"))
      align = SVG_PRESERVEASPECTRATIO_XMINYMAX;
    else if (!strcmp(token, "xMidYMax"))
      align = SVG_PRESERVEASPECTRATIO_XMIDYMAX;
    else if (!strcmp(token, "xMaxYMax"))
      align = SVG_PRESERVEASPECTRATIO_XMAXYMAX;
    else
      rv = NS_ERROR_FAILURE;

    if (NS_SUCCEEDED(rv)) {
      token = nsCRT::strtok(rest, delimiters, &rest);
      if (token) {
        if (!strcmp(token, "meet"))
          meetOrSlice = SVG_MEETORSLICE_MEET;
        else if (!strcmp(token, "slice"))
          meetOrSlice = SVG_MEETORSLICE_SLICE;
        else
          rv = NS_ERROR_FAILURE;
      }
      else
        meetOrSlice = SVG_MEETORSLICE_MEET;
    }
  }
  else  // align not specified
    rv = NS_ERROR_FAILURE;

  if (nsCRT::strtok(rest, delimiters, &rest))  // there's more
    rv = NS_ERROR_FAILURE;

  if (NS_SUCCEEDED(rv)) {
    WillModify();
    mAlign = align;
    mMeetOrSlice = meetOrSlice;
    DidModify();
  }

  nsMemory::Free(str);

  return rv;
}
Exemplo n.º 4
0
static char *
MimeMessage_partial_message_html(const char *data, void *closure,
                 MimeHeaders *headers)
{
  MimeMessage *msg = (MimeMessage *)closure;
  nsCAutoString orig_url(data);
  char *uidl = MimeHeaders_get(headers, HEADER_X_UIDL, PR_FALSE, PR_FALSE);
  char *msgId = MimeHeaders_get(headers, HEADER_MESSAGE_ID, PR_FALSE,
                  PR_FALSE);
  char *msgIdPtr = PL_strstr(msgId, "<");
  int msgBase;

  PRInt32 pos = orig_url.Find("mailbox-message");
  if (pos != -1)
    orig_url.Cut(pos + 7, 8);

  pos = orig_url.Find("#");
  if (pos != -1)
    orig_url.Replace(pos, 1, "?number=", 8);

  if (msgIdPtr)
    msgIdPtr++;
  else
    msgIdPtr = msgId;
  char *gtPtr = PL_strstr(msgIdPtr, ">");
  if (gtPtr)
    *gtPtr = 0;

  msgBase = (msg->bodyLength > MSG_LINEBREAK_LEN) ? MIME_MSG_PARTIAL_FMT_1 : MIME_MSG_PARTIAL_FMT2_1;

  nsCString partialMsgHtml;
  nsCString item;

  item.Adopt(MimeGetStringByID(msgBase));
  partialMsgHtml += item;

  item.Adopt(MimeGetStringByID(msgBase+1));
  partialMsgHtml += item;

  partialMsgHtml.Append(orig_url);

  if (msgIdPtr) {
    partialMsgHtml.AppendLiteral("&messageid=");

    MsgEscapeString(nsDependentCString(msgIdPtr), nsINetUtil::ESCAPE_URL_PATH,
                    item);

    partialMsgHtml.Append(item);
  }

  if (uidl) {
    partialMsgHtml.AppendLiteral("&uidl=");

    MsgEscapeString(nsDependentCString(uidl), nsINetUtil::ESCAPE_XALPHAS,
                    item);

    partialMsgHtml.Append(item);
  }

  item.Adopt(MimeGetStringByID(msgBase+2));
  partialMsgHtml += item;

  return ToNewCString(partialMsgHtml);
}
// walks the graph using a breadth-first-search algorithm which generates a discovered
// verticies tree. This tree is then walked up (from destination vertex, to origin vertex)
// and each link in the chain is added to an nsStringArray. A direct lookup for the given
// CONTRACTID should be made prior to calling this method in an attempt to find a direct
// converter rather than walking the graph.
nsresult
nsStreamConverterService::FindConverter(const char *aContractID, nsTArray<nsCString> **aEdgeList) {
    nsresult rv;
    if (!aEdgeList) return NS_ERROR_NULL_POINTER;
    *aEdgeList = nullptr;

    // walk the graph in search of the appropriate converter.

    int32_t vertexCount = mAdjacencyList->Count();
    if (0 >= vertexCount) return NS_ERROR_FAILURE;

    // Create a corresponding color table for each vertex in the graph.
    nsObjectHashtable lBFSTable(nullptr, nullptr, DeleteBFSEntry, nullptr);
    mAdjacencyList->Enumerate(InitBFSTable, &lBFSTable);

    NS_ASSERTION(lBFSTable.Count() == vertexCount, "strmconv BFS table init problem");

    // This is our source vertex; our starting point.
    nsAutoCString fromC, toC;
    rv = ParseFromTo(aContractID, fromC, toC);
    if (NS_FAILED(rv)) return rv;

    nsCStringKey *source = new nsCStringKey(fromC.get());
    if (!source) return NS_ERROR_OUT_OF_MEMORY;

    SCTableData *data = (SCTableData*)lBFSTable.Get(source);
    if (!data) {
        delete source;
        return NS_ERROR_FAILURE;
    }

    BFSState *state = data->data.state;

    state->color = gray;
    state->distance = 0;
    CStreamConvDeallocator *dtorFunc = new CStreamConvDeallocator();
    if (!dtorFunc) {
        delete source;
        return NS_ERROR_OUT_OF_MEMORY;
    }

    nsDeque grayQ(dtorFunc);

    // Now generate the shortest path tree.
    grayQ.Push(source);
    while (0 < grayQ.GetSize()) {
        nsCStringKey *currentHead = (nsCStringKey*)grayQ.PeekFront();
        SCTableData *data2 = (SCTableData*)mAdjacencyList->Get(currentHead);
        if (!data2) return NS_ERROR_FAILURE;

        nsCOMArray<nsIAtom> *edges = data2->data.edges;
        NS_ASSERTION(edges, "something went wrong with BFS strmconv algorithm");
        if (!edges) return NS_ERROR_FAILURE;

        // Get the state of the current head to calculate the distance of each
        // reachable vertex in the loop.
        data2 = (SCTableData*)lBFSTable.Get(currentHead);
        if (!data2) return NS_ERROR_FAILURE;

        BFSState *headVertexState = data2->data.state;
        NS_ASSERTION(headVertexState, "problem with the BFS strmconv algorithm");
        if (!headVertexState) return NS_ERROR_FAILURE;

        int32_t edgeCount = edges->Count();

        for (int32_t i = 0; i < edgeCount; i++) {
            nsIAtom* curVertexAtom = edges->ObjectAt(i);
            nsAutoString curVertexStr;
            curVertexAtom->ToString(curVertexStr);
            nsCStringKey *curVertex = new nsCStringKey(ToNewCString(curVertexStr), 
                                        curVertexStr.Length(), nsCStringKey::OWN);
            if (!curVertex) return NS_ERROR_OUT_OF_MEMORY;

            SCTableData *data3 = (SCTableData*)lBFSTable.Get(curVertex);
            if (!data3) {
                delete curVertex;
                return NS_ERROR_FAILURE;
            }
            BFSState *curVertexState = data3->data.state;
            NS_ASSERTION(curVertexState, "something went wrong with the BFS strmconv algorithm");
            if (!curVertexState) return NS_ERROR_FAILURE;

            if (white == curVertexState->color) {
                curVertexState->color = gray;
                curVertexState->distance = headVertexState->distance + 1;
                curVertexState->predecessor = (nsCStringKey*)currentHead->Clone();
                if (!curVertexState->predecessor) {
                    delete curVertex;
                    return NS_ERROR_OUT_OF_MEMORY;
                }
                grayQ.Push(curVertex);
            } else {
                delete curVertex; // if this vertex has already been discovered, we don't want
                                  // to leak it. (non-discovered vertex's get cleaned up when
                                  // they're popped).
            }
        }
        headVertexState->color = black;
        nsCStringKey *cur = (nsCStringKey*)grayQ.PopFront();
        delete cur;
        cur = nullptr;
    }
    // The shortest path (if any) has been generated and is represetned by the chain of 
    // BFSState->predecessor keys. Start at the bottom and work our way up.

    // first parse out the FROM and TO MIME-types being registered.

    nsAutoCString fromStr, toStr;
    rv = ParseFromTo(aContractID, fromStr, toStr);
    if (NS_FAILED(rv)) return rv;

    // get the root CONTRACTID
    nsAutoCString ContractIDPrefix(NS_ISTREAMCONVERTER_KEY);
    nsTArray<nsCString> *shortestPath = new nsTArray<nsCString>();
    if (!shortestPath) return NS_ERROR_OUT_OF_MEMORY;

    nsCStringKey toMIMEType(toStr);
    data = (SCTableData*)lBFSTable.Get(&toMIMEType);
    if (!data) {
        // If this vertex isn't in the BFSTable, then no-one has registered for it,
        // therefore we can't do the conversion.
        delete shortestPath;
        return NS_ERROR_FAILURE;
    }

    while (data) {
        BFSState *curState = data->data.state;

        nsCStringKey *key = data->key;
        
        if (fromStr.Equals(key->GetString())) {
            // found it. We're done here.
            *aEdgeList = shortestPath;
            return NS_OK;
        }

        // reconstruct the CONTRACTID.
        // Get the predecessor.
        if (!curState->predecessor) break; // no predecessor
        SCTableData *predecessorData = (SCTableData*)lBFSTable.Get(curState->predecessor);

        if (!predecessorData) break; // no predecessor, chain doesn't exist.

        // build out the CONTRACTID.
        nsAutoCString newContractID(ContractIDPrefix);
        newContractID.AppendLiteral("?from=");

        nsCStringKey *predecessorKey = predecessorData->key;
        newContractID.Append(predecessorKey->GetString());

        newContractID.AppendLiteral("&to=");
        newContractID.Append(key->GetString());
    
        // Add this CONTRACTID to the chain.
        rv = shortestPath->AppendElement(newContractID) ? NS_OK : NS_ERROR_FAILURE;  // XXX this method incorrectly returns a bool
        NS_ASSERTION(NS_SUCCEEDED(rv), "AppendElement failed");

        // move up the tree.
        data = predecessorData;
    }
    delete shortestPath;
    return NS_ERROR_FAILURE; // couldn't find a stream converter or chain.
}
Exemplo n.º 6
0
NS_IMETHODIMP
nsScriptError::GetCategory(char **result) {
    *result = ToNewCString(mCategory);
    return NS_OK;
}
Exemplo n.º 7
0
nsresult
nsOperaProfileMigrator::CopyPreferences(PRBool aReplace)
{
    nsresult rv;

    nsCOMPtr<nsIFile> operaPrefs;
    mOperaProfile->Clone(getter_AddRefs(operaPrefs));
    operaPrefs->Append(OPERA_PREFERENCES_FILE_NAME);

    nsCOMPtr<nsILocalFile> lf(do_QueryInterface(operaPrefs));
    NS_ENSURE_TRUE(lf, NS_ERROR_UNEXPECTED);

    nsINIParser parser;
    rv = parser.Init(lf);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIPrefBranch> branch(do_GetService(NS_PREFSERVICE_CONTRACTID));

    // Traverse the standard transforms
    PrefTransform* transform;
    PrefTransform* end = gTransforms + sizeof(gTransforms)/sizeof(PrefTransform);

    const char* lastSectionName = nsnull;
    for (transform = gTransforms; transform < end; ++transform) {
        if (transform->sectionName)
            lastSectionName = transform->sectionName;

        if (transform->type == _OPM(COLOR)) {
            char* colorString = nsnull;
            nsresult rv = ParseColor(parser, lastSectionName, &colorString);
            if (NS_SUCCEEDED(rv)) {
                transform->stringValue = colorString;

                transform->prefHasValue = PR_TRUE;
                transform->prefSetterFunc(transform, branch);
            }
            if (colorString)
                free(colorString);
        }
        else {
            nsCAutoString val;
            rv = parser.GetString(lastSectionName,
                                  transform->keyName,
                                  val);
            if (NS_SUCCEEDED(rv)) {
                nsresult strerr;
                switch (transform->type) {
                case _OPM(STRING):
                    transform->stringValue = ToNewCString(val);
                    break;
                case _OPM(INT): {
                    transform->intValue = val.ToInteger(&strerr);
                }
                break;
                case _OPM(BOOL): {
                    transform->boolValue = val.ToInteger(&strerr) != 0;
                }
                break;
                default:
                    break;
                }
                transform->prefHasValue = PR_TRUE;
                transform->prefSetterFunc(transform, branch);
                if (transform->type == _OPM(STRING) && transform->stringValue) {
                    NS_Free(transform->stringValue);
                    transform->stringValue = nsnull;
                }
            }
        }
    }

    // Copy Proxy Settings
    CopyProxySettings(parser, branch);

    // Copy User Content Sheet
    if (aReplace)
        CopyUserContentSheet(parser);

    return NS_OK;
}
NS_IMETHODIMP
nsAbLDAPAutoCompFormatter::GetAttributes(PRUint32 *aCount, char ** *aAttrs)
{
    if (!aCount || !aAttrs) {
        return NS_ERROR_INVALID_POINTER;
    }

    nsCStringArray mSearchAttrs;
    nsresult rv = ProcessFormat(mNameFormat, 0, 0, &mSearchAttrs);
    if (NS_FAILED(rv)) {
        NS_WARNING("nsAbLDAPAutoCompFormatter::SetNameFormat(): "
                   "ProcessFormat() failed");
        return rv;
    }
    rv = ProcessFormat(mAddressFormat, 0, 0, &mSearchAttrs);
    if (NS_FAILED(rv)) {
        NS_WARNING("nsAbLDAPAutoCompFormatter::SetNameFormat(): "
                   "ProcessFormat() failed");
        return rv;
    }
    rv = ProcessFormat(mCommentFormat, 0, 0, &mSearchAttrs);
    if (NS_FAILED(rv)) {
        NS_WARNING("nsAbLDAPAutoCompFormatter::SetNameFormat(): "
                   "ProcessFormat() failed");
        return rv;
    }

    // none of the formatting templates require any LDAP attributes
    //
    PRUint32 count = mSearchAttrs.Count();   // size of XPCOM array we'll need
    if (!count) {
        NS_ERROR("nsAbLDAPAutoCompFormatter::GetAttributes(): "
                 "current output format (if set) requires no search "
                 "attributes");
        return NS_ERROR_NOT_INITIALIZED;
    }

    // build up the raw XPCOM array to return
    //
    PRUint32 rawSearchAttrsSize = 0;        // grown as XPCOM array is built
    char **rawSearchAttrs = 
        static_cast<char **>(nsMemory::Alloc(count * sizeof(char *)));
    if (!rawSearchAttrs) {
        NS_ERROR("nsAbLDAPAutoCompFormatter::GetAttributes(): out of "
		 "memory");
        return NS_ERROR_OUT_OF_MEMORY;
    }

    // Loop through the string array, and build up the C-array.
    //
    while (rawSearchAttrsSize < count) {
        if (!(rawSearchAttrs[rawSearchAttrsSize] = 
              ToNewCString(*(mSearchAttrs.CStringAt(rawSearchAttrsSize))))) {
            NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(rawSearchAttrsSize, 
                                                  rawSearchAttrs);
            NS_ERROR("nsAbLDAPAutoCompFormatter::GetAttributes(): out "
		     "of memory");
            return NS_ERROR_OUT_OF_MEMORY;
        }
        rawSearchAttrsSize++;
    }

    *aCount = rawSearchAttrsSize;
    *aAttrs = rawSearchAttrs;

    return NS_OK;

}
Exemplo n.º 9
0
void Area::ParseCoords(const nsAString& aSpec)
{
  char* cp = ToNewCString(aSpec);
  if (cp) {
    char *tptr;
    char *n_str;
    PRInt32 i, cnt;
    PRInt32 *value_list;

    /*
     * Nothing in an empty list
     */
    mNumCoords = 0;
    mCoords = nsnull;
    if (*cp == '\0')
    {
      return;
    }

    /*
     * Skip beginning whitespace, all whitespace is empty list.
     */
    n_str = cp;
    while (is_space(*n_str))
    {
      n_str++;
    }
    if (*n_str == '\0')
    {
      return;
    }

    /*
     * Make a pass where any two numbers separated by just whitespace
     * are given a comma separator.  Count entries while passing.
     */
    cnt = 0;
    while (*n_str != '\0')
    {
      PRBool has_comma;

      /*
       * Skip to a separator
       */
      tptr = n_str;
      while (!is_space(*tptr) && *tptr != ',' && *tptr != '\0')
      {
        tptr++;
      }
      n_str = tptr;

      /*
       * If no more entries, break out here
       */
      if (*n_str == '\0')
      {
        break;
      }

      /*
       * Skip to the end of the separator, noting if we have a
       * comma.
       */
      has_comma = PR_FALSE;
      while (is_space(*tptr) || *tptr == ',')
      {
        if (*tptr == ',')
        {
          if (!has_comma)
          {
            has_comma = PR_TRUE;
          }
          else
          {
            break;
          }
        }
        tptr++;
      }
      /*
       * If this was trailing whitespace we skipped, we are done.
       */
      if ((*tptr == '\0') && !has_comma)
      {
        break;
      }
      /*
       * Else if the separator is all whitespace, and this is not the
       * end of the string, add a comma to the separator.
       */
      else if (!has_comma)
      {
        *n_str = ',';
      }

      /*
       * count the entry skipped.
       */
      cnt++;

      n_str = tptr;
    }
    /*
     * count the last entry in the list.
     */
    cnt++;

    /*
     * Allocate space for the coordinate array.
     */
    value_list = new nscoord[cnt];
    if (!value_list)
    {
      return;
    }

    /*
     * Second pass to copy integer values into list.
     */
    tptr = cp;
    for (i=0; i<cnt; i++)
    {
      char *ptr;

      ptr = strchr(tptr, ',');
      if (ptr)
      {
        *ptr = '\0';
      }
      /*
       * Strip whitespace in front of number because I don't
       * trust atoi to do it on all platforms.
       */
      while (is_space(*tptr))
      {
        tptr++;
      }
      if (*tptr == '\0')
      {
        value_list[i] = 0;
      }
      else
      {
        value_list[i] = (nscoord) ::atoi(tptr);
      }
      if (ptr)
      {
        *ptr = ',';
        tptr = ptr + 1;
      }
    }

    mNumCoords = cnt;
    mCoords = value_list;

    NS_Free(cp);
  }
}
Exemplo n.º 10
0
/* read only attribute string name; */
NS_IMETHODIMP nsAbDirectoryQueryPropertyValue::GetName(char*  *aName)
{
    *aName = mName.IsEmpty() ? 0 : ToNewCString(mName);

    return NS_OK;
}
Exemplo n.º 11
0
nsresult writeoutto(const char* i_pURL, char** o_Result, int32_t urlFactory = URL_FACTORY_DEFAULT)
{
    if (!o_Result || !i_pURL)
        return NS_ERROR_FAILURE;
    *o_Result = 0;
    nsCOMPtr<nsIURI> pURL;
    nsresult result = NS_OK;

    switch (urlFactory) {
        case URL_FACTORY_STDURL: {
            nsIURI* url;
            result = CallCreateInstance(kStdURLCID, &url);
            if (NS_FAILED(result))
            {
                printf("CreateInstance failed\n");
                return NS_ERROR_FAILURE;
            }
            pURL = url;
            pURL->SetSpec(nsDependentCString(i_pURL));
            break;
        }
        case URL_FACTORY_DEFAULT: {
            nsCOMPtr<nsIIOService> pService = 
                     do_GetService(kIOServiceCID, &result);
            if (NS_FAILED(result)) 
            {
                printf("Service failed!\n");
                return NS_ERROR_FAILURE;
            }   
            result = pService->NewURI(nsDependentCString(i_pURL), nullptr, nullptr, getter_AddRefs(pURL));
        }
    }

    nsCString output;
    if (NS_SUCCEEDED(result))
    {
        nsCOMPtr<nsIURL> tURL = do_QueryInterface(pURL);
        nsAutoCString temp;
        int32_t port;
        nsresult rv;

#define RESULT() NS_SUCCEEDED(rv) ? temp.get() : ""

        rv = tURL->GetScheme(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetUsername(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetPassword(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetHost(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetPort(&port);
        char portbuffer[40];
        snprintf_literal(portbuffer, "%d", port);
        output.Append(portbuffer);
        output += ',';
        rv = tURL->GetDirectory(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetFileBaseName(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetFileExtension(temp);
        output += RESULT();
        output += ',';
        // removed with https://bugzilla.mozilla.org/show_bug.cgi?id=665706
        // rv = tURL->GetParam(temp); 
        // output += RESULT();
        output += ',';
        rv = tURL->GetQuery(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetRef(temp);
        output += RESULT();
        output += ',';
        rv = tURL->GetSpec(temp);
        output += RESULT();
        *o_Result = ToNewCString(output);
    } else {
        output = "Can not create URL";
        *o_Result = ToNewCString(output);
    }
    return NS_OK;
}
Exemplo n.º 12
0
nsresult nsMsgI18NSaveAsCharset(const char* contentType, const char *charset, 
                                const char16_t* inString, char** outString, 
                                char **fallbackCharset, bool *isAsciiOnly)
{
  NS_ENSURE_ARG_POINTER(contentType);
  NS_ENSURE_ARG_POINTER(charset);
  NS_ENSURE_ARG_POINTER(inString);
  NS_ENSURE_ARG_POINTER(outString);

  *outString = nullptr;

  if (NS_IsAscii(inString)) {
    if (isAsciiOnly)
      *isAsciiOnly = true;
    *outString = ToNewCString(NS_LossyConvertUTF16toASCII(inString));
    return (nullptr != *outString) ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
  }
  if (isAsciiOnly)
    *isAsciiOnly = false;

  bool bTEXT_HTML = false;
  nsresult res;

  if (!PL_strcasecmp(contentType, TEXT_HTML)) {
    bTEXT_HTML = true;
  }
  else if (PL_strcasecmp(contentType, TEXT_PLAIN)) {
    return NS_ERROR_ILLEGAL_VALUE;  // not supported type
  }

  nsCOMPtr <nsICharsetConverterManager> ccm =
    do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &res);
  NS_ENSURE_SUCCESS(res, res);

  nsAutoCString charsetName;
  res = ccm->GetCharsetAlias(charset, charsetName);
  NS_ENSURE_SUCCESS(res, res);

  nsCOMPtr <nsISaveAsCharset> conv = do_CreateInstance(NS_SAVEASCHARSET_CONTRACTID, &res);
  NS_ENSURE_SUCCESS(res, res);

  // First try to transliterate, if that fails use '?' for "bad" chars.
  res = conv->Init(charsetName.get(),
                   nsISaveAsCharset::attr_FallbackQuestionMark +
                     nsISaveAsCharset::attr_EntityNone,
                   nsIEntityConverter::transliterate);
  NS_ENSURE_SUCCESS(res, res);

  const char16_t *input = inString;

  // Convert to charset
  res = conv->Convert(input, outString);

  // If the converer cannot encode to the charset,
  // then fallback to pref sepcified charsets.
  if (NS_ERROR_UENC_NOMAPPING == res && !bTEXT_HTML && fallbackCharset) {
    nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &res));
    NS_ENSURE_SUCCESS(res, res);

    nsAutoCString prefString("intl.fallbackCharsetList.");
    prefString.Append(charset);
    nsCString fallbackList;
    res = prefBranch->GetCharPref(prefString.get(), getter_Copies(fallbackList));
    // do the fallback only if there is a pref for the charset
    if (NS_FAILED(res) || fallbackList.IsEmpty())
      return NS_ERROR_UENC_NOMAPPING;

    res = conv->Init(fallbackList.get(), 
                     nsISaveAsCharset::attr_FallbackQuestionMark + 
                     nsISaveAsCharset::attr_EntityAfterCharsetConv +
                     nsISaveAsCharset::attr_CharsetFallback, 
                     nsIEntityConverter::transliterate);
    NS_ENSURE_SUCCESS(res, res);

    // free whatever we have now
    PR_FREEIF(*outString);  

    res = conv->Convert(input, outString);
    NS_ENSURE_SUCCESS(res, res);

    // get the actual charset used for the conversion
    if (NS_FAILED(conv->GetCharset(fallbackCharset)))
      *fallbackCharset = nullptr;
  }
  // Exclude stateful charset which is 7 bit but not ASCII only.
  else if (isAsciiOnly && *outString &&
           !nsMsgI18Nstateful_charset(charsetName.get()))
    *isAsciiOnly = NS_IsAscii(*outString);

  return res;
}
Exemplo n.º 13
0
// nsIStreamListener implementation
NS_IMETHODIMP
nsFTPDirListingConv::OnDataAvailable(nsIRequest* request, nsISupports *ctxt,
                                  nsIInputStream *inStr, uint32_t sourceOffset, uint32_t count) {
    NS_ASSERTION(request, "FTP dir listing stream converter needs a request");
    
    nsresult rv;

    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    
    uint32_t read, streamLen;

    uint64_t streamLen64;
    rv = inStr->Available(&streamLen64);
    NS_ENSURE_SUCCESS(rv, rv);
    streamLen = (uint32_t)NS_MIN(streamLen64, uint64_t(PR_UINT32_MAX - 1));

    nsAutoArrayPtr<char> buffer(new char[streamLen + 1]);
    NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

    rv = inStr->Read(buffer, streamLen, &read);
    NS_ENSURE_SUCCESS(rv, rv);

    // the dir listings are ascii text, null terminate this sucker.
    buffer[streamLen] = '\0';

    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("nsFTPDirListingConv::OnData(request = %x, ctxt = %x, inStr = %x, sourceOffset = %d, count = %d)\n", request, ctxt, inStr, sourceOffset, count));

    if (!mBuffer.IsEmpty()) {
        // we have data left over from a previous OnDataAvailable() call.
        // combine the buffers so we don't lose any data.
        mBuffer.Append(buffer);

        buffer = new char[mBuffer.Length()+1];
        NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

        strncpy(buffer, mBuffer.get(), mBuffer.Length()+1);
        mBuffer.Truncate();
    }

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer.get()) );
#else
    printf("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer);
#endif // DEBUG_dougt

    nsCAutoString indexFormat;
    if (!mSentHeading) {
        // build up the 300: line
        nsCOMPtr<nsIURI> uri;
        rv = channel->GetURI(getter_AddRefs(uri));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = GetHeaders(indexFormat, uri);
        NS_ENSURE_SUCCESS(rv, rv);

        mSentHeading = true;
    }

    char *line = buffer;
    line = DigestBufferLines(line, indexFormat);

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", 
        indexFormat.Length(), indexFormat.get()) );
#else
    char *unescData = ToNewCString(indexFormat);
    NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY);
    
    nsUnescape(unescData);
    printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData);
    nsMemory::Free(unescData);
#endif // DEBUG_dougt

    // if there's any data left over, buffer it.
    if (line && *line) {
        mBuffer.Append(line);
        PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n",
            PL_strlen(line), line) );
    }

    // send the converted data out.
    nsCOMPtr<nsIInputStream> inputData;

    rv = NS_NewCStringInputStream(getter_AddRefs(inputData), indexFormat);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mFinalListener->OnDataAvailable(request, ctxt, inputData, 0, indexFormat.Length());

    return rv;
}
nsresult
nsFtpProtocolHandler::InsertConnection(nsIURI *aKey, nsFtpControlConnection *aConn)
{
    NS_ASSERTION(aConn, "null pointer");
    NS_ASSERTION(aKey, "null pointer");

    if (aConn->mSessionId != mSessionId)
        return NS_ERROR_FAILURE;

    nsCAutoString spec;
    aKey->GetPrePath(spec);

    LOG(("FTP:inserting connection for %s\n", spec.get()));

    nsresult rv;
    nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1", &rv);
    if (NS_FAILED(rv)) return rv;
    
    timerStruct* ts = new timerStruct();
    if (!ts)
        return NS_ERROR_OUT_OF_MEMORY;

    rv = timer->InitWithFuncCallback(nsFtpProtocolHandler::Timeout,
                                     ts,
                                     mIdleTimeout*1000,
                                     nsITimer::TYPE_REPEATING_SLACK);
    if (NS_FAILED(rv)) {
        delete ts;
        return rv;
    }
    
    ts->key = ToNewCString(spec);
    if (!ts->key) {
        delete ts;
        return NS_ERROR_OUT_OF_MEMORY;
    }

    NS_ADDREF(aConn);
    ts->conn = aConn;
    ts->timer = timer;

    //
    // limit number of idle connections.  if limit is reached, then prune
    // eldest connection with matching key.  if none matching, then prune
    // eldest connection.
    //
    if (mRootConnectionList.Length() == IDLE_CONNECTION_LIMIT) {
        PRUint32 i;
        for (i=0;i<mRootConnectionList.Length();++i) {
            timerStruct *candidate = mRootConnectionList[i];
            if (strcmp(candidate->key, ts->key) == 0) {
                mRootConnectionList.RemoveElementAt(i);
                delete candidate;
                break;
            }
        }
        if (mRootConnectionList.Length() == IDLE_CONNECTION_LIMIT) {
            timerStruct *eldest = mRootConnectionList[0];
            mRootConnectionList.RemoveElementAt(0);
            delete eldest;
        }
    }

    mRootConnectionList.AppendElement(ts);
    return NS_OK;
}
/*
 * Class:     org_mozilla_webclient_impl_wrapper_0005fnative_CurrentPageImpl
 * Method:    nativeGetCurrentURL
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_org_mozilla_webclient_impl_wrapper_1native_CurrentPageImpl_nativeGetCurrentURL
(JNIEnv *env, jobject obj, jint nativeBCPtr)
{
    JNIEnv  *   pEnv = env;
    jobject     jobj = obj;
    char    *   charResult = nsnull;
    PRInt32 currentIndex;
    jstring     urlString = nsnull;
    nsresult rv = NS_ERROR_NULL_POINTER;

    NativeBrowserControl* nativeBrowserControl = (NativeBrowserControl *) nativeBCPtr;

    if (nativeBrowserControl == nsnull) {
        ::util_ThrowExceptionToJava(env, "Exception: null nativeBCPtr passed to raptorWebShellGetURL");
        return nsnull;
    }

    nsCOMPtr<nsISHistory> sHistory;
    rv = nativeBrowserControl->mNavigation->GetSessionHistory(getter_AddRefs(sHistory));
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "Exception: Can't get SessionHistory");
        return nsnull;
    }
    
    rv = sHistory->GetIndex(&currentIndex);
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "Exception: Can't get current index from SessionHistory");
        return nsnull;
    }
    
    nsIHistoryEntry * Entry;
    nsIURI *URI;
    rv = sHistory->GetEntryAtIndex(currentIndex, PR_FALSE, &Entry);
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "Exception: Can't get history entry for current index");
        return nsnull;
    }
    
    rv = Entry->GetURI(&URI);
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "Exception: Can't get URI from History Entry");
        return nsnull;
    }
    
    nsCString urlSpecString;
    
    rv = URI->GetSpec(urlSpecString);
    if (NS_FAILED(rv)) {
        ::util_ThrowExceptionToJava(env, "Exception: Can't get url spec from URI");
        return nsnull;
    }
    charResult = ToNewCString(urlSpecString);
    
    if (charResult != nsnull) {
        urlString = ::util_NewStringUTF(env, (const char *) charResult);
    }
    else {
        ::util_ThrowExceptionToJava(env, "raptorWebShellGetURL Exception: GetURL() returned NULL");
        return nsnull;
    }
    
    nsMemory::Free(charResult);
    
    return urlString;
}
Exemplo n.º 16
0
// contructor for CWAB object
//
// pszFileName - FileName of WAB file to open
//          if no file name is specified, opens the default
//
CWAB::CWAB(nsILocalFile *file)
{
    // Here we load the WAB Object and initialize it
    m_pUniBuff = NULL;
  m_uniBuffLen = 0;

  m_bInitialized = PR_FALSE;
  m_lpAdrBook = NULL;
  m_lpWABObject = NULL;
  m_hinstWAB = NULL;

    {
        TCHAR  szWABDllPath[MAX_PATH];
        DWORD  dwType = 0;
        ULONG  cbData = sizeof(szWABDllPath);
        HKEY hKey = NULL;

        *szWABDllPath = '\0';

        // First we look under the default WAB DLL path location in the
        // Registry.
        // WAB_DLL_PATH_KEY is defined in wabapi.h
        //
        if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, WAB_DLL_PATH_KEY, 0, KEY_READ, &hKey))
            RegQueryValueEx( hKey, "", NULL, &dwType, (LPBYTE) szWABDllPath, &cbData);

        if(hKey) RegCloseKey(hKey);

        // if the Registry came up blank, we do a loadlibrary on the wab32.dll
        // WAB_DLL_NAME is defined in wabapi.h
        //
        m_hinstWAB = LoadLibrary( (lstrlen(szWABDllPath)) ? szWABDllPath : WAB_DLL_NAME );
    }

    if(m_hinstWAB)
    {
        // if we loaded the dll, get the entry point
        //
        m_lpfnWABOpen = (LPWABOPEN) GetProcAddress(m_hinstWAB, "WABOpen");

        if(m_lpfnWABOpen)
        {
          char    fName[2] = {0, 0};
            HRESULT hr = E_FAIL;
            WAB_PARAM wp = {0};
            wp.cbSize = sizeof(WAB_PARAM);
            if (file != nsnull) {
                nsCString path;
              file->GetNativePath(path);
              wp.szFileName = (LPTSTR) ToNewCString(path);
            }
            else
              wp.szFileName = (LPTSTR) fName;

            // if we choose not to pass in a WAB_PARAM object,
            // the default WAB file will be opened up
            //
            hr = m_lpfnWABOpen(&m_lpAdrBook,&m_lpWABObject,&wp,0);

            if(!hr)
                m_bInitialized = TRUE;

        }
    }

}
Exemplo n.º 17
0
void
nsXBLPrototypeHandler::ConstructPrototype(nsIContent* aKeyElement, 
                                          const PRUnichar* aEvent,
                                          const PRUnichar* aPhase,
                                          const PRUnichar* aAction,
                                          const PRUnichar* aCommand,
                                          const PRUnichar* aKeyCode,
                                          const PRUnichar* aCharCode,
                                          const PRUnichar* aModifiers,
                                          const PRUnichar* aButton,
                                          const PRUnichar* aClickCount,
                                          const PRUnichar* aGroup,
                                          const PRUnichar* aPreventDefault,
                                          const PRUnichar* aAllowUntrusted)
{
  mType = 0;

  if (aKeyElement) {
    mType |= NS_HANDLER_TYPE_XUL;
    nsCOMPtr<nsIWeakReference> weak = do_GetWeakReference(aKeyElement);
    if (!weak) {
      return;
    }
    weak.swap(mHandlerElement);
  }
  else {
    mType |= aCommand ? NS_HANDLER_TYPE_XBL_COMMAND : NS_HANDLER_TYPE_XBL_JS;
    mHandlerText = nsnull;
  }

  mDetail = -1;
  mMisc = 0;
  mKeyMask = 0;
  mPhase = NS_PHASE_BUBBLING;

  if (aAction)
    mHandlerText = ToNewUnicode(nsDependentString(aAction));
  else if (aCommand)
    mHandlerText = ToNewUnicode(nsDependentString(aCommand));

  nsAutoString event(aEvent);
  if (event.IsEmpty()) {
    if (mType & NS_HANDLER_TYPE_XUL)
      GetEventType(event);
    if (event.IsEmpty())
      return;
  }

  mEventName = do_GetAtom(event);

  if (aPhase) {
    const nsDependentString phase(aPhase);
    if (phase.EqualsLiteral("capturing"))
      mPhase = NS_PHASE_CAPTURING;
    else if (phase.EqualsLiteral("target"))
      mPhase = NS_PHASE_TARGET;
  }

  // Button and clickcount apply only to XBL handlers and don't apply to XUL key
  // handlers.  
  if (aButton && *aButton)
    mDetail = *aButton - '0';

  if (aClickCount && *aClickCount)
    mMisc = *aClickCount - '0';

  // Modifiers are supported by both types of handlers (XUL and XBL).  
  nsAutoString modifiers(aModifiers);
  if (mType & NS_HANDLER_TYPE_XUL)
    aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiers);
  
  if (!modifiers.IsEmpty()) {
    mKeyMask = cAllModifiers;
    char* str = ToNewCString(modifiers);
    char* newStr;
    char* token = nsCRT::strtok( str, ", \t", &newStr );
    while( token != NULL ) {
      if (PL_strcmp(token, "shift") == 0)
        mKeyMask |= cShift | cShiftMask;
      else if (PL_strcmp(token, "alt") == 0)
        mKeyMask |= cAlt | cAltMask;
      else if (PL_strcmp(token, "meta") == 0)
        mKeyMask |= cMeta | cMetaMask;
      else if (PL_strcmp(token, "control") == 0)
        mKeyMask |= cControl | cControlMask;
      else if (PL_strcmp(token, "accel") == 0)
        mKeyMask |= KeyToMask(kAccelKey);
      else if (PL_strcmp(token, "access") == 0)
        mKeyMask |= KeyToMask(kMenuAccessKey);
      else if (PL_strcmp(token, "any") == 0)
        mKeyMask &= ~(mKeyMask << 4);
    
      token = nsCRT::strtok( newStr, ", \t", &newStr );
    }

    nsMemory::Free(str);
  }

  nsAutoString key(aCharCode);
  if (key.IsEmpty()) {
    if (mType & NS_HANDLER_TYPE_XUL) {
      aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, key);
      if (key.IsEmpty()) 
        aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::charcode, key);
    }
  }

  if (!key.IsEmpty()) {
    if (mKeyMask == 0)
      mKeyMask = cAllModifiers;
    ToLowerCase(key);

    // We have a charcode.
    mMisc = 1;
    mDetail = key[0];
    const PRUint8 GTK2Modifiers = cShift | cControl | cShiftMask | cControlMask;
    if ((mKeyMask & GTK2Modifiers) == GTK2Modifiers &&
        modifiers.First() != PRUnichar(',') &&
        (mDetail == 'u' || mDetail == 'U'))
      ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "GTK2Conflict");
    const PRUint8 WinModifiers = cControl | cAlt | cControlMask | cAltMask;
    if ((mKeyMask & WinModifiers) == WinModifiers &&
        modifiers.First() != PRUnichar(',') &&
        (('A' <= mDetail && mDetail <= 'Z') ||
         ('a' <= mDetail && mDetail <= 'z')))
      ReportKeyConflict(key.get(), modifiers.get(), aKeyElement, "WinConflict");
  }
  else {
    key.Assign(aKeyCode);
    if (mType & NS_HANDLER_TYPE_XUL)
      aKeyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::keycode, key);
    
    if (!key.IsEmpty()) {
      if (mKeyMask == 0)
        mKeyMask = cAllModifiers;
      mDetail = GetMatchingKeyCode(key);
    }
  }

  if (aGroup && nsDependentString(aGroup).EqualsLiteral("system"))
    mType |= NS_HANDLER_TYPE_SYSTEM;

  if (aPreventDefault &&
      nsDependentString(aPreventDefault).EqualsLiteral("true"))
    mType |= NS_HANDLER_TYPE_PREVENTDEFAULT;

  if (aAllowUntrusted) {
    mType |= NS_HANDLER_HAS_ALLOW_UNTRUSTED_ATTR;
    if (nsDependentString(aAllowUntrusted).EqualsLiteral("true")) {
      mType |= NS_HANDLER_ALLOW_UNTRUSTED;
    } else {
      mType &= ~NS_HANDLER_ALLOW_UNTRUSTED;
    }
  }
}
Exemplo n.º 18
0
// moved almost verbatim from mimehdrs.cpp
// char *
// MimeHeaders_get_parameter (const char *header_value, const char *parm_name,
//                            char **charset, char **language)
//
// The format of these header lines  is
// <token> [ ';' <token> '=' <token-or-quoted-string> ]*
NS_IMETHODIMP 
nsMIMEHeaderParamImpl::GetParameterInternal(const char *aHeaderValue, 
                                            const char *aParamName,
                                            char **aCharset,
                                            char **aLang,
                                            char **aResult)
{
  if (!aHeaderValue ||  !*aHeaderValue || !aResult)
    return NS_ERROR_INVALID_ARG;

  *aResult = nsnull;

  if (aCharset) *aCharset = nsnull;
  if (aLang) *aLang = nsnull;

  const char *str = aHeaderValue;

  // skip leading white space.
  for (; *str &&  nsCRT::IsAsciiSpace(*str); ++str)
    ;
  const char *start = str;
  
  // aParamName is empty. return the first (possibly) _unnamed_ 'parameter'
  // For instance, return 'inline' in the following case:
  // Content-Disposition: inline; filename=.....
  if (!aParamName || !*aParamName) 
    {
      for (; *str && *str != ';' && !nsCRT::IsAsciiSpace(*str); ++str)
        ;
      if (str == start)
        return NS_ERROR_UNEXPECTED;
      *aResult = (char *) nsMemory::Clone(start, (str - start) + 1);
      NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
      (*aResult)[str - start] = '\0';  // null-terminate
      return NS_OK;
    }

  /* Skip forward to first ';' */
  for (; *str && *str != ';' && *str != ','; ++str)
    ;
  if (*str)
    str++;
  /* Skip over following whitespace */
  for (; *str && nsCRT::IsAsciiSpace(*str); ++str)
    ;

  // Some broken http servers just specify parameters
  // like 'filename' without specifying disposition
  // method. Rewind to the first non-white-space
  // character.
  
  if (!*str)
    str = start;

  // RFC2231 - The legitimate parm format can be:
  // A. title=ThisIsTitle 
  // B. title*=us-ascii'en-us'This%20is%20wierd.
  // C. title*0*=us-ascii'en'This%20is%20wierd.%20We
  //    title*1*=have%20to%20support%20this.
  //    title*2="Else..."
  // D. title*0="Hey, what you think you are doing?"
  //    title*1="There is no charset and lang info."

  PRInt32 paramLen = strlen(aParamName);

  while (*str) {
    const char *tokenStart = str;
    const char *tokenEnd = 0;
    const char *valueStart = str;
    const char *valueEnd = 0;

    NS_ASSERTION(!nsCRT::IsAsciiSpace(*str), "should be after whitespace.");

    // Skip forward to the end of this token. 
    for (; *str && !nsCRT::IsAsciiSpace(*str) && *str != '=' && *str != ';'; str++)
      ;
    tokenEnd = str;

    // Skip over whitespace, '=', and whitespace
    while (nsCRT::IsAsciiSpace(*str)) ++str;
    if (*str == '=') ++str;
    while (nsCRT::IsAsciiSpace(*str)) ++str;

    if (*str != '"')
    {
      // The value is a token, not a quoted string.
      valueStart = str;
      for (valueEnd = str;
           *valueEnd && !nsCRT::IsAsciiSpace (*valueEnd) && *valueEnd != ';';
           valueEnd++)
        ;
      str = valueEnd;
    }
    else
    {
      // The value is a quoted string. 
      ++str;
      valueStart = str;
      for (valueEnd = str; *valueEnd; ++valueEnd)
      {
        if (*valueEnd == '\\')
          ++valueEnd;
        else if (*valueEnd == '"')
          break;
      }
      str = valueEnd + 1;
    }

    // See if this is the simplest case (case A above),
    // a 'single' line value with no charset and lang.
    // If so, copy it and return.
    if (tokenEnd - tokenStart == paramLen &&
        !nsCRT::strncasecmp(tokenStart, aParamName, paramLen))
    {
      // if the parameter spans across multiple lines we have to strip out the
      //     line continuation -- jht 4/29/98 
      nsCAutoString tempStr(valueStart, valueEnd - valueStart);
      tempStr.StripChars("\r\n");
      *aResult = ToNewCString(tempStr);
      NS_ENSURE_TRUE(*aResult, NS_ERROR_OUT_OF_MEMORY);
      return NS_OK;
    }
    // case B, C, and D
    else if (tokenEnd - tokenStart > paramLen &&
             !nsCRT::strncasecmp(tokenStart, aParamName, paramLen) &&
             *(tokenStart + paramLen) == '*')
    {
      const char *cp = tokenStart + paramLen + 1; // 1st char pass '*'
      PRBool needUnescape = *(tokenEnd - 1) == '*';
      // the 1st line of a multi-line parameter or a single line  that needs 
      // unescaping. ( title*0*=  or  title*= )
      if ((*cp == '0' && needUnescape) || (tokenEnd - tokenStart == paramLen + 1))
      {
        // look for single quotation mark(')
        const char *sQuote1 = PL_strchr(valueStart, 0x27);
        const char *sQuote2 = (char *) (sQuote1 ? PL_strchr(sQuote1 + 1, 0x27) : nsnull);

        // Two single quotation marks must be present even in
        // absence of charset and lang. 
        if (!sQuote1 || !sQuote2)
          NS_WARNING("Mandatory two single quotes are missing in header parameter\n");
        if (aCharset && sQuote1 > valueStart && sQuote1 < valueEnd)
        {
          *aCharset = (char *) nsMemory::Clone(valueStart, sQuote1 - valueStart + 1);
          if (*aCharset) 
            *(*aCharset + (sQuote1 - valueStart)) = 0;
        }
        if (aLang && sQuote1 && sQuote2 && sQuote2 > sQuote1 + 1 &&
            sQuote2 < valueEnd)
        {
          *aLang = (char *) nsMemory::Clone(sQuote1 + 1, sQuote2 - (sQuote1 + 1) + 1);
          if (*aLang) 
            *(*aLang + (sQuote2 - (sQuote1 + 1))) = 0;
        }

        // Be generous and handle gracefully when required 
        // single quotes are absent.
        if (sQuote1)
        {
          if(!sQuote2)
            sQuote2 = sQuote1;
        }
        else
          sQuote2 = valueStart - 1;

        if (sQuote2 && sQuote2 + 1 < valueEnd)
        {
          NS_ASSERTION(!*aResult, "This is the 1st line. result buffer should be null.");
          *aResult = (char *) nsMemory::Alloc(valueEnd - (sQuote2 + 1) + 1);
          if (*aResult)
          {
            memcpy(*aResult, sQuote2 + 1, valueEnd - (sQuote2 + 1));
            *(*aResult + (valueEnd - (sQuote2 + 1))) = 0;
            if (needUnescape)
            {
              nsUnescape(*aResult);
              if (tokenEnd - tokenStart == paramLen + 1)
                // we're done; this is case B 
                return NS_OK; 
            }
          }
        }
      }  // end of if-block :  title*0*=  or  title*= 
      // a line of multiline param with no need for unescaping : title*[0-9]=
      // or 2nd or later lines of a multiline param : title*[1-9]*= 
      else if (nsCRT::IsAsciiDigit(PRUnichar(*cp)))
      {
        PRInt32 len = 0;
        if (*aResult) // 2nd or later lines of multiline parameter
        {
          len = strlen(*aResult);
          char *ns = (char *) nsMemory::Realloc(*aResult, len + (valueEnd - valueStart) + 1);
          if (!ns)
          {
            nsMemory::Free(*aResult);
          }
          *aResult = ns;
        }
        else if (*cp == '0') // must be; 1st line :  title*0=
        {
          *aResult = (char *) nsMemory::Alloc(valueEnd - valueStart + 1);
        }
        // else {} something is really wrong; out of memory
        if (*aResult)
        {
          // append a partial value
          memcpy(*aResult + len, valueStart, valueEnd - valueStart);
          *(*aResult + len + (valueEnd - valueStart)) = 0;
          if (needUnescape)
            nsUnescape(*aResult + len);
        }
        else 
          return NS_ERROR_OUT_OF_MEMORY;
      } // end of if-block :  title*[0-9]= or title*[1-9]*=
    }

    // str now points after the end of the value.
    //   skip over whitespace, ';', whitespace.
      
    while (nsCRT::IsAsciiSpace(*str)) ++str;
    if (*str == ';') ++str;
    while (nsCRT::IsAsciiSpace(*str)) ++str;
  }

  if (*aResult) 
    return NS_OK;
  else
    return NS_ERROR_INVALID_ARG; // aParameter not found !!
}
Exemplo n.º 19
0
void 
nsMenuFrame::BuildAcceleratorText()
{
  nsAutoString accelText;

  if ((GetStateBits() & NS_STATE_ACCELTEXT_IS_DERIVED) == 0) {
    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accelText);
    if (!accelText.IsEmpty())
      return;
  }
  // accelText is definitely empty here.

  // Now we're going to compute the accelerator text, so remember that we did.
  AddStateBits(NS_STATE_ACCELTEXT_IS_DERIVED);

  // If anything below fails, just leave the accelerator text blank.
  nsWeakFrame weakFrame(this);
  mContent->UnsetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, PR_FALSE);
  ENSURE_TRUE(weakFrame.IsAlive());

  // See if we have a key node and use that instead.
  nsAutoString keyValue;
  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::key, keyValue);
  if (keyValue.IsEmpty())
    return;

  // Turn the document into a DOM document so we can use getElementById
  nsIDocument *document = mContent->GetDocument();
  if (!document)
    return;

  nsIContent *keyElement = document->GetElementById(keyValue);
  if (!keyElement) {
#ifdef DEBUG
    nsAutoString label;
    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, label);
    nsAutoString msg = NS_LITERAL_STRING("Key '") +
                       keyValue +
                       NS_LITERAL_STRING("' of menu item '") +
                       label +
                       NS_LITERAL_STRING("' could not be found");
    NS_WARNING(NS_ConvertUTF16toUTF8(msg).get());
#endif
    return;
  }

  // get the string to display as accelerator text
  // check the key element's attributes in this order:
  // |keytext|, |key|, |keycode|
  nsAutoString accelString;
  keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::keytext, accelString);

  if (accelString.IsEmpty()) {
    keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, accelString);

    if (!accelString.IsEmpty()) {
      ToUpperCase(accelString);
    } else {
      nsAutoString keyCode;
      keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::keycode, keyCode);
      ToUpperCase(keyCode);

      nsresult rv;
      nsCOMPtr<nsIStringBundleService> bundleService =
        mozilla::services::GetStringBundleService();
      if (bundleService) {
        nsCOMPtr<nsIStringBundle> bundle;
        rv = bundleService->CreateBundle("chrome://global/locale/keys.properties",
                                         getter_AddRefs(bundle));

        if (NS_SUCCEEDED(rv) && bundle) {
          nsXPIDLString keyName;
          rv = bundle->GetStringFromName(keyCode.get(), getter_Copies(keyName));
          if (keyName)
            accelString = keyName;
        }
      }

      // nothing usable found, bail
      if (accelString.IsEmpty())
        return;
    }
  }

  static PRInt32 accelKey = 0;

  if (!accelKey)
  {
    // Compiled-in defaults, in case we can't get LookAndFeel --
    // command for mac, control for all other platforms.
#ifdef XP_MACOSX
    accelKey = nsIDOMKeyEvent::DOM_VK_META;
#else
    accelKey = nsIDOMKeyEvent::DOM_VK_CONTROL;
#endif

    // Get the accelerator key value from prefs, overriding the default:
    accelKey = nsContentUtils::GetIntPref("ui.key.accelKey", accelKey);
  }

  nsAutoString modifiers;
  keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiers);
  
  char* str = ToNewCString(modifiers);
  char* newStr;
  char* token = nsCRT::strtok(str, ", \t", &newStr);
  while (token) {
      
    if (PL_strcmp(token, "shift") == 0)
      accelText += *gShiftText;
    else if (PL_strcmp(token, "alt") == 0) 
      accelText += *gAltText; 
    else if (PL_strcmp(token, "meta") == 0) 
      accelText += *gMetaText; 
    else if (PL_strcmp(token, "control") == 0) 
      accelText += *gControlText; 
    else if (PL_strcmp(token, "accel") == 0) {
      switch (accelKey)
      {
        case nsIDOMKeyEvent::DOM_VK_META:
          accelText += *gMetaText;
          break;

        case nsIDOMKeyEvent::DOM_VK_ALT:
          accelText += *gAltText;
          break;

        case nsIDOMKeyEvent::DOM_VK_CONTROL:
        default:
          accelText += *gControlText;
          break;
      }
    }
    
    accelText += *gModifierSeparator;

    token = nsCRT::strtok(newStr, ", \t", &newStr);
  }

  nsMemory::Free(str);

  accelText += accelString;
  
  mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accelText, PR_FALSE);
}
Exemplo n.º 20
0
/**
 * Obtains all of the information currently available for this plugin.
 */
nsresult nsPluginFile::GetPluginInfo(nsPluginInfo& info, PRLibrary **outLibrary)
{
    *outLibrary = nsnull;

    info.fVersion = nsnull;

    nsCAutoString fullPath;
    if (NS_FAILED(rv = mPlugin->GetNativePath(fullPath)))
        return rv;

    nsCAutoString fileName;
    if (NS_FAILED(rv = mPlugin->GetNativeLeafName(fileName)))
        return rv;

    const char *path = fullPath.get();
    int i;

#ifdef NS_PLUGIN_BEOS_DEBUG
    printf("nsPluginFile::GetPluginInfo() an attempt to load MIME String\n");
    printf("path = <%s>\n", path);
#endif

    // get supported mime types
    BFile file(path, B_READ_ONLY);
    if (file.InitCheck() != B_OK)
        return NS_ERROR_FAILURE;

    BAppFileInfo appinfo(&file);
    if (appinfo.InitCheck() != B_OK)
        return NS_ERROR_FAILURE;

    BMessage msg;
    if (appinfo.GetSupportedTypes(&msg) != B_OK)
        return NS_ERROR_FAILURE;

    uint32 type;
    int32 types_num;
    if (msg.GetInfo("types", &type, &types_num) != B_OK
        || type != B_STRING_TYPE)
        return NS_ERROR_FAILURE;

    // set mime types to plugin info
    info.fMimeTypeArray =(char **)PR_Malloc(types_num * sizeof(char *));
    info.fMimeDescriptionArray =(char **)PR_Malloc(types_num * sizeof(char *));
    info.fExtensionArray =(char **)PR_Malloc(types_num * sizeof(char *));

    for (i = 0 ; i < types_num ; i ++) {
        // get mime string
        const char *mtype;
        if (msg.FindString("types", i, &mtype) != B_OK) {
            types_num = i;
            break;
        }
        
        // get (short)description for the mime
        char desc[B_MIME_TYPE_LENGTH+1] = "";
        BMimeType mime(mtype) ;
        if (mime.InitCheck() == B_OK)
            mime.GetShortDescription(desc);
        
        // get file extensions for the mime
        char extensions[B_MIME_TYPE_LENGTH+1] = "";
        GetMimeExtensions(mtype, extensions, B_MIME_TYPE_LENGTH+1);

        #ifdef NS_PLUGIN_BEOS_DEBUG
            printf("  mime = %30s | %10s | %15s |\n", 
                mtype, extensions, desc);
        #endif
        
        info.fMimeTypeArray[i] = PL_strdup( mtype ? mtype : (char *)"" ) ;
        info.fMimeDescriptionArray[i] = PL_strdup( desc ) ;
        info.fExtensionArray[i] = PL_strdup( extensions );
    }

    // get name and description of this plugin
    version_info vinfo;
    if (appinfo.GetVersionInfo(&vinfo, B_APP_VERSION_KIND) == B_OK
        && *vinfo.short_info) {
        // XXX convert UTF-8 2byte chars to 1 byte chars, to avoid string corruption
        info.fName = ToNewCString(NS_ConvertUTF8toUTF16(vinfo.short_info));
        info.fDescription = ToNewCString(NS_ConvertUTF8toUTF16(vinfo.long_info));
    } else {
        // use filename as its name
        info.fName = GetFileName(path);
        info.fDescription = PL_strdup("");
    }

    info.fVariantCount = types_num;
    info.fFullPath = PL_strdup(fullPath.get());
    info.fFileName = PL_strdup(fileName.get());

#ifdef NS_PLUGIN_BEOS_DEBUG
    printf("info.fFileName = %s\n", info.fFileName);
    printf("info.fName = %s\n", info.fName);
    printf("info.fDescription = %s\n", info.fDescription);
#endif

    return NS_OK;
}
Exemplo n.º 21
0
nsresult
nsKeygenFormProcessor::GetPublicKey(const nsAString& aValue,
                                    const nsAString& aChallenge,
                                    const nsAFlatString& aKeyType,
                                    nsAString& aOutPublicKey,
                                    const nsAString& aKeyParams)
{
    nsNSSShutDownPreventionLock locker;
    if (isAlreadyShutDown()) {
      return NS_ERROR_NOT_AVAILABLE;
    }

    nsresult rv = NS_ERROR_FAILURE;
    char *keystring = nullptr;
    char *keyparamsString = nullptr;
    uint32_t keyGenMechanism;
    PK11SlotInfo *slot = nullptr;
    PK11RSAGenParams rsaParams;
    SECOidTag algTag;
    int keysize = 0;
    void *params = nullptr;
    SECKEYPrivateKey *privateKey = nullptr;
    SECKEYPublicKey *publicKey = nullptr;
    CERTSubjectPublicKeyInfo *spkInfo = nullptr;
    SECStatus srv = SECFailure;
    SECItem spkiItem;
    SECItem pkacItem;
    SECItem signedItem;
    CERTPublicKeyAndChallenge pkac;
    pkac.challenge.data = nullptr;
    nsIGeneratingKeypairInfoDialogs * dialogs;
    nsKeygenThread *KeygenRunnable = 0;
    nsCOMPtr<nsIKeygenThread> runnable;

    // permanent and sensitive flags for keygen
    PK11AttrFlags attrFlags = PK11_ATTR_TOKEN | PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE;

    UniquePLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
    if (!arena) {
        goto loser;
    }

    // Get the key size //
    for (size_t i = 0; i < number_of_key_size_choices; ++i) {
        if (aValue.Equals(mSECKeySizeChoiceList[i].name)) {
            keysize = mSECKeySizeChoiceList[i].size;
            break;
        }
    }
    if (!keysize) {
        goto loser;
    }

    // Set the keygen mechanism
    if (aKeyType.IsEmpty() || aKeyType.LowerCaseEqualsLiteral("rsa")) {
        keyGenMechanism = CKM_RSA_PKCS_KEY_PAIR_GEN;
    } else if (aKeyType.LowerCaseEqualsLiteral("ec")) {
        keyparamsString = ToNewCString(aKeyParams);
        if (!keyparamsString) {
            rv = NS_ERROR_OUT_OF_MEMORY;
            goto loser;
        }

        keyGenMechanism = CKM_EC_KEY_PAIR_GEN;
        /* ecParams are initialized later */
    } else {
        goto loser;
    }

    // Get the slot
    rv = GetSlot(keyGenMechanism, &slot);
    if (NS_FAILED(rv)) {
        goto loser;
    }
    switch (keyGenMechanism) {
        case CKM_RSA_PKCS_KEY_PAIR_GEN:
            rsaParams.keySizeInBits = keysize;
            rsaParams.pe = DEFAULT_RSA_KEYGEN_PE;
            algTag = DEFAULT_RSA_KEYGEN_ALG;
            params = &rsaParams;
            break;
        case CKM_EC_KEY_PAIR_GEN:
            /* XXX We ought to rethink how the KEYGEN tag is 
             * displayed. The pulldown selections presented
             * to the user must depend on the keytype.
             * The displayed selection could be picked
             * from the keyparams attribute (this is currently called
             * the pqg attribute).
             * For now, we pick ecparams from the keyparams field
             * if it specifies a valid supported curve, or else 
             * we pick one of secp384r1, secp256r1 or secp192r1
             * respectively depending on the user's selection
             * (High, Medium, Low). 
             * (RSA uses RSA-2048, RSA-1024 and RSA-512 for historical
             * reasons, while ECC choices represent a stronger mapping)
             * NOTE: The user's selection
             * is silently ignored when a valid curve is presented
             * in keyparams.
             */
            if ((params = decode_ec_params(keyparamsString)) == nullptr) {
                /* The keyparams attribute did not specify a valid
                 * curve name so use a curve based on the keysize.
                 * NOTE: Here keysize is used only as an indication of
                 * High/Medium/Low strength; elliptic curve
                 * cryptography uses smaller keys than RSA to provide
                 * equivalent security.
                 */
                switch (keysize) {
                case 2048:
                    params = decode_ec_params("secp384r1");
                    break;
                case 1024:
                case 512:
                    params = decode_ec_params("secp256r1");
                    break;
                } 
            }
            /* XXX The signature algorithm ought to choose the hashing
             * algorithm based on key size once ECDSA variations based
             * on SHA256 SHA384 and SHA512 are standardized.
             */
            algTag = SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST;
            break;
      default:
          goto loser;
      }

    /* Make sure token is initialized. */
    rv = setPassword(slot, m_ctx, locker);
    if (NS_FAILED(rv))
        goto loser;

    srv = PK11_Authenticate(slot, true, m_ctx);
    if (srv != SECSuccess) {
        goto loser;
    }

    rv = getNSSDialogs((void**)&dialogs,
                       NS_GET_IID(nsIGeneratingKeypairInfoDialogs),
                       NS_GENERATINGKEYPAIRINFODIALOGS_CONTRACTID);

    if (NS_SUCCEEDED(rv)) {
        KeygenRunnable = new nsKeygenThread();
        NS_IF_ADDREF(KeygenRunnable);
    }

    if (NS_FAILED(rv) || !KeygenRunnable) {
        rv = NS_OK;
        privateKey = PK11_GenerateKeyPairWithFlags(slot, keyGenMechanism, params,
                                                   &publicKey, attrFlags, m_ctx);
    } else {
        KeygenRunnable->SetParams( slot, attrFlags, nullptr, 0,
                                   keyGenMechanism, params, m_ctx );

        runnable = do_QueryInterface(KeygenRunnable);
        
        if (runnable) {
            rv = dialogs->DisplayGeneratingKeypairInfo(m_ctx, runnable);
            // We call join on the thread so we can be sure that no
            // simultaneous access to the passed parameters will happen.
            KeygenRunnable->Join();

            NS_RELEASE(dialogs);
            if (NS_SUCCEEDED(rv)) {
                PK11SlotInfo *used_slot = nullptr;
                rv = KeygenRunnable->ConsumeResult(&used_slot, &privateKey, &publicKey);
                if (NS_SUCCEEDED(rv) && used_slot) {
                  PK11_FreeSlot(used_slot);
                }
            }
        }
    }
    
    if (NS_FAILED(rv) || !privateKey) {
        goto loser;
    }
    // just in case we'll need to authenticate to the db -jp //
    privateKey->wincx = m_ctx;

    /*
     * Create a subject public key info from the public key.
     */
    spkInfo = SECKEY_CreateSubjectPublicKeyInfo(publicKey);
    if ( !spkInfo ) {
        goto loser;
    }

    /*
     * Now DER encode the whole subjectPublicKeyInfo.
     */
    srv = DER_Encode(arena.get(), &spkiItem, CERTSubjectPublicKeyInfoTemplate,
                     spkInfo);
    if (srv != SECSuccess) {
        goto loser;
    }

    /*
     * set up the PublicKeyAndChallenge data structure, then DER encode it
     */
    pkac.spki = spkiItem;
    pkac.challenge.len = aChallenge.Length();
    pkac.challenge.data = (unsigned char *)ToNewCString(aChallenge);
    if (!pkac.challenge.data) {
        rv = NS_ERROR_OUT_OF_MEMORY;
        goto loser;
    }

    srv = DER_Encode(arena.get(), &pkacItem, CERTPublicKeyAndChallengeTemplate,
                     &pkac);
    if (srv != SECSuccess) {
        goto loser;
    }

    /*
     * now sign the DER encoded PublicKeyAndChallenge
     */
    srv = SEC_DerSignData(arena.get(), &signedItem, pkacItem.data, pkacItem.len,
                          privateKey, algTag);
    if (srv != SECSuccess) {
        goto loser;
    }

    /*
     * Convert the signed public key and challenge into base64/ascii.
     */
    keystring = BTOA_DataToAscii(signedItem.data, signedItem.len);
    if (!keystring) {
        rv = NS_ERROR_OUT_OF_MEMORY;
        goto loser;
    }

    CopyASCIItoUTF16(keystring, aOutPublicKey);
    free(keystring);

    rv = NS_OK;

    GatherKeygenTelemetry(keyGenMechanism, keysize, keyparamsString);
loser:
    if (srv != SECSuccess) {
        if ( privateKey ) {
            PK11_DestroyTokenObject(privateKey->pkcs11Slot,privateKey->pkcs11ID);
        }
        if ( publicKey ) {
            PK11_DestroyTokenObject(publicKey->pkcs11Slot,publicKey->pkcs11ID);
        }
    }
    if ( spkInfo ) {
        SECKEY_DestroySubjectPublicKeyInfo(spkInfo);
    }
    if ( publicKey ) {
        SECKEY_DestroyPublicKey(publicKey);
    }
    if ( privateKey ) {
        SECKEY_DestroyPrivateKey(privateKey);
    }
    if (slot) {
        PK11_FreeSlot(slot);
    }
    if (KeygenRunnable) {
        NS_RELEASE(KeygenRunnable);
    }
    if (keyparamsString) {
        free(keyparamsString);
    }
    if (pkac.challenge.data) {
        free(pkac.challenge.data);
    }
    // If params is non-null and doesn't point to rsaParams, it was allocated
    // in decode_ec_params. We have to free this memory.
    if (params && params != &rsaParams) {
        SECITEM_FreeItem(static_cast<SECItem*>(params), true);
        params = nullptr;
    }
    return rv;
}
Exemplo n.º 22
0
void printString(nsString &str) {
    const char *cstr = ToNewCString(str);
    printf("%s", cstr);
    delete [] (char*)cstr;
}
// XXX currently you can not add the same adjacency (i.e. you can't have multiple
// XXX stream converters registering to handle the same from-to combination. It's
// XXX not programatically prohibited, it's just that results are un-predictable
// XXX right now.
nsresult
nsStreamConverterService::AddAdjacency(const char *aContractID) {
    nsresult rv;
    // first parse out the FROM and TO MIME-types.

    nsAutoCString fromStr, toStr;
    rv = ParseFromTo(aContractID, fromStr, toStr);
    if (NS_FAILED(rv)) return rv;

    // Each MIME-type is a vertex in the graph, so first lets make sure
    // each MIME-type is represented as a key in our hashtable.

    nsCStringKey fromKey(fromStr);
    SCTableData *fromEdges = (SCTableData*)mAdjacencyList->Get(&fromKey);
    if (!fromEdges) {
        // There is no fromStr vertex, create one.

        nsCStringKey *newFromKey = new nsCStringKey(ToNewCString(fromStr), fromStr.Length(), nsCStringKey::OWN);
        if (!newFromKey) return NS_ERROR_OUT_OF_MEMORY;

        SCTableData *data = new SCTableData(newFromKey);
        if (!data) {
            delete newFromKey;
            return NS_ERROR_OUT_OF_MEMORY;
        }

        nsCOMArray<nsIAtom>* edgeArray = new nsCOMArray<nsIAtom>;
        if (!edgeArray) {
            delete newFromKey;
            data->key = nullptr;
            delete data;
            return NS_ERROR_OUT_OF_MEMORY;
        }
        data->data.edges = edgeArray;

        mAdjacencyList->Put(newFromKey, data);
        fromEdges = data;
    }

    nsCStringKey toKey(toStr);
    if (!mAdjacencyList->Get(&toKey)) {
        // There is no toStr vertex, create one.
        nsCStringKey *newToKey = new nsCStringKey(ToNewCString(toStr), toStr.Length(), nsCStringKey::OWN);
        if (!newToKey) return NS_ERROR_OUT_OF_MEMORY;

        SCTableData *data = new SCTableData(newToKey);
        if (!data) {
            delete newToKey;
            return NS_ERROR_OUT_OF_MEMORY;
        }

        nsCOMArray<nsIAtom>* edgeArray = new nsCOMArray<nsIAtom>;
        if (!edgeArray) {
            delete newToKey;
            data->key = nullptr;
            delete data;
            return NS_ERROR_OUT_OF_MEMORY;
        }
        data->data.edges = edgeArray;
        mAdjacencyList->Put(newToKey, data);
    }
    
    // Now we know the FROM and TO types are represented as keys in the hashtable.
    // Let's "connect" the verticies, making an edge.

    nsCOMPtr<nsIAtom> vertex = do_GetAtom(toStr); 
    if (!vertex) return NS_ERROR_OUT_OF_MEMORY;

    NS_ASSERTION(fromEdges, "something wrong in adjacency list construction");
    if (!fromEdges)
        return NS_ERROR_FAILURE;

    nsCOMArray<nsIAtom> *adjacencyList = fromEdges->data.edges;
    return adjacencyList->AppendObject(vertex) ? NS_OK : NS_ERROR_FAILURE;
}
Exemplo n.º 24
0
nsresult nsMsgSearchAdapter::EncodeImapTerm (nsIMsgSearchTerm *term, bool reallyDredd, const PRUnichar *srcCharset, const PRUnichar *destCharset, char **ppOutTerm)
{
  NS_ENSURE_ARG_POINTER(term);
  NS_ENSURE_ARG_POINTER(ppOutTerm);

  nsresult err = NS_OK;
  bool useNot = false;
  bool useQuotes = false;
  bool ignoreValue = false;
  nsCAutoString arbitraryHeader;
  const char *whichMnemonic = nsnull;
  const char *orHeaderMnemonic = nsnull;

  *ppOutTerm = nsnull;

  nsCOMPtr <nsIMsgSearchValue> searchValue;
  nsresult rv = term->GetValue(getter_AddRefs(searchValue));

  NS_ENSURE_SUCCESS(rv,rv);

  nsMsgSearchOpValue op;
  term->GetOp(&op);

  if (op == nsMsgSearchOp::DoesntContain || op == nsMsgSearchOp::Isnt)
    useNot = true;

  nsMsgSearchAttribValue attrib;
  term->GetAttrib(&attrib);

  switch (attrib)
  {
  case nsMsgSearchAttrib::ToOrCC:
    orHeaderMnemonic = m_kImapCC;
    // fall through to case nsMsgSearchAttrib::To:
  case nsMsgSearchAttrib::To:
    whichMnemonic = m_kImapTo;
    break;
  case nsMsgSearchAttrib::CC:
    whichMnemonic = m_kImapCC;
    break;
  case nsMsgSearchAttrib::Sender:
    whichMnemonic = m_kImapFrom;
    break;
  case nsMsgSearchAttrib::Subject:
    whichMnemonic = m_kImapSubject;
    break;
  case nsMsgSearchAttrib::Body:
    whichMnemonic = m_kImapBody;
    break;
  case nsMsgSearchAttrib::AgeInDays:  // added for searching online for age in days...
    // for AgeInDays, we are actually going to perform a search by date, so convert the operations for age
    // to the IMAP mnemonics that we would use for date!
    {
      // If we have a future date, the > and < are reversed.
      // e.g. ageInDays > 2 means more than 2 days old ("date before X") whereas
      //      ageInDays > -2 should be more than 2 days in the future ("date after X")
      PRInt32 ageInDays;
      searchValue->GetAge(&ageInDays);
      bool dateInFuture = (ageInDays < 0);
      switch (op)
      {
      case nsMsgSearchOp::IsGreaterThan:
        whichMnemonic = (!dateInFuture) ? m_kImapBefore : m_kImapSince;
        break;
      case nsMsgSearchOp::IsLessThan:
        whichMnemonic = (!dateInFuture) ? m_kImapSince : m_kImapBefore;
        break;
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }
    break;
  case nsMsgSearchAttrib::Size:
    switch (op)
    {
    case nsMsgSearchOp::IsGreaterThan:
      whichMnemonic = m_kImapSizeLarger;
      break;
    case nsMsgSearchOp::IsLessThan:
      whichMnemonic = m_kImapSizeSmaller;
      break;
    default:
      NS_ASSERTION(false, "invalid search operator");
      return NS_ERROR_INVALID_ARG;
    }
    break;
    case nsMsgSearchAttrib::Date:
      switch (op)
      {
      case nsMsgSearchOp::IsBefore:
        whichMnemonic = m_kImapBefore;
        break;
      case nsMsgSearchOp::IsAfter:
        whichMnemonic = m_kImapSince;
        break;
      case nsMsgSearchOp::Isnt:  /* we've already added the "Not" so just process it like it was a date is search */
      case nsMsgSearchOp::Is:
        whichMnemonic = m_kImapSentOn;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    case nsMsgSearchAttrib::AnyText:
      whichMnemonic = m_kImapAnyText;
      break;
    case nsMsgSearchAttrib::Keywords:
      whichMnemonic = m_kImapKeyword;
      break;
    case nsMsgSearchAttrib::MsgStatus:
      useNot = false; // bizarrely, NOT SEEN is wrong, but UNSEEN is right.
      ignoreValue = true; // the mnemonic is all we need
      PRUint32 status;
      searchValue->GetStatus(&status);

      switch (status)
      {
      case nsMsgMessageFlags::Read:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapSeen : m_kImapNotSeen;
        break;
      case nsMsgMessageFlags::Replied:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapAnswered : m_kImapNotAnswered;
        break;
      case nsMsgMessageFlags::New:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapNew : m_kImapNotNew;
        break;
      case nsMsgMessageFlags::Marked:
        whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapFlagged : m_kImapNotFlagged;
        break;
      default:
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
      break;
    default:
      if ( attrib > nsMsgSearchAttrib::OtherHeader && attrib < nsMsgSearchAttrib::kNumMsgSearchAttributes)
      {
        nsCString arbitraryHeaderTerm;
        term->GetArbitraryHeader(arbitraryHeaderTerm);
        if (!arbitraryHeaderTerm.IsEmpty())
        {
          arbitraryHeader.AssignLiteral(" \"");
          arbitraryHeader.Append(arbitraryHeaderTerm);
          arbitraryHeader.AppendLiteral("\" ");
          whichMnemonic = arbitraryHeader.get();
        }
        else
          return NS_ERROR_FAILURE;
      }
      else
      {
        NS_ASSERTION(false, "invalid search operator");
        return NS_ERROR_INVALID_ARG;
      }
    }

    char *value = nsnull;
    char dateBuf[100];
    dateBuf[0] = '\0';

    bool valueWasAllocated = false;
    if (attrib == nsMsgSearchAttrib::Date)
    {
      // note that there used to be code here that encoded an RFC822 date for imap searches.
      // The IMAP RFC 2060 is misleading to the point that it looks like it requires an RFC822
      // date but really it expects dd-mmm-yyyy, like dredd, and refers to the RFC822 date only in that the
      // dd-mmm-yyyy date will match the RFC822 date within the message.

      PRTime adjustedDate;
      searchValue->GetDate(&adjustedDate);
      if (whichMnemonic == m_kImapSince)
      {
        // it looks like the IMAP server searches on Since includes the date in question...
        // our UI presents Is, IsGreater and IsLessThan. For the IsGreater case (m_kImapSince)
        // we need to adjust the date so we get greater than and not greater than or equal to which
        // is what the IMAP server wants to search on
        // won't work on Mac.
        // ack, is this right? is PRTime seconds or microseconds?
        PRInt64 microSecondsPerSecond, secondsInDay, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_UI2L(secondsInDay, 60 * 60 * 24);
        LL_MUL(microSecondsInDay, secondsInDay, microSecondsPerSecond);
        LL_ADD(adjustedDate, adjustedDate, microSecondsInDay); // bump up to the day after this one...
      }

      PRExplodedTime exploded;
      PR_ExplodeTime(adjustedDate, PR_LocalTimeParameters, &exploded);
      PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
      //    strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (/* &term->m_value.u.date */ &adjustedDate));
      value = dateBuf;
    }
    else
    {
      if (attrib == nsMsgSearchAttrib::AgeInDays)
      {
        // okay, take the current date, subtract off the age in days, then do an appropriate Date search on
        // the resulting day.
        PRInt32 ageInDays;

        searchValue->GetAge(&ageInDays);

        PRTime now = PR_Now();
        PRTime matchDay;

        PRInt64 microSecondsPerSecond, secondsInDays, microSecondsInDay;

        LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
        LL_I2L(secondsInDays, 60 * 60 * 24 * ageInDays);
        LL_MUL(microSecondsInDay, secondsInDays, microSecondsPerSecond);

        LL_SUB(matchDay, now, microSecondsInDay); // = now - term->m_value.u.age * 60 * 60 * 24;
        PRExplodedTime exploded;
        PR_ExplodeTime(matchDay, PR_LocalTimeParameters, &exploded);
        PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded);
        //      strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (&matchDay));
        value = dateBuf;
      }
      else if (attrib == nsMsgSearchAttrib::Size)
      {
        PRUint32 sizeValue;
        nsCAutoString searchTermValue;
        searchValue->GetSize(&sizeValue);

        // Multiply by 1024 to get into kb resolution
        sizeValue *= 1024;

        // Ensure that greater than is really greater than
        // in kb resolution.
        if (op == nsMsgSearchOp::IsGreaterThan)
          sizeValue += 1024;

        searchTermValue.AppendInt(sizeValue);

        value = ToNewCString(searchTermValue);
        valueWasAllocated = true;
      }
      else

      if (IS_STRING_ATTRIBUTE(attrib))
      {
        PRUnichar *convertedValue; // = reallyDredd ? MSG_EscapeSearchUrl (term->m_value.u.string) : msg_EscapeImapSearchProtocol(term->m_value.u.string);
        nsString searchTermValue;
        searchValue->GetStr(searchTermValue);
        // Ugly switch for Korean mail/news charsets.
        // We want to do this here because here is where
        // we know what charset we want to use.
#ifdef DOING_CHARSET
        if (reallyDredd)
          dest_csid = INTL_DefaultNewsCharSetID(dest_csid);
        else
          dest_csid = INTL_DefaultMailCharSetID(dest_csid);
#endif

        // do all sorts of crazy escaping
        convertedValue = reallyDredd ? EscapeSearchUrl (searchTermValue.get()) :
        EscapeImapSearchProtocol(searchTermValue.get());
        useQuotes = ((!reallyDredd ||
                    (nsDependentString(convertedValue).FindChar(PRUnichar(' ')) != -1)) &&
           (attrib != nsMsgSearchAttrib::Keywords));
        // now convert to char* and escape quoted_specials
        nsCAutoString valueStr;
        nsresult rv = ConvertFromUnicode(NS_LossyConvertUTF16toASCII(destCharset).get(),
          nsDependentString(convertedValue), valueStr);
        if (NS_SUCCEEDED(rv))
        {
          const char *vptr = valueStr.get();
          // max escaped length is one extra character for every character in the cmd.
          nsAutoArrayPtr<char> newValue(new char[2*strlen(vptr) + 1]);
          if (newValue)
          {
            char *p = newValue;
            while (1)
            {
              char ch = *vptr++;
              if (!ch)
                break;
              if ((useQuotes ? ch == '"' : 0) || ch == '\\')
                *p++ = '\\';
              *p++ = ch;
            }
            *p = '\0';
            value = strdup(newValue); // realloc down to smaller size
          }
        }
        else
          value = strdup("");
        NS_Free(convertedValue);
        valueWasAllocated = true;

      }
    }

    // this should be rewritten to use nsCString
    int subLen =
      (value ? strlen(value) : 0) +
      (useNot ? strlen(m_kImapNot) : 0) +
      strlen(m_kImapHeader);
    int len = strlen(whichMnemonic) + subLen + (useQuotes ? 2 : 0) +
      (orHeaderMnemonic
       ? (subLen + strlen(m_kImapOr) + strlen(orHeaderMnemonic) + 2 /*""*/)
       : 0) +
      10; // add slough for imap string literals
    char *encoding = new char[len];
    if (encoding)
    {
      encoding[0] = '\0';
      // Remember: if ToOrCC and useNot then the expression becomes NOT To AND Not CC as opposed to (NOT TO) || (NOT CC)
      if (orHeaderMnemonic && !useNot)
        PL_strcat(encoding, m_kImapOr);
      if (useNot)
        PL_strcat (encoding, m_kImapNot);
      if (!arbitraryHeader.IsEmpty())
        PL_strcat (encoding, m_kImapHeader);
      PL_strcat (encoding, whichMnemonic);
      if (!ignoreValue)
        err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);

      if (orHeaderMnemonic)
      {
        if (useNot)
          PL_strcat(encoding, m_kImapNot);

        PL_strcat (encoding, m_kImapHeader);

        PL_strcat (encoding, orHeaderMnemonic);
        if (!ignoreValue)
          err = EncodeImapValue(encoding, value, useQuotes, reallyDredd);
      }

      // kmcentee, don't let the encoding end with whitespace,
      // this throws off later url STRCMP
      if (*encoding && *(encoding + strlen(encoding) - 1) == ' ')
        *(encoding + strlen(encoding) - 1) = '\0';
    }

    if (value && valueWasAllocated)
      NS_Free (value);

    *ppOutTerm = encoding;

    return err;
}
Exemplo n.º 25
0
NS_IMETHODIMP
nsLDAPOperation::SearchExt(const nsACString& aBaseDn, PRInt32 aScope,
                           const nsACString& aFilter,
                           const nsACString &aAttributes,
                           PRIntervalTime aTimeOut, PRInt32 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 = nsnull;
    PRUint32 origLength = attrArray.Length();
    if (origLength)
    {
      attrs = static_cast<char **> (NS_Alloc((origLength + 1) * sizeof(char *)));
      if (!attrs)
        return NS_ERROR_OUT_OF_MEMORY;

      for (PRUint32 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;
}
Exemplo n.º 26
0
//-------------------------------------------------------------------------
//
// Show - Display the file dialog
//
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::Show(PRInt16 *retval)
{
  NS_ENSURE_ARG_POINTER(retval);

  PRBool result = PR_FALSE;
  nsCAutoString fileBuffer;
  char *converted = ConvertToFileSystemCharset(mDefault);
  if (nsnull == converted) {
    LossyCopyUTF16toASCII(mDefault, fileBuffer);
  }
  else {
    fileBuffer.Assign(converted);
    nsMemory::Free( converted );
  }

  char *title = ConvertToFileSystemCharset(mTitle);
  if (nsnull == title)
    title = ToNewCString(mTitle);
  nsCAutoString initialDir;
  if (mDisplayDirectory)
    mDisplayDirectory->GetNativePath(initialDir);
  // If no display directory, re-use the last one.
  if(initialDir.IsEmpty())
    initialDir = mLastUsedDirectory;

  mFile.Truncate();

  FILEDLG filedlg;
  memset(&filedlg, 0, sizeof(FILEDLG));
  filedlg.cbSize = sizeof(FILEDLG);
  filedlg.pszTitle = title;

  if (mMode == modeGetFolder) {
    PL_strncat(filedlg.szFullFile, initialDir.get(), MAX_PATH);
    PL_strncat(filedlg.szFullFile, "\\", 1);
    PL_strncat(filedlg.szFullFile, "^", 1);
    filedlg.fl = FDS_OPEN_DIALOG | FDS_CENTER;
    filedlg.pfnDlgProc = DirDialogProc;
    DosError(FERR_DISABLEHARDERR);
    WinFileDlg(HWND_DESKTOP, mWnd, &filedlg);
    DosError(FERR_ENABLEHARDERR);
    char* tempptr = strstr(filedlg.szFullFile, "^");
    if (tempptr)
      *tempptr = '\0';
    if (filedlg.lReturn == DID_OK) {
      result = PR_TRUE;
      if (!mDisplayDirectory)
        mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
      if (mDisplayDirectory)
        mDisplayDirectory->InitWithNativePath(nsDependentCString(filedlg.szFullFile));
      mFile.Assign(filedlg.szFullFile);
    }
  }
  else {
    PL_strncpy(filedlg.szFullFile, initialDir.get(), MAX_PATH);
    PL_strncat(filedlg.szFullFile, "\\", 1);
    PL_strncat(filedlg.szFullFile, fileBuffer.get(), MAX_PATH);
    filedlg.fl = FDS_CENTER;
    if (mMode == modeSave) {
       filedlg.fl |= FDS_SAVEAS_DIALOG | FDS_ENABLEFILELB;
    } else if (mMode == modeOpenMultiple) {
       filedlg.fl |= FDS_MULTIPLESEL | FDS_OPEN_DIALOG;
    } else {
       filedlg.fl |= FDS_OPEN_DIALOG;
    }
    PMYDATA pmydata;
    pmydata = (PMYDATA)calloc(1, sizeof(MYDATA));
    filedlg.ulUser = (ULONG)pmydata;
    filedlg.pfnDlgProc = FileDialogProc;

    PRUint32 i;

    PSZ *apszTypeList;
    apszTypeList = (PSZ *)malloc(mTitles.Length()*sizeof(PSZ)+1);
    for (i = 0; i < mTitles.Length(); i++)
    {
      const nsString& typeWide = mTitles[i];
      nsAutoCharBuffer buffer;
      PRInt32 bufLength;
      WideCharToMultiByte(0, typeWide.get(), typeWide.Length(),
                          buffer, bufLength);
      apszTypeList[i] = ToNewCString(nsDependentCString(buffer.Elements()));
    }
    apszTypeList[i] = 0;
    filedlg.papszITypeList = (PAPSZ)apszTypeList;

    PSZ *apszFilterList;
    apszFilterList = (PSZ *)malloc(mFilters.Length()*sizeof(PSZ)+1);
    for (i = 0; i < mFilters.Length(); i++)
    {
      const nsString& filterWide = mFilters[i];
      apszFilterList[i] = ToNewCString(filterWide);
    }
    apszFilterList[i] = 0;
    pmydata->papszIFilterList = (PAPSZ)apszFilterList;

    pmydata->ulCurExt = mSelectedType;

    PRBool fileExists;
    do {
      DosError(FERR_DISABLEHARDERR);
      WinFileDlg(HWND_DESKTOP, mWnd, &filedlg);
      DosError(FERR_ENABLEHARDERR);
      if ((filedlg.lReturn == DID_OK) && (mMode == modeSave)) {
         PRFileInfo64 fileinfo64;
         PRStatus status = PR_GetFileInfo64(filedlg.szFullFile, &fileinfo64);
         if (status == PR_SUCCESS) {
            fileExists = PR_TRUE;
         } else {
            fileExists = PR_FALSE;
         }
         if (fileExists) {
            if (!gpszFDSaveCaption) {
              HMODULE hmod;
              char LoadError[CCHMAXPATH];
              char loadedString[256];
              int length;
              DosLoadModule(LoadError, CCHMAXPATH, "PMSDMRI", &hmod);
              length = WinLoadString((HAB)0, hmod, 1110, 256, loadedString);
              gpszFDSaveCaption = (char*)malloc(length+1);
              strcpy(gpszFDSaveCaption, loadedString);
              length = WinLoadString((HAB)0, hmod, 1135, 256, loadedString);
              gpszFDFileExists = (char*)malloc(length+1);
              strcpy(gpszFDFileExists, loadedString);
              length = WinLoadString((HAB)0, hmod, 1136, 256, loadedString);
              gpszFDFileReadOnly = (char*)malloc(length+1);
              strcpy(gpszFDFileReadOnly, loadedString);
              int i;
              for (i=0;i<256 && gpszFDFileExists[i];i++ ) {
                if (gpszFDFileExists[i] == '%') {
                  gpszFDFileExists[i+1] = 's';
                  break;
                }
              }
              for (i=0;i<256 && gpszFDFileReadOnly[i];i++ ) {
                if (gpszFDFileReadOnly[i] == '%') {
                  gpszFDFileReadOnly[i+1] = 's';
                  break;
                }
              }
              DosFreeModule(hmod);

            }
            char pszFullText[256+CCHMAXPATH];
            FILESTATUS3 fsts3;
            ULONG ulResponse;
            DosQueryPathInfo( filedlg.szFullFile, FIL_STANDARD, &fsts3, sizeof(FILESTATUS3));
            if (fsts3.attrFile & FILE_READONLY) {
              sprintf(pszFullText, gpszFDFileReadOnly, filedlg.szFullFile);
              ulResponse = WinMessageBox(HWND_DESKTOP, mWnd, pszFullText,
                                               gpszFDSaveCaption, 0,
                                               MB_OK | MB_MOVEABLE | MB_WARNING);
            } else {
              sprintf(pszFullText, gpszFDFileExists, filedlg.szFullFile);
              ulResponse = WinMessageBox(HWND_DESKTOP, mWnd, pszFullText,
                                               gpszFDSaveCaption, 0,
                                               MB_YESNO | MB_MOVEABLE | MB_WARNING);
            }

            if (ulResponse == MBID_YES) {
               fileExists = PR_FALSE;
            }
         }
      }
    } while (mMode == modeSave && fileExists && filedlg.lReturn == DID_OK);

    if (filedlg.lReturn == DID_OK) {
      result = PR_TRUE;
      if (mMode == modeOpenMultiple) {
        nsresult rv;

        if (filedlg.papszFQFilename) {
          for (ULONG i=0;i<filedlg.ulFQFCount;i++) {
            nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
            NS_ENSURE_SUCCESS(rv,rv);

            rv = file->InitWithNativePath(nsDependentCString(*(filedlg.papszFQFilename)[i]));
            NS_ENSURE_SUCCESS(rv,rv);

            rv = mFiles.AppendObject(file);
            NS_ENSURE_SUCCESS(rv,rv);
          }
          WinFreeFileDlgList(filedlg.papszFQFilename);
        } else {
          nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
          NS_ENSURE_SUCCESS(rv,rv);

          rv = file->InitWithNativePath(nsDependentCString(filedlg.szFullFile));
          NS_ENSURE_SUCCESS(rv,rv);

          rv = mFiles.AppendObject(file);
          NS_ENSURE_SUCCESS(rv,rv);
        }
      } else {
        mFile.Assign(filedlg.szFullFile);
      }
      mSelectedType = (PRInt16)pmydata->ulCurExt;
    }

    for (i = 0; i < mTitles.Length(); i++)
    {
      nsMemory::Free(*(filedlg.papszITypeList[i]));
    }
    free(filedlg.papszITypeList);

    for (i = 0; i < mFilters.Length(); i++)
    {
      nsMemory::Free(*(pmydata->papszIFilterList[i]));
    }
    free(pmydata->papszIFilterList);
    free(pmydata);
  }

  if (title)
    nsMemory::Free( title );

  if (result) {
    PRInt16 returnOKorReplace = returnOK;

    nsresult rv;
    // Remember last used directory.
    nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    file->InitWithNativePath(mFile);
    nsCOMPtr<nsIFile> dir;
    if (NS_SUCCEEDED(file->GetParent(getter_AddRefs(dir)))) {
      nsCOMPtr<nsILocalFile> localDir(do_QueryInterface(dir));
      if (localDir) {
        nsCAutoString newDir;
        localDir->GetNativePath(newDir);
        if(!newDir.IsEmpty())
          PL_strncpyz(mLastUsedDirectory, newDir.get(), MAX_PATH+1);
        // Update mDisplayDirectory with this directory, also.
        // Some callers rely on this.
        if (!mDisplayDirectory)
           mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
        if (mDisplayDirectory)
           mDisplayDirectory->InitWithNativePath( nsDependentCString(mLastUsedDirectory) );
      }
    }

    if (mMode == modeSave) {
      // Windows does not return resultReplace,
      //   we must check if file already exists
      PRBool exists = PR_FALSE;
      file->Exists(&exists);
      if (exists)
        returnOKorReplace = returnReplace;
    }
    *retval = returnOKorReplace;
  }
  else {
    *retval = returnCancel;
  }
  return NS_OK;
}
Exemplo n.º 27
0
int
main(int argc, char* argv[])
{
  if (test_common_init(&argc, &argv) != 0)
    return -1;

  nsresult ret;


  nsCOMPtr<nsIServiceManager> servMan;
  NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
  nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
  NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
  registrar->AutoRegister(nsnull);

  nsIInputStream* in = nsnull;

  nsCOMPtr<nsIIOService> service(do_GetService(kIOServiceCID, &ret));
  if (NS_FAILED(ret)) return ret;

  nsCOMPtr<nsIEventQueueService> eventQService = 
           do_GetService(kEventQueueServiceCID, &ret);
  if (NS_FAILED(ret)) return ret;

  nsIChannel *channel = nsnull;
  ret = service->NewChannel(NS_LITERAL_CSTRING(TEST_URL), nsnull, nsnull, &channel);
  if (NS_FAILED(ret)) return ret;

  nsIEventQueue *eventQ = nsnull;
  ret = eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, &eventQ);
  if (NS_FAILED(ret)) return ret;

  ret = channel->Open(&in);
  if (NS_FAILED(ret)) return ret;

  nsIPersistentProperties* props;
  ret = CallCreateInstance(kPersistentPropertiesCID, &props);
  if (NS_FAILED(ret) || (!props)) {
    printf("create nsIPersistentProperties failed\n");
    return 1;
  }
  ret = props->Load(in);
  if (NS_FAILED(ret)) {
    printf("cannot load properties\n");
    return 1;
  }
  int i = 1;
  while (1) {
    char name[16];
    name[0] = 0;
    sprintf(name, "%d", i);
    nsAutoString v;
    ret = props->GetStringProperty(nsDependentCString(name), v);
    if (NS_FAILED(ret) || (!v.Length())) {
      break;
    }
    char* value = ToNewCString(v);
    if (value) {
      printf("\"%d\"=\"%s\"\n", i, value);
      delete[] value;
    }
    else {
      printf("%d: ToNewCString failed\n", i);
    }
    i++;
  }

  nsCOMPtr<nsISimpleEnumerator> propEnum;
  ret = props->Enumerate(getter_AddRefs(propEnum));

  if (NS_FAILED(ret)) {
    printf("cannot enumerate properties\n");
    return 1;
  }
  

  printf("\nKey\tValue\n");
  printf(  "---\t-----\n");
  
  PRBool hasMore;
  while (NS_SUCCEEDED(propEnum->HasMoreElements(&hasMore)) &&
         hasMore) {
    nsCOMPtr<nsISupports> sup;
    ret = propEnum->GetNext(getter_AddRefs(sup));
    
    nsCOMPtr<nsIPropertyElement> propElem = do_QueryInterface(sup, &ret);
	  if (NS_FAILED(ret)) {
      printf("failed to get current item\n");
      return 1;
	  }

    nsCAutoString key;
    nsAutoString value;

    ret = propElem->GetKey(key);
	  if (NS_FAILED(ret)) {
		  printf("failed to get current element's key\n");
		  return 1;
	  }
    ret = propElem->GetValue(value);
	  if (NS_FAILED(ret)) {
		  printf("failed to get current element's value\n");
		  return 1;
	  }

    printf("%s\t%s\n", key.get(), NS_ConvertUTF16toUTF8(value).get());
  }
  return 0;
}
Exemplo n.º 28
0
NS_CStringCloneData(const nsACString& aStr)
{
  return ToNewCString(aStr);
}
Exemplo n.º 29
0
NS_IMETHODIMP 
nsSystemPrincipal::GetOrigin(char** aOrigin)
{
    *aOrigin = ToNewCString(NS_LITERAL_CSTRING("[System]"));
    return *aOrigin ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
Exemplo n.º 30
0
NS_IMETHODIMP nsMsgCompFields::GetDefaultCharacterSet(char * *aDefaultCharacterSet)
{
  NS_ENSURE_ARG_POINTER(aDefaultCharacterSet);
  *aDefaultCharacterSet = ToNewCString(m_DefaultCharacterSet);
  return *aDefaultCharacterSet ? NS_OK : NS_ERROR_OUT_OF_MEMORY; 
}