Ejemplo n.º 1
0
nsresult
nsPluggableJVM::loadPluginDLL(const char* plugin_home)
{
  char* plugin_dll = PR_GetLibraryName(plugin_home, LIBJVMP);
  JVMP_GetPlugin_t fJVMP_GetPlugin;
  char errorMsg[1024] = "<unknown; can't get error from NSPR>";

  OJI_LOG2("Loading JVMP from %s", plugin_dll);
  m_dll = PR_LoadLibrary(plugin_dll);
  PR_Free(plugin_dll);
  if (!m_dll) 
    {
      if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
	PR_GetErrorText(errorMsg);
      OJI_LOG2("Cannot load plugin DLL: %s", errorMsg);
      return NS_ERROR_FAILURE;
    }
  fJVMP_GetPlugin = 
    (JVMP_GetPlugin_t) PR_FindSymbol(m_dll, "JVMP_GetPlugin");
  if (!fJVMP_GetPlugin)
    {
      if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
	PR_GetErrorText(errorMsg);
      OJI_LOG2("Cannot resolve JVMP_GetPlugin: %s", errorMsg);
      return NS_ERROR_FAILURE;
    }
  (*fJVMP_GetPlugin)(&m_jvmp_context);
  return NS_OK;
}
Ejemplo n.º 2
0
/****************************************************************
 *
 * J z i p O p e n
 *
 * Opens a new ZIP file and creates a new ZIPfile structure to
 * control the process of installing files into a zip.
 */
ZIPfile *
JzipOpen(char *filename, char *comment)
{
    ZIPfile *zipfile;
    PRExplodedTime prtime;

    zipfile = PORT_ZAlloc(sizeof(ZIPfile));
    if (!zipfile)
        out_of_memory();

    /* Construct time and date */
    PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &prtime);
    zipfile->date = ((prtime.tm_year - 1980) << 9) |
                    ((prtime.tm_month + 1) << 5) |
                    prtime.tm_mday;
    zipfile->time = (prtime.tm_hour << 11) |
                    (prtime.tm_min << 5) |
                    (prtime.tm_sec & 0x3f);

    zipfile->fp = NULL;
    if (filename &&
        (zipfile->fp = PR_Open(filename,
                               PR_WRONLY |
                                   PR_CREATE_FILE |
                                   PR_TRUNCATE,
                               0777)) == NULL) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "%s: can't open output jar, %s.%s\n",
                   PROGRAM_NAME,
                   filename, nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }

    zipfile->list = NULL;
    if (filename) {
        zipfile->filename = PORT_ZAlloc(strlen(filename) + 1);
        if (!zipfile->filename)
            out_of_memory();
        PORT_Strcpy(zipfile->filename, filename);
    }
    if (comment) {
        zipfile->comment = PORT_ZAlloc(strlen(comment) + 1);
        if (!zipfile->comment)
            out_of_memory();
        PORT_Strcpy(zipfile->comment, comment);
    }

    return zipfile;
}
Ejemplo n.º 3
0
static void DisplayPR_LoadLibraryErrorMessage(const char *libName)
{
    char errorMsg[PLUGIN_MAX_LEN_OF_TMP_ARR] = "Cannot get error from NSPR.";
    if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
        PR_GetErrorText(errorMsg);

    fprintf(stderr, "LoadPlugin: failed to initialize shared library %s [%s]\n",
        libName, errorMsg);
}
Ejemplo n.º 4
0
Archivo: pk11.c Proyecto: emaldona/nss
/**********************************************************************
 *
 * A d d M o d u l e
 *
 * Add the named module, with the given library file, ciphers, and
 * default mechanism flags
 */
