static int
MimeInlineText_parse_end (MimeObject *obj, bool abort_p)
{
  MimeInlineText *text = (MimeInlineText *) obj;

  if (obj->parsed_p)
  {
    PR_ASSERT(obj->closed_p);
    return 0;
  }

  /* We won't be needing this buffer any more; nuke it. */
  PR_FREEIF(text->cbuffer);
  text->cbuffer_size = 0;

  return ((MimeObjectClass*)&MIME_SUPERCLASS)->parse_end (obj, abort_p);
}
int ap_encode_end(
	appledouble_encode_object *p_ap_encode_obj, 
	bool is_aborting)
{
	/*
	** clear up the apple doubler.
	*/
	if (p_ap_encode_obj == NULL)
		return noErr;

	if (p_ap_encode_obj->fileId)			/* close the file if it is open.	*/
    ::FSCloseFork(p_ap_encode_obj->fileId);

	PR_FREEIF(p_ap_encode_obj->boundary);		/* the boundary string.				*/
	
	return noErr;
}
Esempio n. 3
0
static int
MimeMultipart_initialize (MimeObject *object)
{
  MimeMultipart *mult = (MimeMultipart *) object;
  char *ct;

  /* This is an abstract class; it shouldn't be directly instantiated. */
  PR_ASSERT(object->clazz != (MimeObjectClass *) &mimeMultipartClass);

  ct = MimeHeaders_get (object->headers, HEADER_CONTENT_TYPE, PR_FALSE, PR_FALSE);
  mult->boundary = (ct
          ? MimeHeaders_get_parameter (ct, HEADER_PARM_BOUNDARY, NULL, NULL)
          : 0);
  PR_FREEIF(ct);
  mult->state = MimeMultipartPreamble;
  return ((MimeObjectClass*)&MIME_SUPERCLASS)->initialize(object);
}
Esempio n. 4
0
NS_IMETHODIMP
nsFileInputStream::Seek(PRInt32 aWhence, PRInt64 aOffset)
{
    PR_FREEIF(mLineBuffer); // this invalidates the line buffer
    if (!mFD) {
        if (mBehaviorFlags & REOPEN_ON_REWIND) {
            nsresult rv = Reopen();
            if (NS_FAILED(rv)) {
                return rv;
            }
        } else {
            return NS_BASE_STREAM_CLOSED;
        }
    }

    return nsFileStream::Seek(aWhence, aOffset);
}
Esempio n. 5
0
NS_IMETHODIMP
nsFileInputStream::Close()
{
    // null out mLineBuffer in case Close() is called again after failing
    PR_FREEIF(mLineBuffer);
    nsresult rv = nsFileStream::Close();
    if (NS_FAILED(rv)) return rv;
    if (mFile && (mBehaviorFlags & DELETE_ON_CLOSE)) {
        rv = mFile->Remove(PR_FALSE);
        NS_ASSERTION(NS_SUCCEEDED(rv), "failed to delete file");
        // If we don't need to save the file for reopening, free it up
        if (!(mBehaviorFlags & REOPEN_ON_REWIND)) {
          mFile = nsnull;
        }
    }
    return rv;
}
Esempio n. 6
0
MimeHeaders *
MimeHeaders_copy (MimeHeaders *hdrs)
{
  MimeHeaders *hdrs2;
  if (!hdrs) return 0;

  hdrs2 = (MimeHeaders *) PR_MALLOC(sizeof(*hdrs));
  if (!hdrs2) return 0;
  memset(hdrs2, 0, sizeof(*hdrs2));

  if (hdrs->all_headers)
  {
    hdrs2->all_headers = (char *) PR_MALLOC(hdrs->all_headers_fp);
    if (!hdrs2->all_headers)
    {
      PR_Free(hdrs2);
      return 0;
    }
    memcpy(hdrs2->all_headers, hdrs->all_headers, hdrs->all_headers_fp);

    hdrs2->all_headers_fp   = hdrs->all_headers_fp;
    hdrs2->all_headers_size = hdrs->all_headers_fp;
  }

  hdrs2->done_p = hdrs->done_p;

  if (hdrs->heads)
  {
    int i;
    hdrs2->heads = (char **) PR_MALLOC(hdrs->heads_size
                    * sizeof(*hdrs->heads));
    if (!hdrs2->heads)
    {
      PR_FREEIF(hdrs2->all_headers);
      PR_Free(hdrs2);
      return 0;
    }
    hdrs2->heads_size = hdrs->heads_size;
    for (i = 0; i < hdrs->heads_size; i++)
    {
      hdrs2->heads[i] = (hdrs2->all_headers +
               (hdrs->heads[i] - hdrs->all_headers));
    }
  }
  return hdrs2;
}
Esempio n. 7
0
void DIR_SetServerFileName(DIR_Server *server)
{
  char * tempName = nsnull; 
  const char * prefName = nsnull;
  PRUint32 numHeaderBytes = 0; 

  if (server && (!server->fileName || !(*server->fileName)) )
  {
          PR_FREEIF(server->fileName); // might be one byte empty string.
    /* make sure we have a pref name...*/
    if (!server->prefName || !*server->prefName)
      server->prefName = dir_CreateServerPrefName(server);

    /* set default personal address book file name*/
    if ((server->position == 1) && (server->dirType == PABDirectory))
            server->fileName = strdup(kPersonalAddressbook);
    else
    {
      /* now use the pref name as the file name since we know the pref name
         will be unique */
      prefName = server->prefName;
      if (prefName && *prefName)
      {
        /* extract just the pref name part and not the ldap tree name portion from the string */
        numHeaderBytes = PL_strlen(PREF_LDAP_SERVER_TREE_NAME) + 1; /* + 1 for the '.' b4 the name */
        if (PL_strlen(prefName) > numHeaderBytes) 
                    tempName = strdup(prefName + numHeaderBytes);

        if (tempName)
        {
          server->fileName = PR_smprintf("%s%s", tempName, kABFileName_CurrentSuffix);
          PR_Free(tempName);
        }
      }
    }

    if (!server->fileName || !*server->fileName) /* when all else has failed, generate a default name */
    {
      if (server->dirType == LDAPDirectory)
        DIR_SetFileName(&(server->fileName), kMainLdapAddressBook); /* generates file name with an ldap prefix */
      else
        DIR_SetFileName(&(server->fileName), kPersonalAddressbook);
    }
  }
}
NS_IMETHODIMP nsCollationMacUC::AllocateRawSortKey(int32_t strength, const nsAString& stringIn,
                                                   uint8_t** key, uint32_t* outLen)
{
  NS_ENSURE_TRUE(mInit, NS_ERROR_NOT_INITIALIZED);
  NS_ENSURE_ARG_POINTER(key);
  NS_ENSURE_ARG_POINTER(outLen);

  nsresult res = EnsureCollator(strength);
  NS_ENSURE_SUCCESS(res, res);

  uint32_t stringInLen = stringIn.Length();
  uint32_t maxKeyLen = (1 + stringInLen) * kCollationValueSizeFactor * sizeof(UCCollationValue);
  if (maxKeyLen > mBufferLen) {
    uint32_t newBufferLen = mBufferLen;
    do {
      newBufferLen *= 2;
    } while (newBufferLen < maxKeyLen);
    void *newBuffer = PR_Malloc(newBufferLen);
    if (!newBuffer)
      return NS_ERROR_OUT_OF_MEMORY;

    PR_FREEIF(mBuffer);
    mBuffer = newBuffer;
    mBufferLen = newBufferLen;
  }

  ItemCount actual;
  OSStatus err = ::UCGetCollationKey(mCollator, (const UniChar*) PromiseFlatString(stringIn).get(),
                                     (UniCharCount) stringInLen,
                                     (ItemCount) (mBufferLen / sizeof(UCCollationValue)),
                                     &actual, (UCCollationValue *)mBuffer);
  NS_ENSURE_TRUE((err == noErr), NS_ERROR_FAILURE);

  uint32_t keyLength = actual * sizeof(UCCollationValue);
  void *newKey = PR_Malloc(keyLength);
  if (!newKey)
    return NS_ERROR_OUT_OF_MEMORY;

  memcpy(newKey, mBuffer, keyLength);
  *key = (uint8_t *)newKey;
  *outLen = keyLength;

  return NS_OK;
}
Esempio n. 9
0
/* This routine is only necessary because the mailbox URL fed to us
   by the winfe can contain spaces and '>'s in it. It's a hack. */
