static
char *createFullPathName(
        char *dirName,
        char *certFile,
        void *plContext)
{
        PKIX_UInt32 certFileLen;
        PKIX_UInt32 dirNameLen;
        char *certPathName = NULL;

        PKIX_TEST_STD_VARS();

        certFileLen = PL_strlen(certFile);
        dirNameLen = PL_strlen(dirName);

        PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Malloc
                (dirNameLen + certFileLen + 2,
                (void **)&certPathName,
                plContext));

        PL_strcpy(certPathName, dirName);
        PL_strcat(certPathName, "/");
        PL_strcat(certPathName, certFile);
        printf("certPathName = %s\n", certPathName);

cleanup:

        PKIX_TEST_RETURN();

        return (certPathName);
}
Ejemplo n.º 2
0
static char *
catDirName(char *platform, char *dir, void *plContext)
{
    char *pathName = NULL;
    PKIX_UInt32 dirLen;
    PKIX_UInt32 platformLen;

    PKIX_TEST_STD_VARS();

    dirLen = PL_strlen(dir);
    platformLen = PL_strlen(platform);

    PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Malloc(platformLen +
                                                 dirLen +
                                                 2,
                                             (void **)&pathName, plContext));

    PL_strcpy(pathName, platform);
    PL_strcat(pathName, "/");
    PL_strcat(pathName, dir);

cleanup:

    PKIX_TEST_RETURN();

    return (pathName);
}
static char *catDirName(char *dir, char *name, void *plContext)
{
        char *pathName = NULL;
        PKIX_UInt32 nameLen;
        PKIX_UInt32 dirLen;

        PKIX_TEST_STD_VARS();

        nameLen = PL_strlen(name);
        dirLen = PL_strlen(dir);

        PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Malloc
                                    (dirLen + nameLen + 2,
                                    (void **)&pathName,
                                    plContext));

        PL_strcpy(pathName, dir);
        PL_strcat(pathName, "/");
        PL_strcat(pathName, name);
        printf("pathName = %s\n", pathName);

cleanup:

        PKIX_TEST_RETURN();

        return (pathName);
}
Ejemplo n.º 4
0
/**
 * returns a string containing all the parameters in the ConfigStore hash set in the 
 * format key1=value1&&key2=value2&& ...
 * The list will be lexically ordered by parameter key values.
 * The string needs to be freed by the caller.
 **/