Error
AddModule(char *moduleName, char *libFile, char *cipherString,
          char *mechanismString, char *modparms)
{
    unsigned long ciphers;
    unsigned long mechanisms;
    SECStatus status;

    mechanisms =
        getFlagsFromString(mechanismString, mechanismStrings,
                           numMechanismStrings);
    ciphers =
        getFlagsFromString(cipherString, cipherStrings, numCipherStrings);

    status =
        SECMOD_AddNewModuleEx(moduleName, libFile,
                              SECMOD_PubMechFlagstoInternal(mechanisms),
                              SECMOD_PubCipherFlagstoInternal(ciphers),
                              modparms, NULL);

    if (status != SECSuccess) {
        char *errtxt = NULL;
        PRInt32 copied = 0;
        if (PR_GetErrorTextLength()) {
            errtxt = PR_Malloc(PR_GetErrorTextLength() + 1);
            copied = PR_GetErrorText(errtxt);
        }
        if (copied && errtxt) {
            PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR],
                       moduleName, errtxt);
            PR_Free(errtxt);
        } else {
            PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR],
                       moduleName, SECU_Strerror(PORT_GetError()));
        }
        return ADD_MODULE_FAILED_ERR;
    } else {
        PR_fprintf(PR_STDOUT, msgStrings[ADD_MODULE_SUCCESS_MSG], moduleName);
        return SUCCESS;
    }
}
Ejemplo n.º 5
0
// Release the retun value with PR_FREEIF
static char* getPRErrorText ()
{
  PRInt32 errTextLen = PR_GetErrorTextLength ();
  char *s = (char*)PR_MALLOC (errTextLen + 1);
  if (s)
  {
    s[0] = '\0';
    (void)PR_GetErrorText (s);
  }

  return s;
}
Ejemplo n.º 6
0
// Release the retun value with PR_FREEIF
static char* getPRErrorText ()
{
  PRInt32 errTextLen = PR_GetErrorTextLength ();
  char *rv = (char*)PR_MALLOC (errTextLen + 1);
  if (rv)
  {
    rv[0] = '\0';
    (void)PR_GetErrorText (rv);
  }

  return rv;
}
Ejemplo n.º 7
0
static gchar *get_error_text(void)
{
	PRInt32 len = PR_GetErrorTextLength();
	gchar *ret = NULL;

	if (len > 0) {
		ret = g_malloc(len + 1);
		len = PR_GetErrorText(ret);
		ret[len] = '\0';
	}

	return ret;
}
Ejemplo n.º 8
0
void
SECU_PrintPRandOSError(const char *progName)
{
    char buffer[513];
    PRInt32 errLen = PR_GetErrorTextLength();
    if (errLen > 0 && errLen < sizeof buffer) {
        PR_GetErrorText(buffer);
    }
    SECU_PrintError(progName, "function failed");
    if (errLen > 0 && errLen < sizeof buffer) {
        PR_fprintf(PR_STDERR, "\t%s\n", buffer);
    }
}
static void
load_nss (GsdSmartcardManager *self)
{
        GsdSmartcardManagerPrivate *priv = self->priv;
        NSSInitContext *context = NULL;

        /* The first field in the NSSInitParameters structure
         * is the size of the structure. NSS requires this, so
         * that it can change the size of the structure in future
         * versions of NSS in a detectable way
         */
        NSSInitParameters parameters = { sizeof (parameters), };
        static const guint32 flags = NSS_INIT_READONLY
                                   | NSS_INIT_FORCEOPEN
                                   | NSS_INIT_NOROOTINIT
                                   | NSS_INIT_OPTIMIZESPACE
                                   | NSS_INIT_PK11RELOAD;

        g_debug ("attempting to load NSS database '%s'",
                 GSD_SMARTCARD_MANAGER_NSS_DB);

        PR_Init (PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

        context = NSS_InitContext (GSD_SMARTCARD_MANAGER_NSS_DB,
                                   "", "", SECMOD_DB, &parameters, flags);

        if (context == NULL) {
                gsize error_message_size;
                char *error_message;

                error_message_size = PR_GetErrorTextLength ();

                if (error_message_size == 0) {
                        g_debug ("NSS security system could not be initialized");
                } else {
                        error_message = g_alloca (error_message_size);
                        PR_GetErrorText (error_message);

                        g_debug ("NSS security system could not be initialized - %s",
                                 error_message);
                }

                priv->nss_context = NULL;
                return;

        }

        g_debug ("NSS database '%s' loaded", GSD_SMARTCARD_MANAGER_NSS_DB);
        priv->nss_context = context;
}
Ejemplo n.º 10
0
char *
sc_get_nss_error (void)
{
    gsize error_message_size;
    gchar *error_message;

    error_message_size = PR_GetErrorTextLength ();
    if (error_message_size) {
        error_message = g_malloc0 (error_message_size);
        PR_GetErrorText (error_message);
    } else {
        error_message = g_strdup (_("unavailable nss error"));
    }
    return error_message;
}
Ejemplo n.º 11
0
void
e_msgport_put (EMsgPort *msgport, EMsg *msg)
{
	gint fd;
#ifdef HAVE_NSS
	PRFileDesc *prfd;
#endif

	g_return_if_fail (msgport != NULL);
	g_return_if_fail (msg != NULL);

	g_async_queue_lock (msgport->queue);

	msg->flags = 0;

	fd = msgport->pipe[1];
	while (fd >= 0) {
		if (E_WRITE (fd, "E", 1) > 0) {
			msg->flags |= MSG_FLAG_SYNC_WITH_PIPE;
			break;
		} else if (!E_IS_STATUS_INTR ()) {
			g_warning ("%s: Failed to write to pipe: %s",
				G_STRFUNC, g_strerror (errno));
			break;
		}
	}

#ifdef HAVE_NSS
	prfd = msgport->prpipe[1];
	while (prfd != NULL) {
		if (PR_Write (prfd, "E", 1) > 0) {
			msg->flags |= MSG_FLAG_SYNC_WITH_PR_PIPE;
			break;
		} else if (PR_GetError () != PR_PENDING_INTERRUPT_ERROR) {
			gchar *text = g_alloca (PR_GetErrorTextLength ());
			PR_GetErrorText (text);
			g_warning ("%s: Failed to write to NSPR pipe: %s",
				G_STRFUNC, text);
			break;
		}
	}
#endif

	g_async_queue_push_unlocked (msgport->queue, msg);
	g_async_queue_unlock (msgport->queue);
}
Ejemplo n.º 12
0
static void
msgport_sync_with_prpipe (PRFileDesc *prfd)
{
	gchar buffer[1];

	while (prfd != NULL) {
		if (PR_Read (prfd, buffer, 1) > 0)
			break;
		else if (PR_GetError () != PR_PENDING_INTERRUPT_ERROR) {
			gchar *text = g_alloca (PR_GetErrorTextLength ());
			PR_GetErrorText (text);
			g_warning ("%s: Failed to read from NSPR pipe: %s",
				G_STRFUNC, text);
			break;
		}
	}
}
Ejemplo n.º 13
0
void
nss_gen_err(const char *fmt, ...)
{
	va_list	ap;
	char	*text;
	int	len;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	if ((len = PR_GetErrorTextLength()) > 0) {
		text = ac_alloc(len);
		if (PR_GetErrorText(text) > 0)
			fprintf(stderr, ": %s\n", text);
		ac_free(text);
	} else
		fprintf(stderr, ": %s.\n", nss_strerror(PR_GetError()));
}
static void
load_nss (GsdSmartcardManager *self)
{
        GsdSmartcardManagerPrivate *priv = self->priv;
        SECStatus status = SECSuccess;
        static const guint32 flags = NSS_INIT_READONLY
                                   | NSS_INIT_FORCEOPEN
                                   | NSS_INIT_NOROOTINIT
                                   | NSS_INIT_OPTIMIZESPACE
                                   | NSS_INIT_PK11RELOAD;

        g_debug ("attempting to load NSS database '%s'",
                 GSD_SMARTCARD_MANAGER_NSS_DB);

        PR_Init (PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

        status = NSS_Initialize (GSD_SMARTCARD_MANAGER_NSS_DB,
                                 "", "", SECMOD_DB, flags);

        if (status != SECSuccess) {
                gsize error_message_size;
                char *error_message;

                error_message_size = PR_GetErrorTextLength ();

                if (error_message_size == 0) {
                        g_debug ("NSS security system could not be initialized");
                } else {
                        error_message = g_alloca (error_message_size);
                        PR_GetErrorText (error_message);

                        g_debug ("NSS security system could not be initialized - %s",
                                 error_message);
                }
                priv->nss_is_loaded = FALSE;
                return;

        }

        g_debug ("NSS database '%s' loaded", GSD_SMARTCARD_MANAGER_NSS_DB);
        priv->nss_is_loaded = TRUE;
}
Ejemplo n.º 15
0
void _PR_InitLinker(void)
{
    PRLibrary *lm = NULL;
#if defined(XP_UNIX) || defined(XP_AMIGAOS)
    void *h;
#endif

    if (!pr_linker_lock) {
        pr_linker_lock = PR_NewNamedMonitor("linker-lock");
    }
    PR_EnterMonitor(pr_linker_lock);

#if defined(XP_PC)
    lm = PR_NEWZAP(PRLibrary);
    lm->name = strdup("Executable");
#if defined(XP_OS2)
    lm->dlh = NULLHANDLE;
#else
    /* A module handle for the executable. */
    lm->dlh = GetModuleHandle(NULL);
#endif /* ! XP_OS2 */

    lm->refCount    = 1;
    lm->staticTable = NULL;
    pr_exe_loadmap  = lm;
    pr_loadmap      = lm;

#elif defined(XP_UNIX) || defined(XP_AMIGAOS)
#ifdef HAVE_DLL
#if defined(USE_DLFCN) && !defined(NO_DLOPEN_NULL)
    h = dlopen(0, RTLD_LAZY);
    if (!h) {
        char *error;

        DLLErrorInternal(_MD_ERRNO());
        error = (char*)PR_MALLOC(PR_GetErrorTextLength());
        (void) PR_GetErrorText(error);
        fprintf(stderr, "failed to initialize shared libraries [%s]\n",
            error);
        PR_DELETE(error);
        abort();/* XXX */
    }
#elif defined(USE_HPSHL)
    h = NULL;
    /* don't abort with this NULL */
#elif defined(USE_MACH_DYLD) || defined(NO_DLOPEN_NULL)
    h = NULL; /* XXXX  toshok */ /* XXXX  vlad */
#else
#error no dll strategy
#endif /* USE_DLFCN */

    lm = PR_NEWZAP(PRLibrary);
    if (lm) {
        lm->name = strdup("a.out");
        lm->refCount = 1;
        lm->dlh = h;
        lm->staticTable = NULL;
    }
    pr_exe_loadmap = lm;
    pr_loadmap = lm;
#endif /* HAVE_DLL */
#endif /* XP_UNIX */

    if (lm) {
        PR_LOG(_pr_linker_lm, PR_LOG_MIN,
            ("Loaded library %s (init)", lm->name));
    }

    PR_ExitMonitor(pr_linker_lock);
}
Ejemplo n.º 16
0
JSObject*
Library::Create(JSContext* cx, HandleValue path, const JSCTypesCallbacks* callbacks)
{
  RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass));
  if (!libraryObj)
    return nullptr;

  // initialize the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(nullptr));

  // attach API functions
  if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions))
    return nullptr;

  if (!path.isString()) {
    JS_ReportErrorASCII(cx, "open takes a string argument");
    return nullptr;
  }

  PRLibSpec libSpec;
  RootedFlatString pathStr(cx, JS_FlattenString(cx, path.toString()));
  if (!pathStr)
    return nullptr;
  AutoStableStringChars pathStrChars(cx);
  if (!pathStrChars.initTwoByte(cx, pathStr))
    return nullptr;