static char *
escape_for_mrel_subst(char *inURL)
{
  char *output, *inC, *outC, *temp;

  int size = strlen(inURL) + 1;

  for(inC = inURL; *inC; inC++)
    if ((*inC == ' ') || (*inC == '>'))
      size += 2; /* space -> '%20', '>' -> '%3E', etc. */

  output = (char *)PR_MALLOC(size);
  if (output)
  {
    /* Walk through the source string, copying all chars
      except for spaces, which get escaped. */
    inC = inURL;
    outC = output;
    while(*inC)
    {
      if (*inC == ' ')
      {
        *outC++ = '%'; *outC++ = '2'; *outC++ = '0';
      }
      else if (*inC == '>')
      {
        *outC++ = '%'; *outC++ = '3'; *outC++ = 'E';
      }
      else
        *outC++ = *inC;

      inC++;
    }
    *outC = '\0';

    temp = escape_unescaped_percents(output);
    if (temp)
    {
      PR_FREEIF(output);
      output = temp;
    }
  }
  return output;
}
Esempio n. 10
0
static bool
MimeMultipartAlternative_display_part_p(MimeObject *self,
                    MimeHeaders *sub_hdrs)
{
  char *ct = MimeHeaders_get (sub_hdrs, HEADER_CONTENT_TYPE, true, false);
  if (!ct)
    return false;

  /* RFC 1521 says:
     Receiving user agents should pick and display the last format
     they are capable of displaying.  In the case where one of the
     alternatives is itself of type "multipart" and contains unrecognized
     sub-parts, the user agent may choose either to show that alternative,
     an earlier alternative, or both.

   Ugh.  If there is a multipart subtype of alternative, we simply show
   that, without descending into it to determine if any of its sub-parts
   are themselves unknown.
   */

  // prefer_plaintext pref
  nsIPrefBranch *prefBranch = GetPrefBranch(self->options);
  bool prefer_plaintext = false;
  if (prefBranch)
    prefBranch->GetBoolPref("mailnews.display.prefer_plaintext",
                            &prefer_plaintext);
  if (prefer_plaintext
      && self->options->format_out != nsMimeOutput::nsMimeMessageSaveAs
      && (!PL_strncasecmp(ct, "text/html", 9) ||
          !PL_strncasecmp(ct, "text/enriched", 13) ||
          !PL_strncasecmp(ct, "text/richtext", 13))
     )
    // if the user prefers plaintext and this is the "rich" (e.g. HTML) part...
  {
    return false;
  }

  MimeObjectClass *clazz = mime_find_class (ct, sub_hdrs, self->options, true);
  bool result = (clazz
          ? clazz->displayable_inline_p(clazz, sub_hdrs)
          : false);
  PR_FREEIF(ct);
  return result;
}
Esempio n. 11
0
/* static */
void WebCL_LibCL::unload (WebCL_LibCL* aInstance)
{
  D_METHOD_START;

  if (!(aInstance && aInstance->m_libHandle))
    return;

  if (PR_UnloadLibrary (aInstance->m_libHandle) == PR_FAILURE)
  {
    char *errText = getPRErrorText ();
    D_LOG (LOG_LEVEL_WARNING, "Failed to unload library %s: %s", aInstance->m_libName, errText);
    D_LOG (LOG_LEVEL_DEBUG, "  (prerr: %d oserr: %d)", PR_GetError(), PR_GetOSError());
    PR_FREEIF (errText);
  }
  else
  {
    D_LOG (LOG_LEVEL_DEBUG, "Unloaded library %s", aInstance->m_libName);
  }
}
Esempio n. 12
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;
}
Esempio n. 13
0
/* dir_ValidateAndAddNewServer
 *
 * This function verifies that the position, serverName and description values
 * are set for the given prefName.  If they are then it adds the server to the
 * unified server list.
 */