TPS_PUBLIC const char* ConfigStore::GetOrderedList()
{
    char *outstr = NULL;
    char *new_string = NULL;
    PRCList order_list;
    PR_INIT_CLIST(&order_list);

    PR_Lock(m_lock);
    PL_HashTableEnumerateEntries(m_root->getSet(), &OrderLoop, &order_list);
    PR_Unlock(m_lock);

    PRCList *current = PR_LIST_HEAD(&order_list);
    PRCList *next;

    outstr = (char*) PR_Malloc(128);
    int allocated = 128;
    int needed = 0;
    PR_snprintf(outstr, 128, "");

    while (current != &order_list) {
        OrderedEntry_t *entry = (OrderedEntry_t *) current;
        const char *value = GetConfigAsString(entry->key, "");

        if ((entry != NULL) && (entry->key != NULL)) {
            needed = PL_strlen(outstr) + PL_strlen(entry->key) + PL_strlen(value) + 4;
            if (allocated <= needed) {
                while (allocated <= needed) {
                    allocated = allocated * 2;
                }
                new_string = (char *)PR_Malloc(allocated);
                PR_snprintf(new_string, allocated, "%s", outstr);
                PR_Free(outstr);
                outstr = new_string;
            } 
                
            PL_strcat(outstr, entry->key);
            PL_strcat(outstr, "=");
            PL_strcat(outstr, value);

            // free the memory for the Ordered Entry
            PL_strfree(entry->key);
        }

        next = PR_NEXT_LINK(current);
        PR_REMOVE_AND_INIT_LINK(current);
        if (current != NULL) {
            PR_Free(current);
        }
        current = next;

        if (current != &order_list) PL_strcat(outstr, "&&");
    }
    return outstr;
}
static const nsIID
getSwarmIID (const char *interfaceName)
{
  nsIID iid;
  nsIID default_iid = NS_GET_IID (nsISupports);

  if (interfaceName)
    {
      char *buf = (char *) malloc (6 + PL_strlen (interfaceName) + 1);
      const nsIID *iidptr;

      if (buf == NULL)
        abort ();
      PL_strcpy (buf, "swarmI");
      PL_strcat (buf, interfaceName);
      
      if ((iidptr = findIIDFromName (buf)))
        iid = *iidptr;
      else
        iid = default_iid;
      free (buf);
    }
  else
    iid = default_iid;

  return iid;
}
Ejemplo n.º 6
0
nsresult nsMsgSearchAdapter::EncodeImapValue(char *encoding, const char *value, bool useQuotes, bool reallyDredd)
{
  // By NNTP RFC, SEARCH HEADER SUBJECT "" is legal and means 'find messages without a subject header'
  if (!reallyDredd)
  {
    // By IMAP RFC, SEARCH HEADER SUBJECT "" is illegal and will generate an error from the server
    if (!value || !value[0])
      return NS_ERROR_NULL_POINTER;
  }

  if (!NS_IsAscii(value))
  {
    nsCAutoString lengthStr;
    PL_strcat(encoding, "{");
    lengthStr.AppendInt((PRInt32) strlen(value));
    PL_strcat(encoding, lengthStr.get());
    PL_strcat(encoding, "}" CRLF);
    PL_strcat(encoding, value);
    return NS_OK;
  }
  if (useQuotes)
    PL_strcat(encoding, "\"");
  PL_strcat (encoding, value);
  if (useQuotes)
    PL_strcat(encoding, "\"");

  return NS_OK;
}
Ejemplo n.º 7
0
static char *
AppendAndAlloc(char *string, const char *newSubstring, bool withComma)
{
    if (!newSubstring) return NULL;
    
    if (!string) return PL_strdup(newSubstring);
    
    char *separator = (char *) (withComma ? ", " : " ");
    char *oldString = string;
    
    string = (char *)PR_Calloc(PL_strlen(oldString) +
                               PL_strlen(separator) +
                               PL_strlen(newSubstring) + 1,
                               sizeof(char));
    
    PL_strcpy(string, oldString);
    PL_strcat(string, separator);
    PL_strcat(string, newSubstring);

    PR_Free(oldString);
    return string;
}
Ejemplo n.º 8
0
int nsMsgSendPart::AppendOtherHeaders(const char* more)
{
  if (!m_other)
    return SetOtherHeaders(more);

  if (!more || !*more)
    return 0;

  char* tmp = (char *) PR_Malloc(sizeof(char) * (PL_strlen(m_other) + PL_strlen(more) + 2));
  if (!tmp)
    return NS_ERROR_OUT_OF_MEMORY;

  PL_strcpy(tmp, m_other);
  PL_strcat(tmp, more);
  PR_FREEIF(m_other);
  m_other = tmp;

  return 0;
}
COMclass
COMfindComponent (const char *className)
{
  const char *prefix = "urn:";
  const char *modulePrefix = "swarm/";
  size_t prefixLen = PL_strlen (prefix);
  size_t modulePrefixLen = PL_strlen (modulePrefix);
  nsCID *cClass = new nsCID ();
  size_t classNameLen = PL_strlen (className);
  char *buf = (char *) malloc (prefixLen + classNameLen + 1);
  if (!buf)
    abort ();
  nsresult rv;

  PL_strcpy (buf, prefix);
  PL_strcat (buf, className);
  if (PL_strncmp (className, modulePrefix, modulePrefixLen) == 0)
    {
      unsigned i;

      buf[prefixLen + 5] = ':';
      for (i = modulePrefixLen; i < classNameLen; i++)
        {
          unsigned pos = prefixLen + i;
          
          if (buf[pos] == '/')
            buf[pos] = '.';
        }
    }
  nsCOMPtr<nsIComponentManager> compMgr;
  NS_GetComponentManager (getter_AddRefs (compMgr));  
  if (!compMgr)
    abort ();
  nsCOMPtr<nsIComponentManagerObsolete> compMgrO = do_QueryInterface (compMgr);
  rv = compMgrO->ContractIDToClassID (buf, cClass);
  free (buf);
 
  if (NS_FAILED (rv))
    abort ();
  return (COMclass) cClass;
}
Ejemplo n.º 10
0
static void SearchForSoname(const char* name, char** soname)
{
    if (!(name && soname))
        return;
    PRDir *fdDir = PR_OpenDir(DEFAULT_X11_PATH);
    if (!fdDir)
        return;       

    int n = PL_strlen(name);
    PRDirEntry *dirEntry;
    while ((dirEntry = PR_ReadDir(fdDir, PR_SKIP_BOTH))) {
        if (!PL_strncmp(dirEntry->name, name, n)) {
            if (dirEntry->name[n] == '.' && dirEntry->name[n+1] && !dirEntry->name[n+2]) {
                // name.N, wild guess this is what we need
                char out[PLUGIN_MAX_LEN_OF_TMP_ARR] = DEFAULT_X11_PATH;
                PL_strcat(out, dirEntry->name);
                *soname = PL_strdup(out);
               break;
            }
        }
    }

    PR_CloseDir(fdDir);
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
0
/*
 * FUNCTION: pkix_pl_helperBytes2Ascii
 * DESCRIPTION:
 *
 *  Converts an array of integers pointed to by "tokens" with a length of
 *  "numTokens", to an ASCII string consisting of those integers with dots in
 *  between them and stores the result at "pAscii". The ASCII representation is
 *  guaranteed to end with a NUL character. This is particularly useful for
 *  OID's and IP Addresses.
 *
 *  The return value "pAscii" is not reference-counted and will need to
 *  be freed with PKIX_PL_Free.
 *
 * PARAMETERS
 *  "tokens"
 *      Address of array of integers. Must be non-NULL.
 *  "numTokens"
 *      Length of array of integers. Must be non-zero.
 *  "pAscii"
 *      Address where object pointer will be stored. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns an Object Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
pkix_pl_helperBytes2Ascii(
        PKIX_UInt32 *tokens,
        PKIX_UInt32 numTokens,
        char **pAscii,
        void *plContext)
{
        char *tempString = NULL;
        char *outputString = NULL;
        char *format = "%d";
        PKIX_UInt32 i = 0;
        PKIX_UInt32 outputLen = 0;
        PKIX_Int32 error;

        PKIX_ENTER(OBJECT, "pkix_pl_helperBytes2Ascii");
        PKIX_NULLCHECK_TWO(tokens, pAscii);

        if (numTokens == 0) {
                PKIX_ERROR_FATAL(PKIX_HELPERBYTES2ASCIINUMTOKENSZERO);
        }

        /*
         * tempString will hold the string representation of a PKIX_UInt32 type
         * The maximum value that can be held by an unsigned 32-bit integer
         * is (2^32 - 1) = 4294967295 (which is ten digits long)
         * Since tempString will hold the string representation of a
         * PKIX_UInt32, we allocate 11 bytes for it (1 byte for '\0')
         */

        PKIX_CHECK(PKIX_PL_Malloc
                    (MAX_DIGITS_32 + 1, (void **)&tempString, plContext),
                    PKIX_MALLOCFAILED);

        for (i = 0; i < numTokens; i++){
                PKIX_OBJECT_DEBUG("\tCalling PR_snprintf).\n");
                error = PR_snprintf(tempString,
                                    MAX_DIGITS_32 + 1,
                                    format,
                                    tokens[i]);
                if (error == -1){
                        PKIX_ERROR(PKIX_PRSNPRINTFFAILED);
                }

                PKIX_OBJECT_DEBUG("\tCalling PL_strlen).\n");
                outputLen += PL_strlen(tempString);

                /* Include a dot to separate each number */
                outputLen++;
        }

        /* Allocate space for the destination string */
        PKIX_CHECK(PKIX_PL_Malloc
                    (outputLen, (void **)&outputString, plContext),
                    PKIX_MALLOCFAILED);

        *outputString = '\0';

        /* Concatenate all strings together */
        for (i = 0; i < numTokens; i++){

                PKIX_OBJECT_DEBUG("\tCalling PR_snprintf).\n");
                error = PR_snprintf(tempString,
                                    MAX_DIGITS_32 + 1,
                                    format,
                                    tokens[i]);
                if (error == -1){
                        PKIX_ERROR(PKIX_PRSNPRINTFFAILED);
                }

                PKIX_OBJECT_DEBUG("\tCalling PL_strcat).\n");
                (void) PL_strcat(outputString, tempString);

                /* we don't want to put a "." at the very end */
                if (i < (numTokens - 1)){
                        PKIX_OBJECT_DEBUG("\tCalling PL_strcat).\n");
                        (void) PL_strcat(outputString, ".");
                }
        }

        /* Ensure output string ends with terminating null */
        outputString[outputLen-1] = '\0';

        *pAscii = outputString;
        outputString = NULL;

cleanup:
        
        PKIX_FREE(outputString);
        PKIX_FREE(tempString);

        PKIX_RETURN(OBJECT);

}
Ejemplo n.º 13
0
/*
 * FUNCTION: pkix_pl_CollectionCertStoreContext_PopulateCRL
 * DESCRIPTION:
 *
 *  Create list of CRLs from *.crl files at directory specified in dirName,
 *  Not recursive to sub-dirctory. Also assume the directory contents are
 *  not changed dynamically.
 *
 * PARAMETERS
 *  "colCertStoreContext" - Address of CollectionCertStoreContext
 *              where the dirName is specified and where the return
 *              CRLs are stored as a list. Must be non-NULL.
 *  "plContext" - Platform-specific context pointer.
 *
 * THREAD SAFETY:
 *  Not Thread Safe - A lock at top level is required.
 *
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a CollectionCertStoreContext Error if the function fails in
 *              a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
static PKIX_Error *
pkix_pl_CollectionCertStoreContext_PopulateCRL(
        PKIX_PL_CollectionCertStoreContext *colCertStoreContext,
        void *plContext)
{
        PKIX_List *crlList = NULL;
        PKIX_PL_CRL *crlItem = NULL;
        char *dirName = NULL;
        char *pathName = NULL;
        PKIX_UInt32 dirNameLen = 0;
        PRErrorCode prError = 0;
        PRDir *dir = NULL;
        PRDirEntry *dirEntry = NULL;

        PKIX_ENTER(COLLECTIONCERTSTORECONTEXT,
                    "pkix_pl_CollectionCertStoreContext_PopulateCRL");
        PKIX_NULLCHECK_ONE(colCertStoreContext);

        /* convert directory to ascii */

        PKIX_CHECK(PKIX_PL_String_GetEncoded
                    (colCertStoreContext->storeDir,
                    PKIX_ESCASCII,
                    (void **)&dirName,
                    &dirNameLen,
                    plContext),
                    PKIX_STRINGGETENCODEDFAILED);

        /* create CRL list, if no CRL file, should return an empty list */

        PKIX_CHECK(PKIX_List_Create(&crlList, plContext),
                    PKIX_LISTCREATEFAILED);

        /* open directory and read in .crl files */

        PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG("\t\t Calling PR_OpenDir.\n");
        dir = PR_OpenDir(dirName);

        if (!dir) {
                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG_ARG
                        ("\t\t Directory Name:%s\n", dirName);
                PKIX_ERROR(PKIX_CANNOTOPENCOLLECTIONCERTSTORECONTEXTDIRECTORY);
        }

        PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG("\t\t Calling PR_ReadDir.\n");
        dirEntry = PR_ReadDir(dir, PR_SKIP_HIDDEN | PR_SKIP_BOTH);

        if (!dirEntry) {
                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Empty directory.\n");
                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Calling PR_GetError.\n");
                prError = PR_GetError();
        }

        PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG("\t\t Calling PR_SetError.\n");
        PR_SetError(0, 0);

        while (dirEntry != NULL && prError == 0) {
                if (PL_strrstr(dirEntry->name, ".crl") ==
                    dirEntry->name + PL_strlen(dirEntry->name) - 4) {

                        PKIX_CHECK_ONLY_FATAL
                                (PKIX_PL_Malloc
                                (dirNameLen + PL_strlen(dirEntry->name) + 2,
                                (void **)&pathName,
                                plContext),
                                PKIX_MALLOCFAILED);

                        if ((!PKIX_ERROR_RECEIVED) && (pathName != NULL)){

                                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                                    ("\t\t Calling PL_strcpy for dirName.\n");
                                PL_strcpy(pathName, dirName);
                                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                                    ("\t\t Calling PL_strcat for dirName.\n");
                                PL_strcat(pathName, "/");
                                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                                        ("\t\t Calling PL_strcat for /.\n");
                                PL_strcat(pathName, dirEntry->name);

                        PKIX_CHECK_ONLY_FATAL
                                (pkix_pl_CollectionCertStoreContext_CreateCRL
                                (pathName, &crlItem, plContext),
                                PKIX_COLLECTIONCERTSTORECONTEXTCREATECRLFAILED);

                                if (!PKIX_ERROR_RECEIVED){
                                        PKIX_CHECK_ONLY_FATAL
                                                (PKIX_List_AppendItem
                                                (crlList,
                                                (PKIX_PL_Object *)crlItem,
                                                plContext),
                                                PKIX_LISTAPPENDITEMFAILED);
                                }
                        }

                        PKIX_DECREF(crlItem);
                        PKIX_FREE(pathName);
                }

                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Calling PR_SetError.\n");
                PR_SetError(0, 0);

                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Calling PR_ReadDir.\n");
                dirEntry = PR_ReadDir(dir, PR_SKIP_HIDDEN | PR_SKIP_BOTH);

                if (!dirEntry) {
                    PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Calling PR_GetError.\n");
                    prError = PR_GetError();
                }
        }

        if ((prError != 0) && (prError != PR_NO_MORE_FILES_ERROR)) {
                PKIX_ERROR(PKIX_COLLECTIONCERTSTORECONTEXTGETSELECTCRLFAILED);
        }

        PKIX_CHECK(PKIX_List_SetImmutable(crlList, plContext),
                    PKIX_LISTSETIMMUTABLEFAILED);

        PKIX_INCREF(crlList);
        colCertStoreContext->crlList = crlList;