#ifdef XP_WIN
  // On Windows, converting to native charset may corrupt path string.
  // So, we have to use Unicode path directly.
  char16ptr_t pathChars = pathStrChars.twoByteChars();
  libSpec.value.pathname_u = pathChars;
  libSpec.type = PR_LibSpec_PathnameU;
#else
  // Convert to platform native charset if the appropriate callback has been
  // provided.
  char* pathBytes;
  if (callbacks && callbacks->unicodeToNative) {
    pathBytes =
      callbacks->unicodeToNative(cx, pathStrChars.twoByteChars(), pathStr->length());
    if (!pathBytes)
      return nullptr;

  } else {
    // Fallback: assume the platform native charset is UTF-8. This is true
    // for Mac OS X, Android, and probably Linux.
    size_t nbytes =
      GetDeflatedUTF8StringLength(cx, pathStrChars.twoByteChars(), pathStr->length());
    if (nbytes == (size_t) -1)
      return nullptr;

    pathBytes = static_cast<char*>(JS_malloc(cx, nbytes + 1));
    if (!pathBytes)
      return nullptr;

    ASSERT_OK(DeflateStringToUTF8Buffer(cx, pathStrChars.twoByteChars(),
                pathStr->length(), pathBytes, &nbytes));
    pathBytes[nbytes] = 0;
  }

  libSpec.value.pathname = pathBytes;
  libSpec.type = PR_LibSpec_Pathname;