static PRBool dir_ValidateAndAddNewServer(nsVoidArray *wholeList, const char *fullprefname)
{
  PRBool rc = PR_FALSE;

  const char *endname = PL_strchr(&fullprefname[PL_strlen(PREF_LDAP_SERVER_TREE_NAME) + 1], '.');
  if (endname)
  {
    char *prefname = (char *)PR_Malloc(endname - fullprefname + 1);
    if (prefname)
    {
      PRInt32 dirType;
      char *t1 = nsnull, *t2 = nsnull;

      PL_strncpyz(prefname, fullprefname, endname - fullprefname + 1);

      dirType = DIR_GetIntPref(prefname, "dirType", -1);
      if (dirType != -1 &&
          DIR_GetIntPref(prefname, "position", 0) != 0 &&
          (t1 = DIR_GetStringPref(prefname, "description", nsnull)) != nsnull)
      {
        if (dirType == PABDirectory || dirType == IMDirectory ||
           (t2 = DIR_GetStringPref(prefname, "serverName",  nsnull)) != nsnull)
        {
          DIR_Server *server = (DIR_Server *)PR_Malloc(sizeof(DIR_Server));
          if (server)
          {
            DIR_InitServer(server, (DirectoryType)dirType);
            server->prefName = prefname;
            DIR_GetPrefsForOneServer(server);
            DIR_SetServerPosition(wholeList, server, server->position);
            rc = PR_TRUE;
          }
          PR_FREEIF(t2);
        }
        PR_Free(t1);
      }
      else
        PR_Free(prefname);
    }
  }

  return rc;
}
Esempio n. 14
0
static void appendcOFile_(OFile *fp, char c)
{
  if (fp->fail) 
    return;
stuff:
  if (fp->len+1 < fp->limit) {
    fp->s[fp->len] = c;
    fp->len++;
    return;
  }
  else if (fp->alloc) {
    fp->limit = fp->limit + OFILE_REALLOC_SIZE;
    fp->s = (char *)PR_Realloc(fp->s,fp->limit);
    if (fp->s) goto stuff;
  }
  if (fp->alloc)
    PR_FREEIF(fp->s);
  fp->s = 0;
  fp->fail = 1;
}
/* void onDataAvailable (in nsIRequest request, in nsISupports ctxt, in nsIInputStream inStr, in unsigned long long sourceOffset, in unsigned long count); */
NS_IMETHODIMP nsURLFetcherStreamConsumer::OnDataAvailable(nsIRequest *aRequest, nsISupports *ctxt, nsIInputStream *inStr, uint64_t sourceOffset, uint32_t count)
{
  uint32_t        readLen = count;
  uint32_t        wroteIt;

  if (!mURLFetcher)
    return NS_ERROR_FAILURE;

  if (!mURLFetcher->mOutStream)
    return NS_ERROR_INVALID_ARG;

  if (mURLFetcher->mBufferSize < count)
  {
    PR_FREEIF(mURLFetcher->mBuffer);

    if (count > 0x1000)
      mURLFetcher->mBufferSize = count;
    else
      mURLFetcher->mBufferSize = 0x1000;

    mURLFetcher->mBuffer = (char *)PR_Malloc(mURLFetcher->mBufferSize);
    if (!mURLFetcher->mBuffer)
      return NS_ERROR_OUT_OF_MEMORY; /* we couldn't allocate the object */
  }

  // read the data from the input stram...
  nsresult rv = inStr->Read(mURLFetcher->mBuffer, count, &readLen);
  if (NS_FAILED(rv))
    return rv;

  // write to the output file...
  mURLFetcher->mOutStream->Write(mURLFetcher->mBuffer, readLen, &wroteIt);

  if (wroteIt != readLen)
    return NS_ERROR_FAILURE;
  else
  {
    mURLFetcher->mTotalWritten += wroteIt;
    return NS_OK;
  }
}
Esempio n. 16
0
// Decode routine (also converts output to unicode)
nsresult
nsMimeConverter::DecodeMimeHeader(const char *header,
                                  const char *default_charset,
                                  bool override_charset,
                                  bool eatContinuations,
                                  nsAString& decodedString)
{
  NS_ENSURE_ARG_POINTER(header);

  // apply MIME decode.
  char *decodedCstr = MIME_DecodeMimeHeader(header, default_charset,
                                            override_charset, eatContinuations);
  if (!decodedCstr) {
    CopyUTF8toUTF16(nsDependentCString(header), decodedString);
  } else {
    CopyUTF8toUTF16(nsDependentCString(decodedCstr), decodedString);
    PR_FREEIF(decodedCstr);
  }

  return NS_OK;
}
Esempio n. 17
0
nsIMAPBodypartMultipart::nsIMAPBodypartMultipart(char *partNum, nsIMAPBodypart *parentPart) : 
nsIMAPBodypart(partNum, parentPart)
{
  if (!m_parentPart  || (m_parentPart->GetType() == IMAP_BODY_MESSAGE_RFC822))
  {
    // the multipart (this) will inherit the part number of its parent
    PR_FREEIF(m_partNumberString);
    if (!m_parentPart)
    {
      m_partNumberString = PR_smprintf("0");
    }
    else
      m_partNumberString = NS_strdup(m_parentPart->GetPartNumberString());
  }
  m_partList = new nsVoidArray();
  m_bodyType = NS_strdup("multipart");
  if (m_partList && m_parentPart && m_bodyType)
    SetIsValid(true);
  else
    SetIsValid(false);
}
Esempio n. 18
0
nsMsgComposeSecure::~nsMsgComposeSecure()
{
  /* destructor code */
  if (mEncryptionContext) {
    if (mBufferedBytes) {
      mEncryptionContext->Update(mBuffer, mBufferedBytes);
      mBufferedBytes = 0;
    }
    mEncryptionContext->Finish();
  }

  if (mSigEncoderData) {
    MIME_EncoderDestroy (mSigEncoderData, true);
  }
  if (mCryptoEncoderData) {
    MIME_EncoderDestroy (mCryptoEncoderData, true);
  }

  delete [] mBuffer;

  PR_FREEIF(mMultipartSignedBoundary);
}
Esempio n. 19
0
ProbingState SBCSGroupProber::HandleData(const char* aBuf, PRUint32 aLen)
{
  ProbingState st;
  PRUint32 i;
  char *newBuf1;
  PRUint32 newLen1;

  //apply filter to original buffer, and we got new buffer back
  //depend on what script it is, we will feed them the new buffer 
  //we got after applying proper filter
  FilterWithoutEnglishLetters(aBuf, aLen, &newBuf1, newLen1);

  for (i = 0; i < NUM_OF_SBCS_PROBERS; i++)
  {
     if (!mIsActive[i])
       continue;
     st = mProbers[i]->HandleData(newBuf1, newLen1);
     if (st == eFoundIt)
     {
       mBestGuess = i;
       mState = eFoundIt;
       break;
     }
     else if (st == eNotMe)
     {
       mIsActive[i] = PR_FALSE;
       mActiveNum--;
       if (mActiveNum <= 0)
       {
         mState = eNotMe;
         break;
       }
     }
  }

  PR_FREEIF(newBuf1);

  return mState;
}
Esempio n. 20
0
void
SaveIntermediateCerts(const ScopedCERTCertList& certList)
{
  if (!certList) {
    return;
  }

  bool isEndEntity = true;
  for (CERTCertListNode* node = CERT_LIST_HEAD(certList);
        !CERT_LIST_END(node, certList);
        node = CERT_LIST_NEXT(node)) {
    if (isEndEntity) {
      // Skip the end-entity; we only want to store intermediates
      isEndEntity = false;
      continue;
    }

    if (node->cert->slot) {
      // This cert was found on a token, no need to remember it in the temp db.
      continue;
    }

    if (node->cert->isperm) {
      // We don't need to remember certs already stored in perm db.
      continue;
    }

    // We have found a signer cert that we want to remember.
    char* nickname = DefaultServerNicknameForCert(node->cert);
    if (nickname && *nickname) {
      ScopedPtr<PK11SlotInfo, PK11_FreeSlot> slot(PK11_GetInternalKeySlot());
      if (slot) {
        PK11_ImportCert(slot.get(), node->cert, CK_INVALID_HANDLE,
                        nickname, false);
      }
    }
    PR_FREEIF(nickname);
  }
}
nsresult
nsMimeXmlEmitter::WriteXMLHeader(const char *msgID)
{
  if ( (!msgID) || (!*msgID) )
    msgID = "none";

  char  *newValue = MsgEscapeHTML(msgID);
  if (!newValue)
    return NS_ERROR_OUT_OF_MEMORY;

  UtilityWrite("<?xml version=\"1.0\"?>");

  UtilityWriteCRLF("<?xml-stylesheet href=\"chrome://messagebody/skin/messageBody.css\" type=\"text/css\"?>");

  UtilityWrite("<message id=\"");
  UtilityWrite(newValue);
  UtilityWrite("\">");

  mXMLHeaderStarted = true;
  PR_FREEIF(newValue);
  return NS_OK;
}
Esempio n. 22
0
static char *SMimeGetStringByID(PRInt32 aMsgId)
{
  char          *tempString = nsnull;
  nsresult res = NS_OK;

  if (!stringBundle)
  {
    static const char propertyURL[] = SMIME_PROPERTIES_URL;

    nsCOMPtr<nsIStringBundleService> sBundleService =
             do_GetService(NS_STRINGBUNDLE_CONTRACTID, &res);
    if (NS_SUCCEEDED(res) && (nsnull != sBundleService))
    {
      res = sBundleService->CreateBundle(propertyURL, getter_AddRefs(stringBundle));
    }
  }

  if (stringBundle)
  {
    PRUnichar *ptrv = nsnull;
    res = stringBundle->GetStringFromID(aMsgId, &ptrv);

    if (NS_FAILED(res))
      return strdup("???");
    else
    {
      nsAutoString v;
      v.Append(ptrv);
      PR_FREEIF(ptrv);
      tempString = ToNewUTF8String(v);
    }
  }

  if (!tempString)
    return strdup("???");
  else
    return tempString;
}
Esempio n. 23
0
static int
MimeMultipart_debug_print (MimeObject *obj, PRFileDesc *stream, PRInt32 depth)
{
  /*  MimeMultipart *mult = (MimeMultipart *) obj; */
  MimeContainer *cont = (MimeContainer *) obj;
  char *addr = mime_part_address(obj);
  int i;
  for (i=0; i < depth; i++)
  PR_Write(stream, "  ", 2);
/**
  fprintf(stream, "<%s %s (%d kid%s) boundary=%s 0x%08X>\n",
      obj->clazz->class_name,
      addr ? addr : "???",
      cont->nchildren, (cont->nchildren == 1 ? "" : "s"),
      (mult->boundary ? mult->boundary : "(none)"),
      (PRUint32) mult);
**/
  PR_FREEIF(addr);

/*
  if (cont->nchildren > 0)
  fprintf(stream, "\n");
 */

  for (i = 0; i < cont->nchildren; i++)
  {
    MimeObject *kid = cont->children[i];
    int status = kid->clazz->debug_print (kid, stream, depth+1);
    if (status < 0) return status;
  }

/*
  if (cont->nchildren > 0)
  fprintf(stream, "\n");
 */

  return 0;
}
Esempio n. 24
0
static void
MimeMultipartRelated_finalize (MimeObject *obj)
{
  MimeMultipartRelated* relobj = (MimeMultipartRelated*) obj;
  PR_FREEIF(relobj->base_url);
  PR_FREEIF(relobj->curtag);
  if (relobj->buffered_hdrs) {
	PR_FREEIF(relobj->buffered_hdrs->all_headers);
	PR_FREEIF(relobj->buffered_hdrs->heads);
	PR_FREEIF(relobj->buffered_hdrs);
  }
  PR_FREEIF(relobj->head_buffer);
  relobj->head_buffer_fp = 0;
  relobj->head_buffer_size = 0;
  if (relobj->hash) {
    PL_HashTableEnumerateEntries(relobj->hash, mime_multipart_related_nukehash, NULL);
    PL_HashTableDestroy(relobj->hash);
    relobj->hash = NULL;
  }

  if (relobj->input_file_stream)
  {
    relobj->input_file_stream->Close();
    relobj->input_file_stream = nullptr;
  }

  if (relobj->output_file_stream)
  {
    relobj->output_file_stream->Close();
    relobj->output_file_stream = nullptr;
  }

  if (relobj->file_buffer)
  {
    relobj->file_buffer->Remove(false);
    relobj->file_buffer = nullptr;
  }
  
  if (relobj->headobj) {
    mime_free(relobj->headobj);
    relobj->headobj = nullptr;
  }

  ((MimeObjectClass*)&MIME_SUPERCLASS)->finalize(obj);
}
nsresult
nsMsgAttachmentHandler::LoadDataFromFile(nsILocalFile *file, nsString &sigData, bool charsetConversion)
{
  PRInt32       readSize;
  char          *readBuf;

  nsCOMPtr <nsIInputStream> inputFile;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputFile), file);
  if (NS_FAILED(rv))
    return NS_MSG_ERROR_WRITING_FILE;

  PRInt64 fileSize;
  file->GetFileSize(&fileSize);
  readSize = (PRUint32) fileSize;

  readBuf = (char *)PR_Malloc(readSize + 1);
  if (!readBuf)
    return NS_ERROR_OUT_OF_MEMORY;
  memset(readBuf, 0, readSize + 1);

  PRUint32 bytesRead;
  inputFile->Read(readBuf, readSize, &bytesRead);
  inputFile->Close();

  nsDependentCString cstringReadBuf(readBuf, bytesRead);
  if (charsetConversion)
  {
    if (NS_FAILED(ConvertToUnicode(m_charset.get(), cstringReadBuf, sigData)))
      CopyASCIItoUTF16(cstringReadBuf, sigData);
  }
  else
    CopyASCIItoUTF16(cstringReadBuf, sigData);

  PR_FREEIF(readBuf);
  return NS_OK;
}
Esempio n. 26
0
PRStatus gif_write(gif_struct *gs, const PRUint8 *buf, PRUint32 len)
{
  if (!gs)
    return PR_FAILURE;

  /* If we fail, some upstream data provider ignored the
     zero return value from il_gif_write_ready() which says not to
     send any more data to this stream until the delay timeout fires. */
  if ((len != 0) && (gs->gathered >= MAX_READ_AHEAD))
    return PR_FAILURE;

  const PRUint8 *q, *p = buf, *ep = buf + len;

  q = nsnull;                   /* Initialize to shut up gcc warnings */

  while (p <= ep) {
    switch (gs->state)
    {
    case gif_lzw:
      if (do_lzw(gs, q) < 0) {
        gs->state = gif_error;
        break;
      }
      GETN(1, gif_sub_block);
      break;

    case gif_lzw_start:
    {
      /* Initialize LZW parser/decoder */
      gs->datasize = *q;
      if (gs->datasize >= MAX_LZW_BITS) {
        gs->state = gif_error;
        break;
      }

      gs->clear_code = 1 << gs->datasize;
      gs->avail = gs->clear_code + 2;
      gs->oldcode = -1;
      gs->codesize = gs->datasize + 1;
      gs->codemask = (1 << gs->codesize) - 1;

      gs->datum = gs->bits = 0;

      if (gs->clear_code >= MAX_BITS) {
        gs->state = gif_error;
        break;
      }

      /* init the tables */
      for (int i = 0; i < gs->clear_code; i++)
        gs->suffix[i] = i;

      gs->stackp = gs->stack;

      GETN(1, gif_sub_block);
    }
    break;

    /* We're positioned at the very start of the file. */
    case gif_init:
    {
      GETN(3, gif_type);
      break;
    }

    /* All GIF files begin with "GIF87a" or "GIF89a" */
    case gif_type:
    {
      if (strncmp((char*)q, "GIF", 3)) {
        gs->state = gif_error;
        break;
      }
      GETN(3, gif_version);
    }
    break;

    case gif_version:
    {
      if (!strncmp((char*)q, "89a", 3)) {
        gs->version = 89;
      } else if (!strncmp((char*)q, "87a", 3)) {
        gs->version = 87;
      } else {
        gs->state = gif_error;
        break;
      }
      GETN(7, gif_global_header);
    }
    break;

    case gif_global_header:
    {
      /* This is the height and width of the "screen" or
       * frame into which images are rendered.  The
       * individual images can be smaller than the
       * screen size and located with an origin anywhere
       * within the screen.
       */

      gs->screen_width = GETINT16(q);
      gs->screen_height = GETINT16(q + 2);

      gs->screen_bgcolor = q[5];

      gs->global_colormap_size = 2<<(q[4]&0x07);

      // XXX make callback
      nsGIFDecoder2::BeginGIF(
        gs->clientptr,
        gs->screen_width,
        gs->screen_height,
        gs->screen_bgcolor);

      if (q[4] & 0x80) /* global map */
        /* 3 bytes for each entry in the global colormap */
        GETN(gs->global_colormap_size*3, gif_global_colormap);
      else
        GETN(1, gif_image_start);

      // q[6] = Pixel Aspect Ratio
      //   Not used
      //   float aspect = (float)((q[6] + 15) / 64.0);
    }
    break;

    case gif_global_colormap:
    {
      memcpy(gs->global_colormap, q, 3 * gs->global_colormap_size);

      GETN(1, gif_image_start);
    }
    break;

    case gif_image_start:
    {
      if (*q == ';') { /* terminator */
        gs->state = gif_done;
        break;
      }

      if (*q == '!') { /* extension */
        GETN(2, gif_extension);
        break;
      }

      /* If we get anything other than ',' (image separator), '!'
       * (extension), or ';' (trailer), there is extraneous data
       * between blocks. The GIF87a spec tells us to keep reading
       * until we find an image separator, but GIF89a says such
       * a file is corrupt. We follow GIF89a and bail out. */
      if (*q != ',') {
        if (gs->images_decoded > 0) {
          /* The file is corrupt, but one or more images have
           * been decoded correctly. In this case, we proceed
           * as if the file were correctly terminated and set
           * the state to gif_done, so the GIF will display.
           */
          gs->state = gif_done;
        } else {
          /* No images decoded, there is nothing to display. */
          gs->state = gif_error;
        }
        break;
      } else
        GETN(9, gif_image_header);
    }
    break;

    case gif_extension:
    {
      int len = gs->count = q[1];
      gstate es = gif_skip_block;

      switch (*q)
      {
      case 0xf9:
        es = gif_control_extension;
        break;

      case 0x01:
        // ignoring plain text extension
        break;

      case 0xff:
        es = gif_application_extension;
        break;

      case 0xfe:
        es = gif_consume_comment;
        break;
      }

      if (len)
        GETN(len, es);
      else
        GETN(1, gif_image_start);
    }
    break;

    case gif_consume_block:
      if (!*q)
        GETN(1, gif_image_start);
      else
        GETN(*q, gif_skip_block);
    break;

    case gif_skip_block:
      GETN(1, gif_consume_block);
      break;

    case gif_control_extension:
    {
      if (*q & 0x1) {
        gs->tpixel = q[3];
        gs->is_transparent = PR_TRUE;
      } else {
        gs->is_transparent = PR_FALSE;
        // ignoring gfx control extension
      }
      gs->disposal_method = (gdispose)(((*q) >> 2) & 0x7);
      // Some specs say 3rd bit (value 4), other specs say value 3
      // Let's choose 3 (the more popular)
      if (gs->disposal_method == 4)
        gs->disposal_method = (gdispose)3;
      gs->delay_time = GETINT16(q + 1) * 10;
      GETN(1, gif_consume_block);
    }
    break;

    case gif_comment_extension:
    {
      gs->count = *q;
      if (gs->count)
        GETN(gs->count, gif_consume_comment);
      else
        GETN(1, gif_image_start);
    }
    break;

    case gif_consume_comment:
      GETN(1, gif_comment_extension);
    break;

    case gif_application_extension:
      /* Check for netscape application extension */
      if (!strncmp((char*)q, "NETSCAPE2.0", 11) ||
        !strncmp((char*)q, "ANIMEXTS1.0", 11))
        GETN(1, gif_netscape_extension_block);
      else
        GETN(1, gif_consume_block);
    break;

    /* Netscape-specific GIF extension: animation looping */
    case gif_netscape_extension_block:
      if (*q)
        GETN(*q, gif_consume_netscape_extension);
      else
        GETN(1, gif_image_start);
    break;

    /* Parse netscape-specific application extensions */
    case gif_consume_netscape_extension:
    {
      int netscape_extension = q[0] & 7;

      /* Loop entire animation specified # of times.  Only read the
         loop count during the first iteration. */
      if (netscape_extension == 1) {
        gs->loop_count = GETINT16(q + 1);

        /* Zero loop count is infinite animation loop request */
        if (gs->loop_count == 0)
          gs->loop_count = -1;

        GETN(1, gif_netscape_extension_block);
      }
      /* Wait for specified # of bytes to enter buffer */
      else if (netscape_extension == 2) {
        // Don't do this, this extension doesn't exist (isn't used at all) 
        // and doesn't do anything, as our streaming/buffering takes care of it all...
        // See: http://semmix.pl/color/exgraf/eeg24.htm
        GETN(1, gif_netscape_extension_block);
      } else
        gs->state = gif_error; // 0,3-7 are yet to be defined netscape
                               // extension codes

      break;
    }

    case gif_image_header:
    {
      PRUintn height, width;

      /* Get image offsets, with respect to the screen origin */
      gs->x_offset = GETINT16(q);
      gs->y_offset = GETINT16(q + 2);

      /* Get image width and height. */
      width  = GETINT16(q + 4);
      height = GETINT16(q + 6);

      /* Work around broken GIF files where the logical screen
       * size has weird width or height.  We assume that GIF87a
       * files don't contain animations.
       */
      if ((gs->images_decoded == 0) &&
          ((gs->screen_height < height) || (gs->screen_width < width) ||
           (gs->version == 87)))
      {
        gs->screen_height = height;
        gs->screen_width = width;
        gs->x_offset = 0;
        gs->y_offset = 0;

        nsGIFDecoder2::BeginGIF(gs->clientptr,
                                gs->screen_width,
                                gs->screen_height,
                                gs->screen_bgcolor);
      }

      /* Work around more broken GIF files that have zero image
         width or height */
      if (!height || !width) {
        height = gs->screen_height;
        width = gs->screen_width;
        if (!height || !width) {
          gs->state = gif_error;
          break;
        }
      }

      gs->height = height;
      gs->width = width;

      nsGIFDecoder2::BeginImageFrame(gs->clientptr,
                                     gs->images_decoded + 1,   /* Frame number, 1-n */
                                     gs->x_offset,  /* X offset in logical screen */
                                     gs->y_offset,  /* Y offset in logical screen */
                                     width,
                                     height);

      /* This case will never be taken if this is the first image */
      /* being decoded. If any of the later images are larger     */
      /* than the screen size, we need to reallocate buffers.     */
      if (gs->screen_width < width) {
        /* XXX Deviant! */

        gs->rowbuf = (PRUint8*)PR_REALLOC(gs->rowbuf, width);

        if (!gs->rowbuf) {
          gs->state = gif_oom;
          break;
        }

        gs->screen_width = width;
        if (gs->screen_height < gs->height)
          gs->screen_height = gs->height;

      }
      else {
        if (!gs->rowbuf)
          gs->rowbuf = (PRUint8*)PR_MALLOC(gs->screen_width);
      }

      if (!gs->rowbuf) {
          gs->state = gif_oom;
          break;
      }

      if (q[8] & 0x40) {
        gs->interlaced = PR_TRUE;
        gs->ipass = 1;
      } else {
        gs->interlaced = PR_FALSE;
        gs->ipass = 0;
      }

      if (gs->images_decoded == 0) {
        gs->progressive_display = PR_TRUE;
      } else {
        /* Overlaying interlaced, transparent GIFs over
           existing image data using the Haeberli display hack
           requires saving the underlying image in order to
           avoid jaggies at the transparency edges.  We are
           unprepared to deal with that, so don't display such
           images progressively */
        gs->progressive_display = PR_FALSE;
      }

      /* Clear state from last image */
      gs->irow = 0;
      gs->rows_remaining = gs->height;
      gs->rowend = gs->rowbuf + gs->width;
      gs->rowp = gs->rowbuf;

      /* bits per pixel is 1<<((q[8]&0x07) + 1); */

      if (q[8] & 0x80) /* has a local colormap? */
      {
        int num_colors = 2 << (q[8] & 0x7);

        // If current local_colormap is not big enough, force reallocation
        if (num_colors > gs->local_colormap_size)
          PR_FREEIF(gs->local_colormap);
        gs->local_colormap_size = num_colors;

        /* Switch to the new local palette after it loads */
        gs->is_local_colormap_defined = PR_TRUE;
        GETN(gs->local_colormap_size * 3, gif_image_colormap);
      } else {
        /* Switch back to the global palette */
        gs->is_local_colormap_defined = PR_FALSE;
        GETN(1, gif_lzw_start);
      }
    }
    break;

    case gif_image_colormap:
    {
      PRUint8 *map = gs->local_colormap;
      if (!map) {
        map = gs->local_colormap = (PRUint8*)PR_MALLOC(3 * gs->local_colormap_size);
        if (!map) {
          gs->state = gif_oom;
          break;
        }
      }

      memcpy(map, q, 3 * gs->local_colormap_size);

      GETN(1, gif_lzw_start);
    }
    break;

    case gif_sub_block:
    {
      if ((gs->count = *q) != 0)
      /* Still working on the same image: Process next LZW data block */
      {
        /* Make sure there are still rows left. If the GIF data */
        /* is corrupt, we may not get an explicit terminator.   */
        if (gs->rows_remaining == 0) {
          /* This is an illegal GIF, but we remain tolerant. */
#ifdef DONT_TOLERATE_BROKEN_GIFS
          gs->state = gif_error;
          break;
#else
          GETN(1, gif_sub_block);
#endif
        }
        GETN(gs->count, gif_lzw);
      }
      else
      /* See if there are any more images in this sequence. */
      {
        gs->images_decoded++;

        nsGIFDecoder2::EndImageFrame(gs->clientptr,
                                     gs->images_decoded,
                                     gs->delay_time);

        /* Clear state from this image */
        gs->is_transparent = PR_FALSE;

        /* An image can specify a delay time before which to display
           subsequent images. */
        if (gs->delay_time < MINIMUM_DELAY_TIME)
          gs->delay_time = MINIMUM_DELAY_TIME;

        GETN(1, gif_image_start);
      }
    }
    break;

    case gif_done:
      nsGIFDecoder2::EndGIF(gs->clientptr, gs->loop_count);
      return PR_SUCCESS;
      break;

    case gif_delay:
    case gif_gather:
    {
      PRInt32 gather_remaining;
      PRInt32 request_size = gs->gather_request_size;

      {
        gather_remaining = request_size - gs->gathered;

        /* Do we already have enough data in the accumulation
           buffer to satisfy the request ?  (This can happen
           after we transition from the gif_delay state.) */
        if (gather_remaining <= 0) {
          gs->gathered -= request_size;
          q = gs->gather_head;
          gs->gather_head += request_size;
          gs->state = gs->post_gather_state;
          break;
        }

        /* Shift remaining data to the head of the buffer */
        if (gs->gathered && (gs->gather_head != gs->hold)) {
          memmove(gs->hold, gs->gather_head, gs->gathered);
          gs->gather_head = gs->hold;
        }

        /* If we add the data just handed to us by the netlib
           to what we've already gathered, is there enough to satisfy
           the current request ? */
        if ((ep - p) >= gather_remaining) {
          if (gs->gathered) { /* finish a prior gather */
            char *hold = (char*)gs->hold;
            BlockAllocCat(hold, gs->gathered, (char*)p, gather_remaining);
            gs->hold = (PRUint8*)hold;
            q = gs->gather_head = gs->hold;
            gs->gathered = 0;
          } else
            q = p;

          p += gather_remaining;
          gs->state = gs->post_gather_state;
        } else {
          char *hold = (char*)gs->hold;
          BlockAllocCat(hold, gs->gathered, (char*)p, ep - p);
          gs->hold = (PRUint8*)hold;
          gs->gather_head = gs->hold;
          gs->gathered += ep-p;
          return PR_SUCCESS;
        }
      }
    }
    break;

    // Handle out of memory errors
    case gif_oom:
      return PR_FAILURE;

    // Handle general errors
    case gif_error:
      nsGIFDecoder2::EndGIF(gs->clientptr, gs->loop_count);
      return PR_SUCCESS;

    case gif_stop_animating:
      return PR_SUCCESS;

    // We shouldn't ever get here.
    default:
      break;
    }
  }

  return PR_SUCCESS;
}
nsresult
nsMimeBaseEmitter::WriteHeaderFieldHTML(const char *field, const char *value)
{
  char *newValue = nullptr;
  char *i18nValue = nullptr;

  if ( (!field) || (!value) )
    return NS_OK;

  //
  // This is a check to see what the pref is for header display. If
  // We should only output stuff that corresponds with that setting.
  //
  if (!EmitThisHeaderForPrefSetting(mHeaderDisplayType, field))
    return NS_OK;

  //
  // If we encounter the 'Date' header we try to convert it's value
  // into localized format.
  //
  if ( strcmp(field, "Date") == 0 )
    i18nValue = GetLocalizedDateString(value);
  else
    i18nValue = strdup(value);

  if ( (mUnicodeConverter) && (mFormat != nsMimeOutput::nsMimeMessageSaveAs) )
  {
    nsCString tValue;

    // we're going to need a converter to convert
    nsresult rv = mUnicodeConverter->DecodeMimeHeaderToUTF8(
      nsDependentCString(i18nValue), nullptr, false, true, tValue);
    if (NS_SUCCEEDED(rv) && !tValue.IsEmpty())
      newValue = MsgEscapeHTML(tValue.get());
    else
      newValue = MsgEscapeHTML(i18nValue);
  }
  else
  {
    newValue = MsgEscapeHTML(i18nValue);
  }

  free(i18nValue);

  if (!newValue)
    return NS_OK;

  mHTMLHeaders.Append("<tr>");
  mHTMLHeaders.Append("<td>");

  if (mFormat == nsMimeOutput::nsMimeMessageSaveAs)
    mHTMLHeaders.Append("<b>");
  else
    mHTMLHeaders.Append("<div class=\"headerdisplayname\" style=\"display:inline;\">");

  // Here is where we are going to try to L10N the tagName so we will always
  // get a field name next to an emitted header value. Note: Default will always
  // be the name of the header itself.
  //
  nsCString newTagName(field);
  newTagName.StripWhitespace();
  ToUpperCase(newTagName);

  char *l10nTagName = LocalizeHeaderName(newTagName.get(), field);
  if ( (!l10nTagName) || (!*l10nTagName) )
    mHTMLHeaders.Append(field);
  else
  {
    mHTMLHeaders.Append(l10nTagName);
    PR_FREEIF(l10nTagName);
  }

  mHTMLHeaders.Append(": ");
  if (mFormat == nsMimeOutput::nsMimeMessageSaveAs)
    mHTMLHeaders.Append("</b>");
  else
    mHTMLHeaders.Append("</div>");

  // Now write out the actual value itself and move on!
  //
  mHTMLHeaders.Append(newValue);
  mHTMLHeaders.Append("</td>");

  mHTMLHeaders.Append("</tr>");

  PR_FREEIF(newValue);
  return NS_OK;
}
Esempio n. 28
0
static int
MimeInlineTextPlainFlowed_parse_eof (MimeObject *obj, PRBool abort_p)
{
  int status = 0;
  struct MimeInlineTextPlainFlowedExData *exdata = nsnull;

  PRBool quoting = ( obj->options
    && ( obj->options->format_out == nsMimeOutput::nsMimeMessageQuoting ||
         obj->options->format_out == nsMimeOutput::nsMimeMessageBodyQuoting
       )           );  // see above

  // Has this method already been called for this object?
  // In that case return.
  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) goto EarlyOut;

  // Look up and unlink "our" extended data structure
  // We do it in the beginning so that if an error occur, we can
  // just free |exdata|.
  struct MimeInlineTextPlainFlowedExData **prevexdata;
  prevexdata = &MimeInlineTextPlainFlowedExDataList;

  while ((exdata = *prevexdata) != nsnull) {
    if (exdata->ownerobj == obj) {
      // Fill hole
      *prevexdata = exdata->next;
      break;
    }
    prevexdata = &exdata->next;
  }
  NS_ASSERTION (exdata, "The extra data has disappeared!");

  if (!obj->output_p) {
    status = 0;
    goto EarlyOut;
  }

  for(; exdata->quotelevel > 0; exdata->quotelevel--) {
    status = MimeObject_write(obj, "</blockquote>", 13, PR_FALSE);
    if(status<0) goto EarlyOut;
  }

  if (exdata->isSig && !quoting) {
    status = MimeObject_write(obj, "</div>", 6, PR_FALSE); // .moz-txt-sig
    if (status<0) goto EarlyOut;
  }
  if (!quoting) // HACK (see above)
  {
    status = MimeObject_write(obj, "</div>", 6, PR_FALSE); // .moz-text-flowed
    if (status<0) goto EarlyOut;
  }

  status = 0;