cleanup:
        if (dir) {
                PKIX_COLLECTIONCERTSTORECONTEXT_DEBUG
                        ("\t\t Calling PR_CloseDir.\n");
                PR_CloseDir(dir);
        }

        PKIX_FREE(pathName);
        PKIX_FREE(dirName);

        if (PKIX_ERROR_RECEIVED){
                PKIX_DECREF(crlList);
        }

        PKIX_DECREF(crlItem);
        PKIX_DECREF(crlList);

        PKIX_RETURN(COLLECTIONCERTSTORECONTEXT);
}
Ejemplo n.º 14
0
/*
 * FUNCTION: pkix_pl_ByteArray_ToHexString
 * DESCRIPTION:
 *
 *  Creates a hex-String representation of the ByteArray pointed to by "array"
 *  and stores the result at "pString". The hex-String consists of hex-digit
 *  pairs separated by spaces, and the entire string enclosed within square
 *  brackets, e.g. [43 61 6E 20 79 6F 75 20 72 65 61 64 20 74 68 69 73 3F].
 *  A zero-length ByteArray is represented as [].
 * PARAMETERS
 *  "array"
 *      ByteArray to be represented by the hex-String; must be non-NULL
 *  "pString"
 *      Address where String will be stored. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a Cert Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
pkix_pl_ByteArray_ToHexString(
        PKIX_PL_ByteArray *array,
        PKIX_PL_String **pString,
        void *plContext)
{
        char *tempText = NULL;
        char *stringText = NULL; /* "[XX XX XX ...]" */
        PKIX_UInt32 i, outputLen, bufferSize;

        PKIX_ENTER(BYTEARRAY, "pkix_pl_ByteArray_ToHexString");
        PKIX_NULLCHECK_TWO(array, pString);

        if ((array->length) == 0) {
                PKIX_CHECK(PKIX_PL_String_Create
                        (PKIX_ESCASCII, "[]", 0, pString, plContext),
                        PKIX_COULDNOTCREATESTRING);
        } else {
                /*
                 * Allocate space for format string
                 * '[' + "XX" + (n-1)*" XX" + ']' + '\0'
                 */
                bufferSize = 2 + (3*(array->length));

                PKIX_CHECK(PKIX_PL_Malloc
                        (bufferSize, (void **)&stringText, plContext),
                        PKIX_COULDNOTALLOCATEMEMORY);

                stringText[0] = 0;
                outputLen = 0;

                PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf).\n");
                tempText = PR_smprintf
                        ("[%02X", (0x0FF&((char *)(array->array))[0]));
                PKIX_BYTEARRAY_DEBUG("\tCalling PL_strlen).\n");
                outputLen += PL_strlen(tempText);

                PKIX_BYTEARRAY_DEBUG("\tCalling PL_strcat).\n");
                stringText = PL_strcat(stringText, tempText);

                PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf_free).\n");
                PR_smprintf_free(tempText);

                for (i = 1; i < array->length; i++) {
                        PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf).\n");
                        tempText = PR_smprintf
                                (" %02X", (0x0FF&((char *)(array->array))[i]));

                        if (tempText == NULL){
                                PKIX_ERROR(PKIX_PRSMPRINTFFAILED);
                        }

                        PKIX_BYTEARRAY_DEBUG("\tCalling PL_strlen).\n");
                        outputLen += PL_strlen(tempText);

                        PKIX_BYTEARRAY_DEBUG("\tCalling PL_strcat).\n");
                        stringText = PL_strcat(stringText, tempText);

                        PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf_free).\n");
                        PR_smprintf_free(tempText);
                        tempText = NULL;
                }

                stringText[outputLen++] = ']';
                stringText[outputLen] = 0;

                PKIX_CHECK(PKIX_PL_String_Create
                        (PKIX_ESCASCII,
                        stringText,
                        0,
                        pString,
                        plContext),
                        PKIX_COULDNOTCREATESTRING);
        }