#endif

  PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW);

#ifndef XP_WIN
  JS_free(cx, pathBytes);
#endif

  if (!library) {
#define MAX_ERROR_LEN 1024
    char error[MAX_ERROR_LEN] = "Cannot get error from NSPR.";
    uint32_t errorLen = PR_GetErrorTextLength();
    if (errorLen && errorLen < MAX_ERROR_LEN)
      PR_GetErrorText(error);
#undef MAX_ERROR_LEN

    if (JS::StringIsASCII(error)) {
      JSAutoByteString pathCharsUTF8;
      if (pathCharsUTF8.encodeUtf8(cx, pathStr))
        JS_ReportErrorUTF8(cx, "couldn't open library %s: %s", pathCharsUTF8.ptr(), error);
    } else {
      JSAutoByteString pathCharsLatin1;
      if (pathCharsLatin1.encodeLatin1(cx, pathStr))
        JS_ReportErrorLatin1(cx, "couldn't open library %s: %s", pathCharsLatin1.ptr(), error);
    }
    return nullptr;
  }

  // stash the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(library));

  return libraryObj;
}
const mozilla::Module*
nsNativeModuleLoader::LoadModule(nsILocalFile* aFile)
{
    nsresult rv;

    if (!NS_IsMainThread()) {
        // If this call is off the main thread, synchronously proxy it
        // to the main thread.
        nsRefPtr<LoadModuleMainThreadRunnable> r = new LoadModuleMainThreadRunnable(this, aFile);
        NS_DispatchToMainThread(r, NS_DISPATCH_SYNC);
        return r->mResult;
    }

    nsCOMPtr<nsIHashable> hashedFile(do_QueryInterface(aFile));
    if (!hashedFile) {
        NS_ERROR("nsIFile is not nsIHashable");
        return NULL;
    }

    nsCAutoString filePath;
    aFile->GetNativePath(filePath);

    NativeLoadData data;

    if (mLibraries.Get(hashedFile, &data)) {
        NS_ASSERTION(data.module, "Corrupt mLibraries hash");
        LOG(PR_LOG_DEBUG,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache",
             filePath.get()));
        return data.module;
    }

    // We haven't loaded this module before

    rv = aFile->Load(&data.library);

    if (NS_FAILED(rv)) {
        char errorMsg[1024] = "<unknown; can't get error from NSPR>";

        if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
            PR_GetErrorText(errorMsg);

        LOG(PR_LOG_ERROR,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - load FAILED, "
             "rv: %lx, error:\n\t%s\n",
             filePath.get(), rv, errorMsg));