EarlyOut:
  PR_Free(exdata);

  // Free mCitationColor
  MimeInlineTextPlainFlowed *text = (MimeInlineTextPlainFlowed *) obj;
  PR_FREEIF(text->mCitationColor);
  text->mCitationColor = nsnull;

  return status;
}
Esempio n. 29
0
File: uxshm.c Progetto: edrikL/gears
extern PRSharedMemory * _MD_OpenSharedMemory( 
    const char *name,
    PRSize      size,
    PRIntn      flags,
    PRIntn      mode
)
{
    PRStatus rc = PR_SUCCESS;
    key_t   key;
    PRSharedMemory *shm;
    char        ipcname[PR_IPC_NAME_SIZE];

    rc = _PR_MakeNativeIPCName( name, ipcname, PR_IPC_NAME_SIZE, _PRIPCShm );
    if ( PR_FAILURE == rc )
    {
        _PR_MD_MAP_DEFAULT_ERROR( errno );
        PR_LOG( _pr_shm_lm, PR_LOG_DEBUG, 
            ("_MD_OpenSharedMemory(): _PR_MakeNativeIPCName() failed: %s", name ));
        return( NULL );
    }

    shm = PR_NEWZAP( PRSharedMemory );
    if ( NULL == shm ) 
    {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
        PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New PRSharedMemory out of memory")); 
        return( NULL );
    }

    shm->ipcname = (char*)PR_MALLOC( strlen( ipcname ) + 1 );
    if ( NULL == shm->ipcname )
    {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0 );
        PR_LOG(_pr_shm_lm, PR_LOG_DEBUG, ( "PR_OpenSharedMemory: New shm->ipcname out of memory")); 
        PR_DELETE( shm );
        return( NULL );
    }

    /* copy args to struct */
    strcpy( shm->ipcname, ipcname );
    shm->size = size; 
    shm->mode = mode; 
    shm->flags = flags;
    shm->ident = _PR_SHM_IDENT;

    /* create the file first */
    if ( flags & PR_SHM_CREATE )  {
        int osfd = open( shm->ipcname, (O_RDWR | O_CREAT), shm->mode );
        if ( -1 == osfd ) {
            _PR_MD_MAP_OPEN_ERROR( errno );
            PR_FREEIF( shm->ipcname );
            PR_DELETE( shm );
            return( NULL );
        } 
        if ( close(osfd) == -1 ) {
            _PR_MD_MAP_CLOSE_ERROR( errno );
            PR_FREEIF( shm->ipcname );
            PR_DELETE( shm );
            return( NULL );
        }
    }

    /* hash the shm.name to an ID */
    key = ftok( shm->ipcname, NSPR_IPC_SHM_KEY );
    if ( -1 == key )
    {
        rc = PR_FAILURE;
        _PR_MD_MAP_DEFAULT_ERROR( errno );
        PR_LOG( _pr_shm_lm, PR_LOG_DEBUG, 
            ("_MD_OpenSharedMemory(): ftok() failed on name: %s", shm->ipcname));
        PR_FREEIF( shm->ipcname );
        PR_DELETE( shm );
        return( NULL );
    }

    /* get the shared memory */
    if ( flags & PR_SHM_CREATE )  {
        shm->id = shmget( key, shm->size, ( shm->mode | IPC_CREAT|IPC_EXCL));
        if ( shm->id >= 0 ) {
            return( shm );
        }
        if ((errno == EEXIST) && (flags & PR_SHM_EXCL)) {
            PR_SetError( PR_FILE_EXISTS_ERROR, errno );
            PR_LOG( _pr_shm_lm, PR_LOG_DEBUG, 
                ("_MD_OpenSharedMemory(): shmget() exclusive failed, errno: %d", errno));
            PR_FREEIF(shm->ipcname);
            PR_DELETE(shm);
            return(NULL);
        }
    } 

    shm->id = shmget( key, shm->size, shm->mode );
    if ( -1 == shm->id ) {
        _PR_MD_MAP_DEFAULT_ERROR( errno );
        PR_LOG( _pr_shm_lm, PR_LOG_DEBUG, 
            ("_MD_OpenSharedMemory(): shmget() failed, errno: %d", errno));
        PR_FREEIF(shm->ipcname);
        PR_DELETE(shm);
        return(NULL);
    }

    return( shm );
} /* end _MD_OpenSharedMemory() */
Esempio n. 30
0
static int
MimeMessage_write_headers_html (MimeObject *obj)
{
  MimeMessage     *msg = (MimeMessage *) obj;
  int             status;

#ifdef MOZ_SECURITY
  HG33391
#endif /* MOZ_SECURITY */

  if (!obj->options || !obj->options->output_fn)
    return 0;

  PR_ASSERT(obj->output_p && obj->options->write_html_p);

  // To support the no header option! Make sure we are not
  // suppressing headers on included email messages...
  if ( (obj->options->headers == MimeHeadersNone) &&
       (obj == obj->options->state->root) )
  {
    // Ok, we are going to kick the Emitter for a StartHeader
    // operation ONLY WHEN THE CHARSET OF THE ORIGINAL MESSAGE IS
    // NOT US-ASCII ("ISO-8859-1")
    //
    // This is only to notify the emitter of the charset of the
    // original message
    char    *mailCharset = DetermineMailCharset(msg);

    if ( (mailCharset) && (PL_strcasecmp(mailCharset, "US-ASCII")) &&
         (PL_strcasecmp(mailCharset, "ISO-8859-1")) )
      mimeEmitterUpdateCharacterSet(obj->options, mailCharset);
    PR_FREEIF(mailCharset);
    return 0;
  }

  if (!obj->options->state->first_data_written_p)
  {
    status = MimeObject_output_init (obj, TEXT_HTML);
    if (status < 0)
    {
      mimeEmitterEndHeader(obj->options);
      return status;
    }
    PR_ASSERT(obj->options->state->first_data_written_p);
  }

  // Start the header parsing by the emitter
  char *msgID = MimeHeaders_get (msg->hdrs, HEADER_MESSAGE_ID,
                                    PR_FALSE, PR_FALSE);
  PRBool outer_p = !obj->headers; /* is this the outermost message? */
  if (!outer_p && obj->options->format_out == nsMimeOutput::nsMimeMessageBodyDisplay &&
      obj->options->part_to_load)
  {
    //Maybe we are displaying a embedded message as outer part!
    char *id = mime_part_address(obj);
    if (id)
    {
      outer_p = !strcmp(id, obj->options->part_to_load);
      PR_Free(id);
    }
  }

  // Ok, we should really find out the charset of this part. We always
  // output UTF-8 for display, but the original charset is necessary for
  // reply and forward operations.
  //
  char    *mailCharset = DetermineMailCharset(msg);
  mimeEmitterStartHeader(obj->options,
                            outer_p,
                            (obj->options->headers == MimeHeadersOnly),
                            msgID,
                            mailCharset);

  // Change the default_charset by the charset of the original message
  // ONLY WHEN THE CHARSET OF THE ORIGINAL MESSAGE IS NOT US-ASCII
  // ("ISO-8859-1") and defailt_charset and mailCharset are different.
  if ( (mailCharset) && (PL_strcasecmp(mailCharset, "US-ASCII")) &&
       (PL_strcasecmp(mailCharset, "ISO-8859-1")) &&
       (PL_strcasecmp(obj->options->default_charset, mailCharset)) &&
       !obj->options->override_charset )
  {
    PR_FREEIF(obj->options->default_charset);
    obj->options->default_charset = strdup(mailCharset);
  }

  PR_FREEIF(msgID);
  PR_FREEIF(mailCharset);

#ifdef MOZ_SECURITY
    HG00919
#endif /* MOZ_SECURITY */

  status = MimeHeaders_write_all_headers (msg->hdrs, obj->options, PR_FALSE);
  if (status < 0)
  {
    mimeEmitterEndHeader(obj->options);
    return status;
  }

  if (msg->crypto_stamped_p)
  {
#ifdef MOZ_SECURITY
    HG11995
#endif /* MOZ_SECURITY */
  }
  else
  {
  /* If we're not writing a xlation stamp, and this is the outermost
  message, then now is the time to run the post_header_html_fn.
  (Otherwise, it will be run when the xlation-stamp is finally
  closed off, in MimeXlateed_emit_buffered_child() or
  MimeMultipartSigned_emit_child().)
     */
    if (obj->options &&
      obj->options->state &&
      obj->options->generate_post_header_html_fn &&
      !obj->options->state->post_header_html_run_p)
    {
      char *html = 0;
      PR_ASSERT(obj->options->state->first_data_written_p);
      html = obj->options->generate_post_header_html_fn(NULL,
                                          obj->options->html_closure,
                                          msg->hdrs);
      obj->options->state->post_header_html_run_p = PR_TRUE;
      if (html)
      {
        status = MimeObject_write(obj, html, strlen(html), PR_FALSE);
        PR_Free(html);
        if (status < 0)
        {
          mimeEmitterEndHeader(obj->options);
          return status;
        }
      }
    }
  }

  mimeEmitterEndHeader(obj->options);

  // rhp:
  // For now, we are going to parse the entire message, even if we are
  // only interested in headers...why? Well, because this is the only
  // way to build the attachment list. Now we will have the attachment
  // list in the output being created by the XML emitter. If we ever
  // want to go back to where we were before, just uncomment the conditional
  // and it will stop at header parsing.
  //
  // if (obj->options->headers == MimeHeadersOnly)
  //   return -1;
  // else

  return 0;
}