cleanup:

        PKIX_FREE(stringText);
        PKIX_RETURN(BYTEARRAY);
}
Ejemplo n.º 15
0
/**
 * Commits changes to the config file
 */
TPS_PUBLIC int ConfigStore::Commit(const bool backup, char *error_msg, int len)
{
    char name_tmp[256], cdate[256], name_bak[256], bak_dir[256];
    char basename[256], dirname[256];
    PRFileDesc *ftmp  = NULL;
    PRExplodedTime time;
    PRTime now;
    PRStatus status;

    if (m_cfg_file_path == NULL) {
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): m_cfg_file_path is NULL!");
        return 1;
    }

    if (strrchr(m_cfg_file_path, '/') != NULL) {
        PR_snprintf((char *) basename, 256, "%s", strrchr(m_cfg_file_path, '/') +1);
        PR_snprintf((char *) dirname, PL_strlen(m_cfg_file_path) - PL_strlen(basename), "%s", m_cfg_file_path);
        PL_strcat(dirname, '\0');
    } else {
        PR_snprintf((char *) basename, 256, "%s", m_cfg_file_path);
        PR_snprintf((char *) dirname, 256, ".");
    }
    PR_snprintf(bak_dir, 256, "%s/bak", dirname); 

    now = PR_Now();
    PR_ExplodeTime(now, PR_LocalTimeParameters, &time);
    PR_snprintf(cdate, 16, "%04d%02d%02d%02d%02d%02dZ",
        time.tm_year, (time.tm_month + 1), time.tm_mday,
        time.tm_hour, time.tm_min, time.tm_sec);
    PR_snprintf(name_tmp, 256, "%s.%s.tmp", m_cfg_file_path,cdate);
    PR_snprintf(name_bak, 256, "%s/%s.%s", bak_dir, basename, cdate);

    ftmp = PR_Open(name_tmp, PR_WRONLY| PR_CREATE_FILE, 00400|00200);
    if (ftmp == NULL) {
        // unable to create temporary config file 
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): unable to create temporary config file");
        return 1;
    }

    PRCList order_list;
    PR_INIT_CLIST(&order_list);

    PR_Lock(m_lock);
    PL_HashTableEnumerateEntries(m_root->getSet(), &OrderLoop, &order_list);
    PR_Unlock(m_lock);

    PRCList *current = PR_LIST_HEAD(&order_list);
    PRCList *next;

    while (current != &order_list) {
        OrderedEntry_t *entry = (OrderedEntry_t *) current;
        PR_Write(ftmp, entry->key, PL_strlen(entry->key));
        PR_Write(ftmp, "=", 1);
        const char *value = GetConfigAsString(entry->key, "");
        PR_Write(ftmp, value, PL_strlen(value));
        PR_Write(ftmp, "\n", 1);

        // free the memory for the Ordered Entry
        if (entry->key != NULL)  PL_strfree(entry->key);

        next = PR_NEXT_LINK(current);
        PR_REMOVE_AND_INIT_LINK(current);
        if (current != NULL) {
            PR_Free(current);
        }
        current = next;
    }

    PR_Close(ftmp);

    if (backup) { 
        // create the backup directory if it does not exist
        if (PR_Access(bak_dir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
            PR_MkDir(bak_dir, 00770);
        } 
        status = PR_Rename(m_cfg_file_path, name_bak);
        if (status != PR_SUCCESS) {
            // failed to back up CS.cfg
        }
    } 
    if (PR_Access(m_cfg_file_path, PR_ACCESS_EXISTS) == PR_SUCCESS) {
        // backup is false, or backup failed
        status = PR_Delete(m_cfg_file_path);
        if (status != PR_SUCCESS) {
            // failed to delete old CS.cfg file
            PR_snprintf(error_msg, len, "ConfigStore::Commit(): unable to delete old CS.cfg file");
            return 1;
        }
    }

    status = PR_Rename(name_tmp, m_cfg_file_path);
    if (status != PR_SUCCESS) {
        // failed to move tmp to CS.cfg 
        // major badness - we now have only tmp file, no CS.cfg
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): failed to move tmp file to CS.cfg");
        return 1;
    }

    return 0;
}
Ejemplo n.º 16
0
static void LoadExtraSharedLibs()
{
    // check out if user's prefs.js has libs name
    nsresult res;
    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID, &res));
    if (NS_SUCCEEDED(res) && (prefs != nsnull)) {
        char *sonameList = NULL;
        PRBool prefSonameListIsSet = PR_TRUE;
        res = prefs->GetCharPref(PREF_PLUGINS_SONAME, &sonameList);
        if (!sonameList) {
            // pref is not set, lets use hardcoded list
            prefSonameListIsSet = PR_FALSE;
            sonameList = PL_strdup(DEFAULT_EXTRA_LIBS_LIST);
        }
        if (sonameList) {
            char *arrayOfLibs[PLUGIN_MAX_NUMBER_OF_EXTRA_LIBS] = {0};
            int numOfLibs = 0;
            char *nextToken;
            char *p = nsCRT::strtok(sonameList,":",&nextToken);
            if (p) {
                while (p && numOfLibs < PLUGIN_MAX_NUMBER_OF_EXTRA_LIBS) {
                    arrayOfLibs[numOfLibs++] = p;
                    p = nsCRT::strtok(nextToken,":",&nextToken);
                }
            } else // there is just one lib
                arrayOfLibs[numOfLibs++] = sonameList;

            char sonameListToSave[PLUGIN_MAX_LEN_OF_TMP_ARR] = "";
            for (int i=0; i<numOfLibs; i++) {
                // trim out head/tail white spaces (just in case)
                PRBool head = PR_TRUE;
                p = arrayOfLibs[i];
                while (*p) {
                    if (*p == ' ' || *p == '\t') {
                        if (head) {
                            arrayOfLibs[i] = ++p;
                        } else {
                            *p = 0;
                        }
                    } else {
                        head = PR_FALSE;
                        p++;
                    }
                }
                if (!arrayOfLibs[i][0]) {
                    continue; // null string
                }
                PRBool tryToGetSoname = PR_TRUE;
                if (PL_strchr(arrayOfLibs[i], '/')) {
                    //assuming it's real name, try to stat it
                    struct stat st;
                    if (stat((const char*) arrayOfLibs[i], &st)) {
                        //get just a file name
                        arrayOfLibs[i] = PL_strrchr(arrayOfLibs[i], '/') + 1;
                    } else
                        tryToGetSoname = PR_FALSE;
                }
                char *soname = NULL;
                if (LoadExtraSharedLib(arrayOfLibs[i], &soname, tryToGetSoname)) {
                    //construct soname's list to save in prefs
                    p = soname ? soname : arrayOfLibs[i];
                    int n = PLUGIN_MAX_LEN_OF_TMP_ARR -
                        (PL_strlen(sonameListToSave) + PL_strlen(p));
                    if (n > 0) {
                        PL_strcat(sonameListToSave, p);
                        PL_strcat(sonameListToSave,":");
                    }
                    if (soname) {
                        PL_strfree(soname); // it's from strdup
                    }
                    if (numOfLibs > 1)
                        arrayOfLibs[i][PL_strlen(arrayOfLibs[i])] = ':'; //restore ":" in sonameList
                }
            }

            // Check whether sonameListToSave is a empty String, Bug: 329205
            if (sonameListToSave[0]) 
                for (p = &sonameListToSave[PL_strlen(sonameListToSave) - 1]; *p == ':'; p--)
                    *p = 0; //delete tail ":" delimiters

            if (!prefSonameListIsSet || PL_strcmp(sonameList, sonameListToSave)) {
                // if user specified some bogus soname I overwrite it here,
                // otherwise it'll decrease performance by calling popen() in SearchForSoname
                // every time for each bogus name
                prefs->SetCharPref(PREF_PLUGINS_SONAME, (const char *)sonameListToSave);
            }
            PL_strfree(sonameList);
        }
    }
}
Ejemplo n.º 17
0
static int
MimeExternalBody_parse_eof (MimeObject *obj, bool abort_p)
{
  int status = 0;
  MimeExternalBody *bod = (MimeExternalBody *) obj;

  if (obj->closed_p) return 0;

  /* Run parent method first, to flush out any buffered data. */
  status = ((MimeObjectClass*)&MIME_SUPERCLASS)->parse_eof(obj, abort_p);
  if (status < 0) return status;

#ifdef XP_MACOSX
  if (obj->parent && mime_typep(obj->parent,
                                (MimeObjectClass*) &mimeMultipartAppleDoubleClass))
    goto done;
#endif /* XP_MACOSX */

  if (!abort_p &&
      obj->output_p &&
      obj->options &&
      obj->options->write_html_p)
  {
    bool all_headers_p = obj->options->headers == MimeHeadersAll;
    MimeDisplayOptions *newopt = obj->options;  /* copy it */

    char *ct = MimeHeaders_get(obj->headers, HEADER_CONTENT_TYPE,
                               PR_FALSE, PR_FALSE);
    char *at, *lexp, *size, *perm;
    char *url, *dir, *mode, *name, *site, *svr, *subj;
    char *h = 0, *lname = 0, *lurl = 0, *body = 0;
    MimeHeaders *hdrs = 0;

    if (!ct) return MIME_OUT_OF_MEMORY;

    at   = MimeHeaders_get_parameter(ct, "access-type", NULL, NULL);
    lexp  = MimeHeaders_get_parameter(ct, "expiration", NULL, NULL);
    size = MimeHeaders_get_parameter(ct, "size", NULL, NULL);
    perm = MimeHeaders_get_parameter(ct, "permission", NULL, NULL);
    dir  = MimeHeaders_get_parameter(ct, "directory", NULL, NULL);
    mode = MimeHeaders_get_parameter(ct, "mode", NULL, NULL);
    name = MimeHeaders_get_parameter(ct, "name", NULL, NULL);
    site = MimeHeaders_get_parameter(ct, "site", NULL, NULL);
    svr  = MimeHeaders_get_parameter(ct, "server", NULL, NULL);
    subj = MimeHeaders_get_parameter(ct, "subject", NULL, NULL);
    url  = MimeHeaders_get_parameter(ct, "url", NULL, NULL);
    PR_FREEIF(ct);

    /* the *internal* content-type */
    ct = MimeHeaders_get(bod->hdrs, HEADER_CONTENT_TYPE,
                         PR_TRUE, PR_FALSE);
						 
    PRUint32 hlen = ((at ? strlen(at) : 0) +
                    (lexp ? strlen(lexp) : 0) +
                    (size ? strlen(size) : 0) +
                    (perm ? strlen(perm) : 0) +
                    (dir ? strlen(dir) : 0) +
                    (mode ? strlen(mode) : 0) +
                    (name ? strlen(name) : 0) +
                    (site ? strlen(site) : 0) +
                    (svr ? strlen(svr) : 0) +
                    (subj ? strlen(subj) : 0) +
                    (ct ? strlen(ct) : 0) +
                    (url ? strlen(url) : 0) + 100);
					
	h = (char *) PR_MALLOC(hlen);
    if (!h)
    {
      status = MIME_OUT_OF_MEMORY;
      goto FAIL;
    }

    /* If there's a URL parameter, remove all whitespace from it.
      (The URL parameter to one of these headers is stored with
       lines broken every 40 characters or less; it's assumed that
       all significant whitespace was URL-hex-encoded, and all the
       rest of it was inserted just to keep the lines short.)
      */
    if (url)
    {
      char *in, *out;
      for (in = url, out = url; *in; in++)
        if (!IS_SPACE(*in))
          *out++ = *in;
      *out = 0;
    }

    hdrs = MimeHeaders_new();
    if (!hdrs)
    {
      status = MIME_OUT_OF_MEMORY;
      goto FAIL;
    }

# define FROB(STR,VAR) \
    if (VAR) \
    { \
      PL_strncpyz(h, STR ": ", hlen); \
        PL_strcatn(h, hlen, VAR); \
          PL_strcatn(h, hlen, MSG_LINEBREAK); \
            status = MimeHeaders_parse_line(h, strlen(h), hdrs); \
              if (status < 0) goto FAIL; \
    }
    FROB("Access-Type",  at);
    FROB("URL",      url);
    FROB("Site",      site);
    FROB("Server",    svr);
    FROB("Directory",    dir);
    FROB("Name",      name);
    FROB("Type",      ct);
    FROB("Size",      size);
    FROB("Mode",      mode);
    FROB("Permission",  perm);
    FROB("Expiration",  lexp);
    FROB("Subject",    subj);
# undef FROB
    PL_strncpyz(h, MSG_LINEBREAK, hlen);
    status = MimeHeaders_parse_line(h, strlen(h), hdrs);
    if (status < 0) goto FAIL;

    lurl = MimeExternalBody_make_url(ct, at, lexp, size, perm, dir, mode,
                                     name, url, site, svr, subj, bod->body);
    if (lurl)
    {
      lname = MimeGetStringByID(MIME_MSG_LINK_TO_DOCUMENT);
    }
    else
    {
      lname = MimeGetStringByID(MIME_MSG_DOCUMENT_INFO);
      all_headers_p = PR_TRUE;
    }

    all_headers_p = PR_TRUE;  /* #### just do this all the time? */

    if (bod->body && all_headers_p)
    {
      char *s = bod->body;
      while (IS_SPACE(*s)) s++;
      if (*s)
      {
        char *s2;
        const char *pre = "<P><PRE>";
        const char *suf = "</PRE>";
        PRInt32 i;
        for(i = strlen(s)-1; i >= 0 && IS_SPACE(s[i]); i--)
          s[i] = 0;
        s2 = MsgEscapeHTML(s);
        if (!s2) goto FAIL;
        body = (char *) PR_MALLOC(strlen(pre) + strlen(s2) +
                                  strlen(suf) + 1);
        if (!body)
        {
          NS_Free(s2);
          goto FAIL;
        }
        PL_strcpy(body, pre);
        PL_strcat(body, s2);
        PL_strcat(body, suf);
      }
    }

    newopt->fancy_headers_p = PR_TRUE;
    newopt->headers = (all_headers_p ? MimeHeadersAll : MimeHeadersSome);

FAIL:
      if (hdrs)
        MimeHeaders_free(hdrs);
    PR_FREEIF(h);
    PR_FREEIF(lname);
    PR_FREEIF(lurl);
    PR_FREEIF(body);
    PR_FREEIF(ct);
    PR_FREEIF(at);
    PR_FREEIF(lexp);
    PR_FREEIF(size);
    PR_FREEIF(perm);
    PR_FREEIF(dir);
    PR_FREEIF(mode);
    PR_FREEIF(name);
    PR_FREEIF(url);
    PR_FREEIF(site);
    PR_FREEIF(svr);
    PR_FREEIF(subj);
  }

#ifdef XP_MACOSX
done:
#endif

    return status;
}
Ejemplo n.º 18
0
void display( nsIRegistry *reg, nsRegistryKey root, const char *rootName ) {
    // Print out key name.
    printf( "%s\n", rootName );

    // Make sure it isn't a "root" key.
    if ( root != nsIRegistry::Common
         &&
         root != nsIRegistry::Users
         &&
         root != nsIRegistry::CurrentUser ) {
        // Print values stored under this key.
        displayValues( reg, root );
    }

    // Enumerate all subkeys (immediately) under the given node.
    nsIEnumerator *keys;
    nsresult rv = reg->EnumerateSubtrees( root, &keys );

    // Check result.
    if ( rv == NS_OK ) {
        // Set enumerator to beginning.
        rv = keys->First();
        // Enumerate subkeys till done.
        while( NS_SUCCEEDED( rv ) && (NS_OK != keys->IsDone()) ) {
            nsISupports *base;
            rv = keys->CurrentItem( &base );
            // Test result.
            if ( rv == NS_OK ) {
                // Get specific interface.
                nsIRegistryNode *node;
                nsIID nodeIID = NS_IREGISTRYNODE_IID;
                rv = base->QueryInterface( nodeIID, (void**)&node );
                // Test that result.
                if ( rv == NS_OK ) {
                    // Get node name.
                    char *name;
                    rv = node->GetNameUTF8( &name );
                    // Test result.
                    if ( rv == NS_OK ) {
                        // Build complete name.
                        char *fullName = new char[ PL_strlen(rootName) + PL_strlen(name) + 5 ];
                        PL_strcpy( fullName, rootName );
                        PL_strcat( fullName, " -  " );
                        PL_strcat( fullName, name );
                        // Display contents under this subkey.
                        nsRegistryKey key;
                        rv = reg->GetSubtreeRaw( root, name, &key );
                        if ( rv == NS_OK ) {
                            display( reg, key, fullName );
                            printf( "\n" );
                        } else {
                            printf( "Error getting key, rv=0x%08X\n", (int)rv );
                        }
                        delete [] fullName;
                    } else {
                        printf( "Error getting subtree name, rv=0x%08X\n", (int)rv );
                    }
                    // Release node.
                    node->Release();
                } else {
                    printf( "Error converting base node ptr to nsIRegistryNode, rv=0x%08X\n", (int)rv );
                }
                // Release item.
                base->Release();

                // Advance to next key.
                rv = keys->Next();
                // Check result.
                if ( NS_SUCCEEDED( rv ) ) {
                } else {
                    printf( "Error advancing enumerator, rv=0x%08X\n", (int)rv );
                }
            } else {
                printf( "Error getting current item, rv=0x%08X\n", (int)rv );
            }
        }
        // Release key enumerator.
        keys->Release();
    } else {
        printf( "Error creating enumerator for %s, root=0x%08X, rv=0x%08X\n",
                rootName, (int)root, (int)rv );
    }
    return;
}
Ejemplo n.º 19
0
/*
 * FUNCTION: pkix_pl_ByteArray_ToString
 * (see comments for PKIX_PL_ToStringCallback in pkix_pl_system.h)
 */