#ifdef DEBUG
        fprintf(stderr,
                "nsNativeModuleLoader::LoadModule(\"%s\") - load FAILED, "
                "rv: %lx, error:\n\t%s\n",
                filePath.get(), (unsigned long)rv, errorMsg);
#endif

        return NULL;
    }

#ifdef IMPLEMENT_BREAK_AFTER_LOAD
    nsCAutoString leafName;
    aFile->GetNativeLeafName(leafName);

    char *env = getenv("XPCOM_BREAK_ON_LOAD");
    char *blist;
    if (env && *env && (blist = strdup(env))) {
        char *nextTok = blist;
        while (char *token = NS_strtok(":", &nextTok)) {
            if (leafName.Find(token, PR_TRUE) != kNotFound) {
                NS_BREAK();
            }
        }

        free(blist);
    }
#endif

    void *module = PR_FindSymbol(data.library, "NSModule");
    if (module) {
        data.module = *(mozilla::Module const *const *) module;
        if (mLibraries.Put(hashedFile, data))
            return data.module;
    }
    else {
        LOG(PR_LOG_ERROR,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - "
             "Symbol NSModule not found", filePath.get()));
    }

    // at some point we failed, clean up
    data.module = nsnull;
    PR_UnloadLibrary(data.library);

    return NULL;
}
Ejemplo n.º 18
0
ErrorString::ErrorString() : code(PR_GetError()), buffer(new char[PR_GetErrorTextLength()]), used(PR_GetErrorText(buffer)) {}    
Ejemplo n.º 19
0
/****************************************************************
 *
 * J z i p A d d
 *
 * Adds a new file into a ZIP file.  The ZIP file must have already
 * been opened with JzipOpen.
 */
int
JzipAdd(char *fullname, char *filename, ZIPfile *zipfile, int compression_level)
{
    ZIPentry *entry;
    PRFileDesc *readfp;
    PRFileDesc *zipfp;
    unsigned long crc;
    unsigned long local_size_pos;
    int num;
    int err;
    int deflate_percent;
    z_stream zstream;
    Bytef inbuf[BUFSIZ];
    Bytef outbuf[BUFSIZ];

    if (!fullname || !filename || !zipfile) {
        return -1;
    }

    zipfp = zipfile->fp;
    if (!zipfp)
        return -1;

    if ((readfp = PR_Open(fullname, PR_RDONLY, 0777)) == NULL) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "%s: %s\n", fullname, nsprErr ? nsprErr : "");
        errorCount++;
        if (nsprErr)
            PR_Free(nsprErr);
        exit(ERRX);
    }

    /*
     * Make sure the input file is not the output file.
     * Add a few bytes to the end of the JAR file and see if the input file
     * twitches
     */
    {
        PRInt32 endOfJar;
        PRInt32 inputSize;
        PRBool isSame;

        inputSize = PR_Available(readfp);

        endOfJar = PR_Seek(zipfp, 0L, PR_SEEK_CUR);

        if (PR_Write(zipfp, "abcde", 5) < 5) {
            char *nsprErr;

            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing to zip file: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }

        isSame = (PR_Available(readfp) != inputSize);

        PR_Seek(zipfp, endOfJar, PR_SEEK_SET);

        if (isSame) {
            /* It's the same file! Forget it! */
            PR_Close(readfp);
            return 0;
        }
    }

    if (verbosity >= 0) {
        PR_fprintf(outputFD, "adding %s to %s...", fullname, zipfile->filename);
    }

    entry = PORT_ZAlloc(sizeof(ZIPentry));
    if (!entry)
        out_of_memory();

    entry->filename = PORT_Strdup(filename);
    entry->comment = NULL;

    /* Set up local file header */
    longtox(LSIG, entry->local.signature);
    inttox(strlen(filename), entry->local.filename_len);
    inttox(zipfile->time, entry->local.time);
    inttox(zipfile->date, entry->local.date);
    inttox(Z_DEFLATED, entry->local.method);

    /* Set up central directory entry */
    longtox(CSIG, entry->central.signature);
    inttox(strlen(filename), entry->central.filename_len);
    if (entry->comment) {
        inttox(strlen(entry->comment), entry->central.commentfield_len);
    }
    longtox(PR_Seek(zipfile->fp, 0, PR_SEEK_CUR),
            entry->central.localhdr_offset);
    inttox(zipfile->time, entry->central.time);
    inttox(zipfile->date, entry->central.date);
    inttox(Z_DEFLATED, entry->central.method);

    /* Compute crc.  Too bad we have to process the whole file to do this*/
    crc = crc32(0L, NULL, 0);
    while ((num = PR_Read(readfp, inbuf, BUFSIZ)) > 0) {
        crc = crc32(crc, inbuf, num);
    }
    PR_Seek(readfp, 0L, PR_SEEK_SET);

    /* Store CRC */
    longtox(crc, entry->local.crc32);
    longtox(crc, entry->central.crc32);

    /* Stick this entry onto the end of the list */
    entry->next = NULL;
    if (zipfile->list == NULL) {
        /* First entry */
        zipfile->list = entry;
    } else {
        ZIPentry *pe;

        pe = zipfile->list;
        while (pe->next != NULL) {
            pe = pe->next;
        }
        pe->next = entry;
    }

    /*
     * Start writing stuff out
     */

    local_size_pos = PR_Seek(zipfp, 0, PR_SEEK_CUR) + 18;
    /* File header */
    if (PR_Write(zipfp, &entry->local, sizeof(struct ZipLocal)) <
        sizeof(struct ZipLocal)) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }

    /* File Name */
    if (PR_Write(zipfp, filename, strlen(filename)) < strlen(filename)) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }

    /*
     * File data
     */
    /* Initialize zstream */
    zstream.zalloc = my_alloc_func;
    zstream.zfree = my_free_func;
    zstream.opaque = NULL;
    zstream.next_in = inbuf;
    zstream.avail_in = BUFSIZ;
    zstream.next_out = outbuf;
    zstream.avail_out = BUFSIZ;
    /* Setting the windowBits to -MAX_WBITS is an undocumented feature of
     * zlib (see deflate.c in zlib).  It is the same thing that Java does
     * when you specify the nowrap option for deflation in java.util.zip.
     * It causes zlib to leave out its headers and footers, which don't
     * work in PKZIP files.
     */
    err = deflateInit2(&zstream, compression_level, Z_DEFLATED,
                       -MAX_WBITS, 8 /*default*/, Z_DEFAULT_STRATEGY);
    if (err != Z_OK) {
        handle_zerror(err, zstream.msg);
        exit(ERRX);
    }

    while ((zstream.avail_in = PR_Read(readfp, inbuf, BUFSIZ)) > 0) {
        zstream.next_in = inbuf;
        /* Process this chunk of data */
        while (zstream.avail_in > 0) {
            err = deflate(&zstream, Z_NO_FLUSH);
            if (err != Z_OK) {
                handle_zerror(err, zstream.msg);
                exit(ERRX);
            }
            if (zstream.avail_out <= 0) {
                if (PR_Write(zipfp, outbuf, BUFSIZ) < BUFSIZ) {
                    char *nsprErr;
                    if (PR_GetErrorTextLength()) {
                        nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                        PR_GetErrorText(nsprErr);
                    } else {
                        nsprErr = NULL;
                    }
                    PR_fprintf(errorFD, "Writing zip data: %s\n",
                               nsprErr ? nsprErr : "");
                    if (nsprErr)
                        PR_Free(nsprErr);
                    errorCount++;
                    exit(ERRX);
                }
                zstream.next_out = outbuf;
                zstream.avail_out = BUFSIZ;
            }
        }
    }

    /* Now flush everything */
    while (1) {
        err = deflate(&zstream, Z_FINISH);
        if (err == Z_STREAM_END) {
            break;
        } else if (err == Z_OK) {
            /* output buffer full, repeat */
        } else {
            handle_zerror(err, zstream.msg);
            exit(ERRX);
        }
        if (PR_Write(zipfp, outbuf, BUFSIZ) < BUFSIZ) {
            char *nsprErr;
            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing zip data: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }
        zstream.avail_out = BUFSIZ;
        zstream.next_out = outbuf;
    }

    /* If there's any output left, write it out. */
    if (zstream.next_out != outbuf) {
        if (PR_Write(zipfp, outbuf, zstream.next_out - outbuf) <
            zstream.next_out - outbuf) {
            char *nsprErr;
            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing zip data: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }
        zstream.avail_out = BUFSIZ;
        zstream.next_out = outbuf;
    }

    /* Now that we know the compressed size, write this to the headers */
    longtox(zstream.total_in, entry->local.orglen);
    longtox(zstream.total_out, entry->local.size);
    if (PR_Seek(zipfp, local_size_pos, PR_SEEK_SET) == -1) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Accessing zip file: %s\n", nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }
    if (PR_Write(zipfp, entry->local.size, 8) != 8) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }
    if (PR_Seek(zipfp, 0L, PR_SEEK_END) == -1) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Accessing zip file: %s\n",
                   nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }
    longtox(zstream.total_in, entry->central.orglen);
    longtox(zstream.total_out, entry->central.size);

    /* Close out the deflation operation */
    err = deflateEnd(&zstream);
    if (err != Z_OK) {
        handle_zerror(err, zstream.msg);
        exit(ERRX);
    }

    PR_Close(readfp);

    if ((zstream.total_in > zstream.total_out) && (zstream.total_in > 0)) {
        deflate_percent = (int)((zstream.total_in -
                                 zstream.total_out) *
                                100 / zstream.total_in);
    } else {
        deflate_percent = 0;
    }
    if (verbosity >= 0) {
        PR_fprintf(outputFD, "(deflated %d%%)\n", deflate_percent);
    }

    return 0;
}
Ejemplo n.º 20
0
/********************************************************************
 * J z i p C l o s e
 *
 * Finishes the ZipFile. ALSO DELETES THE ZIPFILE STRUCTURE PASSED IN!!
 */