static PKIX_Error *
pkix_pl_ByteArray_ToString(
        PKIX_PL_Object *object,
        PKIX_PL_String **pString,
        void *plContext)
{
        PKIX_PL_ByteArray *array = NULL;
        char *tempText = NULL;
        char *stringText = NULL; /* "[OOO, OOO, ... OOO]" */
        PKIX_UInt32 i, outputLen, bufferSize;

        PKIX_ENTER(BYTEARRAY, "pkix_pl_ByteArray_ToString");
        PKIX_NULLCHECK_TWO(object, pString);

        PKIX_CHECK(pkix_CheckType(object, PKIX_BYTEARRAY_TYPE, plContext),
                    PKIX_OBJECTNOTBYTEARRAY);

        array = (PKIX_PL_ByteArray *)object;

        if ((array->length) == 0) {
                PKIX_CHECK(PKIX_PL_String_Create
                        (PKIX_ESCASCII, "[]", 0, pString, plContext),
                        PKIX_COULDNOTCREATESTRING);
        } else {
                /* Allocate space for "XXX, ". */
                bufferSize = 2+5*array->length;

                /* Allocate space for format string */
                PKIX_CHECK(PKIX_PL_Malloc
                        (bufferSize, (void **)&stringText, plContext),
                        PKIX_MALLOCFAILED);

                stringText[0] = 0;
                outputLen = 0;

                PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf).\n");
                tempText =
                        PR_smprintf
                            ("[%03u", (0x0FF&((char *)(array->array))[0]));
                PKIX_BYTEARRAY_DEBUG("\tCalling PL_strlen).\n");
                outputLen += PL_strlen(tempText);

                PKIX_BYTEARRAY_DEBUG("\tCalling PL_strcat).\n");
                stringText = PL_strcat(stringText, tempText);

                PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf_free).\n");
                PR_smprintf_free(tempText);

                for (i = 1; i < array->length; i++) {
                        PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf).\n");
                        tempText = PR_smprintf
                                (", %03u",
                                (0x0FF&((char *)(array->array))[i]));

                        if (tempText == NULL){
                                PKIX_ERROR(PKIX_PRSMPRINTFFAILED);
                        }

                        PKIX_BYTEARRAY_DEBUG("\tCalling PL_strlen).\n");
                        outputLen += PL_strlen(tempText);

                        PKIX_BYTEARRAY_DEBUG("\tCalling PL_strcat).\n");
                        stringText = PL_strcat(stringText, tempText);

                        PKIX_BYTEARRAY_DEBUG("\tCalling PR_smprintf_free).\n");
                        PR_smprintf_free(tempText);
                        tempText = NULL;
                }

                stringText[outputLen++] = ']';
                stringText[outputLen] = 0;

                PKIX_CHECK(PKIX_PL_String_Create
                        (PKIX_ESCASCII, stringText, 0, pString, plContext),
                        PKIX_STRINGCREATEFAILED);

        }

cleanup:

        PKIX_FREE(stringText);
        PKIX_RETURN(BYTEARRAY);
}