int
JzipClose(ZIPfile *zipfile)
{
    ZIPentry *pe, *dead;
    PRFileDesc *zipfp;
    struct ZipEnd zipend;
    unsigned int entrycount = 0;

    if (!zipfile) {
        return -1;
    }

    if (!zipfile->filename) {
        /* bogus */
        return 0;
    }

    zipfp = zipfile->fp;
    zipfile->central_start = PR_Seek(zipfp, 0L, PR_SEEK_CUR);

    /* Write out all the central directories */
    pe = zipfile->list;
    while (pe) {
        entrycount++;

        /* Write central directory info */
        if (PR_Write(zipfp, &pe->central, sizeof(struct ZipCentral)) <
            sizeof(struct ZipCentral)) {
            char *nsprErr;
            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing zip data: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }

        /* Write filename */
        if (PR_Write(zipfp, pe->filename, strlen(pe->filename)) <
            strlen(pe->filename)) {
            char *nsprErr;
            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing zip data: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }

        /* Write file comment */
        if (pe->comment) {
            if (PR_Write(zipfp, pe->comment, strlen(pe->comment)) <
                strlen(pe->comment)) {
                char *nsprErr;
                if (PR_GetErrorTextLength()) {
                    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                    PR_GetErrorText(nsprErr);
                } else {
                    nsprErr = NULL;
                }
                PR_fprintf(errorFD, "Writing zip data: %s\n",
                           nsprErr ? nsprErr : "");
                if (nsprErr)
                    PR_Free(nsprErr);
                errorCount++;
                exit(ERRX);
            }
        }

        /* Delete the structure */
        dead = pe;
        pe = pe->next;
        if (dead->filename) {
            PORT_Free(dead->filename);
        }
        if (dead->comment) {
            PORT_Free(dead->comment);
        }
        PORT_Free(dead);
    }
    zipfile->central_end = PR_Seek(zipfile->fp, 0L, PR_SEEK_CUR);

    /* Create the ZipEnd structure */
    PORT_Memset(&zipend, 0, sizeof(zipend));
    longtox(ESIG, zipend.signature);
    inttox(entrycount, zipend.total_entries_disk);
    inttox(entrycount, zipend.total_entries_archive);
    longtox(zipfile->central_end - zipfile->central_start,
            zipend.central_dir_size);
    longtox(zipfile->central_start, zipend.offset_central_dir);
    if (zipfile->comment) {
        inttox(strlen(zipfile->comment), zipend.commentfield_len);
    }

    /* Write out ZipEnd xtructure */
    if (PR_Write(zipfp, &zipend, sizeof(zipend)) < sizeof(zipend)) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "Writing zip data: %s\n",
                   nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }

    /* Write out Zipfile comment */
    if (zipfile->comment) {
        if (PR_Write(zipfp, zipfile->comment, strlen(zipfile->comment)) <
            strlen(zipfile->comment)) {
            char *nsprErr;
            if (PR_GetErrorTextLength()) {
                nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
                PR_GetErrorText(nsprErr);
            } else {
                nsprErr = NULL;
            }
            PR_fprintf(errorFD, "Writing zip data: %s\n",
                       nsprErr ? nsprErr : "");
            if (nsprErr)
                PR_Free(nsprErr);
            errorCount++;
            exit(ERRX);
        }
    }

    PR_Close(zipfp);

    /* Free the memory of the zipfile structure */
    if (zipfile->filename) {
        PORT_Free(zipfile->filename);
    }
    if (zipfile->comment) {
        PORT_Free(zipfile->comment);
    }
    PORT_Free(zipfile);

    return 0;
}
const mozilla::Module*
nsNativeModuleLoader::LoadModule(nsILocalFile* aFile)
{
    nsresult rv;

    if (!NS_IsMainThread()) {
        // If this call is off the main thread, synchronously proxy it
        // to the main thread.
        nsRefPtr<LoadModuleMainThreadRunnable> r = new LoadModuleMainThreadRunnable(this, aFile);
        NS_DispatchToMainThread(r, NS_DISPATCH_SYNC);
        return r->mResult;
    }

    nsCOMPtr<nsIHashable> hashedFile(do_QueryInterface(aFile));
    if (!hashedFile) {
        NS_ERROR("nsIFile is not nsIHashable");
        return NULL;
    }

    nsCAutoString filePath;
    aFile->GetNativePath(filePath);

    NativeLoadData data;

    if (mLibraries.Get(hashedFile, &data)) {
        NS_ASSERTION(data.module, "Corrupt mLibraries hash");
        LOG(PR_LOG_DEBUG,
            ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache",
             filePath.get()));
        return data.module;
    }

    // We haven't loaded this module before

    rv = aFile->Load(&data.library);

    if (NS_FAILED(rv)) {
        char errorMsg[1024] = "<unknown; can't get error from NSPR>";

        if (PR_GetErrorTextLength() < (int) sizeof(errorMsg))
            PR_GetErrorText(errorMsg);

        LogMessage("Failed to load native module at path '%s': (%lx) %s",
                   filePath.get(), rv, errorMsg);

        return NULL;
    }

#ifdef IMPLEMENT_BREAK_AFTER_LOAD
    nsCAutoString leafName;
    aFile->GetNativeLeafName(leafName);

    char *env = getenv("XPCOM_BREAK_ON_LOAD");
    char *blist;
    if (env && *env && (blist = strdup(env))) {
        char *nextTok = blist;
        while (char *token = NS_strtok(":", &nextTok)) {
            if (leafName.Find(token, true) != kNotFound) {
                NS_BREAK();
            }
        }

        free(blist);
    }
#endif

    void *module = PR_FindSymbol(data.library, "NSModule");
    if (!module) {
        LogMessage("Native module at path '%s' doesn't export symbol `NSModule`.",
                   filePath.get());
        PR_UnloadLibrary(data.library);
        return NULL;
    }

    data.module = *(mozilla::Module const *const *) module;
    if (mozilla::Module::kVersion != data.module->mVersion) {
        LogMessage("Native module at path '%s' is incompatible with this version of Firefox, has version %i, expected %i.",
                   filePath.get(), data.module->mVersion,
                   mozilla::Module::kVersion);
        PR_UnloadLibrary(data.library);
        return NULL;
    }
        
    mLibraries.Put(hashedFile, data); // infallible
    return data.module;
}
Ejemplo n.º 22
0
JSBool
__Core_include (JSContext* cx, std::string path)
{
    if (__Core_isIncluded(path)) {
        #ifdef DEBUG
        std::cerr << "(already included) " << path << "." << std::endl;
        #endif

        return JS_TRUE;
    }

    if (path.substr(path.length()-3) == ".js") {
        struct stat pathStat;

        if (stat(path.c_str(), &pathStat) == -1) {
            #ifdef DEBUG
            std::cerr << "(javascript) ";
            #endif
 
            std::cerr << path << " not found." << std::endl;
            return JS_FALSE;
        }
        
        std::string cachePath = path + "c";
        struct stat cacheStat;
        if (!stat(cachePath.c_str(), &cacheStat)) {
            if (cacheStat.st_mtime >= pathStat.st_mtime) {
                try {
                    lulzJS::Script script(cx, cachePath, lulzJS::Script::Bytecode);
                    script.execute();
                }
                catch (std::exception e) { }

                if (JS_IsExceptionPending(cx)) {
                    JS_ReportPendingException(cx);
                    return JS_FALSE;
                }
            }
        }

        #ifdef DEBUG
        std::cerr << "(javascript) path: " << path << std::endl;
        #endif

        try {
            lulzJS::Script script(cx, path, lulzJS::Script::Text);
            script.execute();

            if (JS_IsExceptionPending(cx)) {
                JS_ReportPendingException(cx);
                return JS_FALSE;
            }

            script.save(cachePath, lulzJS::Script::Bytecode);
        }
        catch (std::runtime_error e) {
            JS_ReportPendingException(cx);
            return JS_FALSE;
        }
    }
    else if (path.substr(path.length()-3) == ".so") {
        #ifdef DEBUG
        std::cerr << "(object) path: " << path << std::endl;
        #endif

        struct stat test;
        if (stat(path.c_str(), &test)) {
            #ifdef DEBUG
            std::cerr << "(object) ";
            #endif

            std::cerr << path << " not found." << std::endl;
            return JS_FALSE;
        }

        PRLibrary* lib = PR_LoadLibrary(path.c_str());

        if (!lib) {
            char* error = new char[PR_GetErrorTextLength()];
            PR_GetErrorText(error);
            std::cerr << error << std::endl;
            delete [] error;
            return JS_FALSE;
        }

        JSBool (*exec)(JSContext*) = (JSBool (*)(JSContext*)) PR_FindSymbol(lib, "exec");

        if (exec == NULL || !(*exec)(cx)) {
            #ifdef DEBUG
            std::cerr << "Couldn't retrieve the symbol." << std::endl;
            #endif

            std::cerr << "The initialization of the module failed." << std::endl;
            return JS_FALSE;
        }
    }
    else {
        #ifdef DEBUG
        std::cerr << "(module) path: " << path << std::endl;
        #endif

        struct stat test;
        if (stat(path.c_str(), &test)) {
            #ifdef DEBUG
            std::cerr << "(module) ";
            #endif

            std::cerr << path << " not found." << std::endl;
            return JS_FALSE;
        }

        if (!__Core_include(cx, path + "/init.js")) {
            return JS_FALSE;
        }
    }

    included.push_back(path);

    return JS_TRUE;
}