// The file name must be in the form "np*.dll"
PRBool nsPluginsDir::IsPluginFile(nsIFile* file)
{
  nsCAutoString path;
  if (NS_FAILED(file->GetNativePath(path)))
    return PR_FALSE;

  const char *cPath = path.get();

  // this is most likely a path, so skip to the filename
  const char* filename = PL_strrchr(cPath, '\\');
  if (filename)
    ++filename;
  else
    filename = cPath;

  char* extension = PL_strrchr(filename, '.');
  if (extension)
    ++extension;

  PRUint32 fullLength = PL_strlen(filename);
  PRUint32 extLength = PL_strlen(extension);
  if (fullLength >= 7 && extLength == 3) {
    if (!PL_strncasecmp(filename, "np", 2) && !PL_strncasecmp(extension, "dll", 3)) {
      // don't load OJI-based Java plugins
      if (!PL_strncasecmp(filename, "npoji", 5) ||
          !PL_strncasecmp(filename, "npjava", 6))
        return PR_FALSE;
      return PR_TRUE;
    }
  }

  return PR_FALSE;
}
Esempio n. 2
0
/*
 *  m a n i f e s t o _ x p i _ f n
 *
 *  Called by pointer from SignArchive(), once for
 *  each file within the directory. This function
 *  is only used for adding to XPI compatible archive
 *
 */
static int
manifesto_xpi_fn(char *relpath, char *basedir, char *reldir, char *filename, void *arg)
{
    char fullname[FNSIZE];
    int count;

    if (verbosity >= 0) {
        PR_fprintf(outputFD, "--> %s\n", relpath);
    }

    /* extension matching */
    if (extensionsGiven) {
        char *ext = PL_strrchr(relpath, '.');
        if (!ext)
            return 0;
        if (!PL_HashTableLookup(extensions, ext))
            return 0;
    }
    count = snprintf(fullname, sizeof(fullname), "%s/%s", basedir, relpath);
    if (count >= sizeof(fullname)) {
        return 1;
    }
    JzipAdd(fullname, relpath, zipfile, compression_level);

    return 0;
}
NSAPI_PUBLIC char * baseName (const char *fileName) {
  char *base = NULL;
  char *fname = NULL;
  base = PL_strdup(fileName);
  fname = base;
  int len = PL_strlen(fname);
  char *p = PL_strrchr(base, '/');

#ifdef XP_WIN32
    if (!p) {  // if no forward slashes check for backward slashes
        p = PL_strrchr(base, '\\');
    }
#endif // XP_WIN32

  if (!p) {  // if no slashes
#ifdef XP_WIN32
    char *driveLetter = strchr(base, ':');
    if (driveLetter) {   // specified only the drive letter
        base = NULL;
    }
#endif // XP_WIN32
  } else if (p == base)  { // only one slash
    if (len > 1) { // more chars after '/'
        base = p + 1;
    } else {
        base = NULL;
    }
  } else if (p == (base + (len - 1))) {
      // name is ending with a slash..set base to NULL
      base = NULL;
  } else {
      base = p + 1;
  }

  if (!base) {
     // set the passed name as the base name
     base = fname;
  }

  char *bname = PL_strdup(base);
  PL_strfree(fname);

  return bname;
}
static char* GetFileName(const char* pathname)
{
        const char* filename = nsnull;
                
        // this is most likely a path, so skip to the filename
        filename = PL_strrchr(pathname, '/');
        if(filename)
                ++filename;
        else
                filename = pathname;

        return PL_strdup(filename);
}
Esempio n. 5
0
VObject* addGroup(VObject *o, const char *g)
{
    /*
  a.b.c
  -->
  prop(c)
      prop(VCGrouping=b)
    prop(VCGrouping=a)
     */
    char *dot = PL_strrchr(g,'.');
    if (dot) {
  VObject *p, *t;
  char *gs, *n = dot+1;
  gs = dupStr(g,0); /* so we can write to it. */
  t = p = addProp_(o,lookupProp(n));
  dot = PL_strrchr(gs,'.');
  *dot = 0;
  do {
      dot = PL_strrchr(gs,'.');
      if (dot) {
    n = dot+1;
    *dot=0;
    }
      else
    n = gs;
      /* property(VCGroupingProp=n);
       *  and the value may have VCGrouping property
       */
      t = addProp(t,VCGroupingProp);
      setVObjectStringZValue(t,lookupProp_(n));
      } while (n != gs);
  deleteString(gs); 
  return p;
  }
    else
  return addProp_(o,lookupProp(g));
}
void
IPC_InitModuleReg(const char *exePath)
{
    if (!(exePath && *exePath))
        return;

    //
    // register plug-in modules
    //
    char *p = PL_strrchr(exePath, IPC_PATH_SEP_CHAR);
    if (p == NULL) {
        LOG(("unexpected exe path\n"));
        return;
    }

    int baseLen = p - exePath;
    int finalLen = baseLen + 1 + sizeof(IPC_MODULES_DIR);

    // build full path to ipc modules
    char *modulesDir = (char*) malloc(finalLen);
    memcpy(modulesDir, exePath, baseLen);
    modulesDir[baseLen] = IPC_PATH_SEP_CHAR;
    memcpy(modulesDir + baseLen + 1, IPC_MODULES_DIR, sizeof(IPC_MODULES_DIR));

    LOG(("loading libraries in %s\n", modulesDir));
    // 
    // scan directory for IPC modules
    //
    PRDir *dir = PR_OpenDir(modulesDir);
    if (dir) {
        PRDirEntry *ent;
        while ((ent = PR_ReadDir(dir, PR_SKIP_BOTH)) != NULL) {
            // 
            // locate extension, and check if dynamic library
            //

            const char *p = strrchr(ent->name, '.');
            if (p && PL_strcasecmp(p, MOZ_DLL_SUFFIX) == 0)
                InitModuleFromLib(modulesDir, ent->name);
        }
        PR_CloseDir(dir);
    }

    free(modulesDir);
}
Esempio n. 7
0
int
main (int argc, char **argv)
{
    int		 retval;
    PRFileDesc	*in_file;
    FILE	*out_file;	/* not PRFileDesc until SECU accepts it */
    int		 crequest, dresponse;
    int		 prequest, presponse;
    int		 ccert, vcert;
    const char	*db_dir, *date_str, *cert_usage_str, *name;
    const char	*responder_name, *responder_url, *signer_name;
    PRBool	 add_acceptable_responses, add_service_locator;
    SECItem	*data = NULL;
    PLOptState	*optstate;
    SECStatus	 rv;
    CERTCertDBHandle *handle = NULL;
    SECCertUsage cert_usage;
    PRTime	 verify_time;
    CERTCertificate *cert = NULL;
    PRBool ascii = PR_FALSE;

    retval = -1;		/* what we return/exit with on error */

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    in_file = PR_STDIN;
    out_file = stdout;

    crequest = 0;
    dresponse = 0;
    prequest = 0;
    presponse = 0;
    ccert = 0;
    vcert = 0;

    db_dir = NULL;
    date_str = NULL;
    cert_usage_str = NULL;
    name = NULL;
    responder_name = NULL;
    responder_url = NULL;
    signer_name = NULL;

    add_acceptable_responses = PR_FALSE;
    add_service_locator = PR_FALSE;

    optstate = PL_CreateOptState (argc, argv, "AHLPR:S:V:d:l:pr:s:t:u:w:");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return retval;
    }

    while (PL_GetNextOpt (optstate) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return retval;

	  case 'A':
	    add_acceptable_responses = PR_TRUE;
	    break;

	  case 'H':
	    long_usage (program_name);
	    return retval;

	  case 'L':
	    add_service_locator = PR_TRUE;
	    break;

	  case 'P':
	    presponse = 1;
	    break;

	  case 'R':
	    dresponse = 1;
	    name = optstate->value;
	    break;

	  case 'S':
	    ccert = 1;
	    name = optstate->value;
	    break;

	  case 'V':
	    vcert = 1;
	    name = optstate->value;
	    break;

	  case 'a':
	    ascii = PR_TRUE;
	    break;

	  case 'd':
	    db_dir = optstate->value;
	    break;

	  case 'l':
	    responder_url = optstate->value;
	    break;

	  case 'p':
	    prequest = 1;
	    break;

	  case 'r':
	    crequest = 1;
	    name = optstate->value;
	    break;

	  case 's':
	    signer_name = optstate->value;
	    break;

	  case 't':
	    responder_name = optstate->value;
	    break;

	  case 'u':
	    cert_usage_str = optstate->value;
	    break;

	  case 'w':
	    date_str = optstate->value;
	    break;
	}
    }

    PL_DestroyOptState(optstate);

    if ((crequest + dresponse + prequest + presponse + ccert + vcert) != 1) {
	PR_fprintf (PR_STDERR, "%s: must specify exactly one command\n\n",
		    program_name);
	short_usage (program_name);
	return retval;
    }

    if (vcert) {
	if (cert_usage_str == NULL) {
	    PR_fprintf (PR_STDERR, "%s: verification requires cert usage\n\n",
			program_name);
	    short_usage (program_name);
	    return retval;
	}

	rv = cert_usage_from_char (cert_usage_str, &cert_usage);
	if (rv != SECSuccess) {
	    PR_fprintf (PR_STDERR, "%s: invalid cert usage (\"%s\")\n\n",
			program_name, cert_usage_str);
	    long_usage (program_name);
	    return retval;
	}
    }

    if (ccert + vcert) {
	if (responder_url != NULL || responder_name != NULL) {
	    /*
	     * To do a full status check, both the URL and the cert name
	     * of the responder must be specified if either one is.
	     */
	    if (responder_url == NULL || responder_name == NULL) {
		if (responder_url == NULL)
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder location\n\n",
				program_name);
		else
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder name\n\n",
				program_name);
		short_usage (program_name);
		return retval;
	    }
	}

	if (date_str != NULL) {
	    rv = DER_AsciiToTime (&verify_time, (char *) date_str);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error converting time string");
		PR_fprintf (PR_STDERR, "\n");
		long_usage (program_name);
		return retval;
	    }
	} else {
	    verify_time = PR_Now();
	}
    }

    retval = -2;		/* errors change from usage to runtime */

    /*
     * Initialize the NSPR and Security libraries.
     */
    PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    db_dir = SECU_ConfigDirectory (db_dir);
    rv = NSS_Init (db_dir);
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	goto prdone;
    }
    SECU_RegisterDynamicOids();

    if (prequest + presponse) {
	MAKE_FILE_BINARY(stdin);
	data = read_file_into_item (in_file, siBuffer);
	if (data == NULL) {
	    SECU_PrintError (program_name, "problem reading input");
	    goto nssdone;
	}
    }

    if (crequest + dresponse + presponse + ccert + vcert) {
	handle = CERT_GetDefaultCertDB();
	if (handle == NULL) {
	    SECU_PrintError (program_name, "problem getting certdb handle");
	    goto nssdone;
	}

	/*
	 * It would be fine to do the enable for all of these commands,
	 * but this way we check that everything but an overall verify
	 * can be done without it.  That is, that the individual pieces
	 * work on their own.
	 */
	if (vcert) {
	    rv = CERT_EnableOCSPChecking (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error enabling OCSP checking");
		goto nssdone;
	    }
	}

	if ((ccert + vcert) && (responder_name != NULL)) {
	    rv = CERT_SetOCSPDefaultResponder (handle, responder_url,
					       responder_name);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error setting default responder");
		goto nssdone;
	    }

	    rv = CERT_EnableOCSPDefaultResponder (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error enabling default responder");
		goto nssdone;
	    }
	}
    }

#define NOTYET(opt)							\
	{								\
	    PR_fprintf (PR_STDERR, "%s not yet working\n", opt);	\
	    exit (-1);							\
	}

    if (name) {
        cert = find_certificate(handle, name, ascii);
    }

    if (crequest) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = create_request (out_file, handle, cert, add_service_locator,
			     add_acceptable_responses);
    } else if (dresponse) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = dump_response (out_file, handle, cert, responder_url);
    } else if (prequest) {
	rv = print_request (out_file, data);
    } else if (presponse) {
	rv = print_response (out_file, data, handle);
    } else if (ccert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = get_cert_status (out_file, handle, cert, name, verify_time);
    } else if (vcert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = verify_cert (out_file, handle, cert, name, cert_usage, verify_time);
    }

    if (rv != SECSuccess)
	SECU_PrintError (program_name, "error performing requested operation");
    else
	retval = 0;

nssdone:
    if (cert) {
        CERT_DestroyCertificate(cert);
    }

    if (data != NULL) {
	SECITEM_FreeItem (data, PR_TRUE);
    }

    if (handle != NULL) {
 	CERT_DisableOCSPDefaultResponder(handle);        
 	CERT_DisableOCSPChecking (handle);
    }

    if (NSS_Shutdown () != SECSuccess) {
	retval = 1;
    }

prdone:
    PR_Cleanup ();
    return retval;
}
//----------------------------------------------------------------------------------------
static void GetCurrentProcessDirectory(nsFileSpec& aFileSpec)
//----------------------------------------------------------------------------------------
{
#if defined (XP_WIN)
    char buf[MAX_PATH];
    if ( ::GetModuleFileName(0, buf, sizeof(buf)) ) {
        // chop of the executable name by finding the rightmost backslash
        char* lastSlash = PL_strrchr(buf, '\\');
        if (lastSlash)
            *(lastSlash + 1) = '\0';

        aFileSpec = buf;
        return;
    }

#elif defined(XP_OS2)
    PPIB ppib;
    PTIB ptib;
    char buffer[CCHMAXPATH];
    DosGetInfoBlocks( &ptib, &ppib);
    DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer);
    *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery
    aFileSpec = buffer;
    return;

#elif defined(XP_UNIX)

    // In the absence of a good way to get the executable directory let
    // us try this for unix:
    //	- if MOZILLA_FIVE_HOME is defined, that is it
    //	- else give the current directory
    char buf[MAXPATHLEN];
    char *moz5 = PR_GetEnv("MOZILLA_FIVE_HOME");
    if (moz5)
    {
        aFileSpec = moz5;
        return;
    }
    else
    {
#if defined(DEBUG)
        static PRBool firstWarning = PR_TRUE;

        if(firstWarning) {
            // Warn that MOZILLA_FIVE_HOME not set, once.
            printf("Warning: MOZILLA_FIVE_HOME not set.\n");
            firstWarning = PR_FALSE;
        }
#endif /* DEBUG */

        // Fall back to current directory.
        if (getcwd(buf, sizeof(buf)))
        {
            aFileSpec = buf;
            return;
        }
    }

#elif defined(XP_BEOS)

    char *moz5 = getenv("MOZILLA_FIVE_HOME");
    if (moz5)
    {
        aFileSpec = moz5;
        return;
    }
    else
    {
      static char buf[MAXPATHLEN];
      int32 cookie = 0;
      image_info info;
      char *p;
      *buf = 0;
      if(get_next_image_info(0, &cookie, &info) == B_OK)
      {
        strcpy(buf, info.name);
        if((p = strrchr(buf, '/')) != 0)
        {
          *p = 0;
          aFileSpec = buf;
          return;
        }
      }
    }

#endif

    NS_ERROR("unable to get current process directory");
} // GetCurrentProcessDirectory()
Esempio n. 9
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);
        }
    }
}
Esempio n. 10
0
//----------------------------------------------------------------------------------------
nsresult
nsDirectoryService::GetCurrentProcessDirectory(nsILocalFile** aFile)
//----------------------------------------------------------------------------------------
{
    NS_ENSURE_ARG_POINTER(aFile);
    *aFile = nsnull;

   //  Set the component registry location:
    if (!mService)
        return NS_ERROR_FAILURE;

    nsresult rv;

    nsCOMPtr<nsIProperties> dirService;
    rv = nsDirectoryService::Create(nsnull,
                                    NS_GET_IID(nsIProperties),
                                    getter_AddRefs(dirService));  // needs to be around for life of product

    if (dirService)
    {
      nsCOMPtr <nsILocalFile> aLocalFile;
      dirService->Get(NS_XPCOM_INIT_CURRENT_PROCESS_DIR, NS_GET_IID(nsILocalFile), getter_AddRefs(aLocalFile));
      if (aLocalFile)
      {
        *aFile = aLocalFile;
        NS_ADDREF(*aFile);
        return NS_OK;
      }
    }

    nsLocalFile* localFile = new nsLocalFile;

    if (localFile == nsnull)
        return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(localFile);



#ifdef XP_WIN
    char buf[MAX_PATH];
    if ( ::GetModuleFileName(0, buf, sizeof(buf)) ) {
        // chop of the executable name by finding the rightmost backslash
        char* lastSlash = PL_strrchr(buf, '\\');
        if (lastSlash)
            *(lastSlash + 1) = '\0';

        localFile->InitWithNativePath(nsDependentCString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(XP_MAC)
    // get info for the the current process to determine the directory
    // its located in
    OSErr err;
    ProcessSerialNumber psn = {kNoProcess, kCurrentProcess};
    ProcessInfoRec pInfo;
    FSSpec         tempSpec;

    // initialize ProcessInfoRec before calling
    // GetProcessInformation() or die horribly.
    pInfo.processName = nil;
    pInfo.processAppSpec = &tempSpec;
    pInfo.processInfoLength = sizeof(ProcessInfoRec);

    err = GetProcessInformation(&psn, &pInfo);
    if (!err)
    {
        // create an FSSpec from the volume and dirid of the app.
        FSSpec appFSSpec;
        ::FSMakeFSSpec(pInfo.processAppSpec->vRefNum, pInfo.processAppSpec->parID, 0, &appFSSpec);

        nsCOMPtr<nsILocalFileMac> localFileMac = do_QueryInterface((nsIFile*)localFile);
        if (localFileMac)
        {
            localFileMac->InitWithFSSpec(&appFSSpec);
            *aFile = localFile;
            return NS_OK;
        }
    }
#elif defined(XP_MACOSX)
# ifdef MOZ_DEFAULT_VBOX_XPCOM_HOME
    rv = localFile->InitWithNativePath(nsDependentCString(MOZ_DEFAULT_VBOX_XPCOM_HOME));
    if (NS_SUCCEEDED(rv))
        *aFile = localFile;
# else
    // Works even if we're not bundled.
    CFBundleRef appBundle = CFBundleGetMainBundle();
    if (appBundle != nsnull)
    {
        CFURLRef bundleURL = CFBundleCopyExecutableURL(appBundle);
        if (bundleURL != nsnull)
        {
            CFURLRef parentURL = CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorDefault, bundleURL);
            if (parentURL)
            {
                // Pass PR_TRUE for the "resolveAgainstBase" arg to CFURLGetFileSystemRepresentation.
                // This will resolve the relative portion of the CFURL against it base, giving a full
                // path, which CFURLCopyFileSystemPath doesn't do.
                char buffer[PATH_MAX];
                if (CFURLGetFileSystemRepresentation(parentURL, PR_TRUE, (UInt8 *)buffer, sizeof(buffer)))
                {
#ifdef DEBUG_conrad
                    printf("nsDirectoryService - CurrentProcessDir is: %s\n", buffer);
#endif
                    rv = localFile->InitWithNativePath(nsDependentCString(buffer));
                    if (NS_SUCCEEDED(rv))
                        *aFile = localFile;
                }
                CFRelease(parentURL);
            }
            CFRelease(bundleURL);
        }
    }
#endif

    NS_ASSERTION(*aFile, "nsDirectoryService - Could not determine CurrentProcessDir.\n");
    if (*aFile)
        return NS_OK;

#elif defined(XP_UNIX)

    // In the absence of a good way to get the executable directory let
    // us try this for unix:
    //	- if VBOX_XPCOM_HOME is defined, that is it
    //	- else give the current directory
    char buf[MAXPATHLEN];

#if 0 /* we need .so location. */
    // Actually we have a way on linux.
    static volatile bool fPathSet = false;
    static char szPath[MAXPATHLEN];
    if (!fPathSet)
    {
        char buf2[MAXPATHLEN + 3];
        buf2[0] = '\0';

        /*
         * Env.var. VBOX_XPCOM_HOME first.
         */
        char *psz = PR_GetEnv("VBOX_XPCOM_HOME");
        if (psz)
        {
            if (strlen(psz) < MAXPATHLEN)
            {
                if (!realpath(psz, buf2))
                    strcpy(buf2, psz);
                strcat(buf2, "/x"); /* for the filename stripping */
            }
        }

        /*
         * The dynamic loader.
         */
        if (!buf2[0])
        {
            Dl_info DlInfo = {0};
            if (    !dladdr((void *)nsDirectoryService::mService, &DlInfo)
                &&  DlInfo.dli_fname)
            {
                if (!realpath(DlInfo.dli_fname, buf2))
                    buf2[0] = '\0';
            }
        }

        /*
         * Executable location.
         */
        if (!buf2[0])
        {
            char buf[MAXPATHLEN];
            int cchLink = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
            if (cchLink > 0 || cchLink != sizeof(buf) - 1)
             {
                buf[cchLink] = '\0';
                if (!realpath(buf, buf2))
                    buf2[0] = '\0';
            }
        }

        /*
         * Copy to static buffer on success.
         */
        if (buf2[0])
        {
            char *p = strrchr(buf2, '/');
            if (p)
            {
                p[p == buf2] = '\0';
            #ifdef DEBUG
                printf("debug: (1) VBOX_XPCOM_HOME=%s\n", buf2);
            #endif
                strcpy(szPath, buf2);
                fPathSet = true;
            }
        }
    }
    if (fPathSet)
    {
        localFile->InitWithNativePath(nsDependentCString(szPath));
        *aFile = localFile;
        return NS_OK;
    }

#endif


    // The MOZ_DEFAULT_VBOX_XPCOM_HOME variable can be set at configure time with
    // a --with-default-mozilla-five-home=foo autoconf flag.
    //
    // The idea here is to allow for builds that have a default VBOX_XPCOM_HOME
    // regardless of the environment.  This makes it easier to write apps that
    // embed mozilla without having to worry about setting up the environment
    //
    // We do this py putenv()ing the default value into the environment.  Note that
    // we only do this if it is not already set.
#ifdef MOZ_DEFAULT_VBOX_XPCOM_HOME
    if (PR_GetEnv("VBOX_XPCOM_HOME") == nsnull)
    {
        putenv("VBOX_XPCOM_HOME=" MOZ_DEFAULT_VBOX_XPCOM_HOME);
    }
#endif

    char *moz5 = PR_GetEnv("VBOX_XPCOM_HOME");

    if (moz5)
    {
        if (realpath(moz5, buf)) {
            localFile->InitWithNativePath(nsDependentCString(buf));
            *aFile = localFile;
            return NS_OK;
        }
    }
#if defined(DEBUG)
    static PRBool firstWarning = PR_TRUE;

    if(!moz5 && firstWarning) {
        // Warn that VBOX_XPCOM_HOME not set, once.
        printf("Warning: VBOX_XPCOM_HOME not set.\n");
        firstWarning = PR_FALSE;
    }
#endif /* DEBUG */

    // Fall back to current directory.
    if (getcwd(buf, sizeof(buf)))
    {
        localFile->InitWithNativePath(nsDependentCString(buf));
        *aFile = localFile;
        return NS_OK;
    }

#elif defined(XP_OS2)
    PPIB ppib;
    PTIB ptib;
    char buffer[CCHMAXPATH];
    DosGetInfoBlocks( &ptib, &ppib);
    DosQueryModuleName( ppib->pib_hmte, CCHMAXPATH, buffer);
    *strrchr( buffer, '\\') = '\0'; // XXX DBCS misery
    localFile->InitWithNativePath(nsDependentCString(buffer));
    *aFile = localFile;
    return NS_OK;

#elif defined(XP_BEOS)

    char *moz5 = getenv("VBOX_XPCOM_HOME");
    if (moz5)
    {
        localFile->InitWithNativePath(nsDependentCString(moz5));
        localFile->Normalize();
        *aFile = localFile;
        return NS_OK;
    }
    else
    {
      static char buf[MAXPATHLEN];
      int32 cookie = 0;
      image_info info;
      char *p;
      *buf = 0;
      if(get_next_image_info(0, &cookie, &info) == B_OK)
      {
        strcpy(buf, info.name);
        if((p = strrchr(buf, '/')) != 0)
        {
          *p = 0;
          localFile->InitWithNativePath(nsDependentCString(buf));
          *aFile = localFile;
          return NS_OK;
        }
      }
    }

#endif

    NS_RELEASE(localFile);

    NS_ERROR("unable to get current process directory");
    return NS_ERROR_FAILURE;
} // GetCurrentProcessDirectory()
Esempio n. 11
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    char	*program_name;
    char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    char  *output_file = NULL;	/* write new encrypted data here */
    char  *log_file = NULL;	/* write new encrypted data here */
    FILE	*inFile = stdin;
    FILE	*outFile = stdout;
    FILE	*logFile = NULL;
    PLOptStatus optstatus;
    SECItem	result;
    int		c;
    secuPWData  pwdata = { PW_NONE, NULL };

    result.data = 0;

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
    if (optstate == NULL) {
        SECU_PrintError (program_name, "PL_CreateOptState failed");
        return 1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
        switch (optstate->option) {
        case '?':
            short_usage (program_name);
            return 1;

        case 'H':
            long_usage (program_name);
            return 1;

        case 'd':
            SECU_ConfigDirectory(optstate->value);
            break;

        case 'i':
            input_file = PL_strdup(optstate->value);
            break;

        case 'o':
            output_file = PL_strdup(optstate->value);
            break;

        case 'l':
            log_file = PL_strdup(optstate->value);
            break;

        case 'f':
            pwdata.source = PW_FROMFILE;
            pwdata.data = PL_strdup(optstate->value);
            break;

        case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PL_strdup(optstate->value);
            break;

        }
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
        short_usage (program_name);
        return 1;
    }

    if (input_file) {
        inFile = fopen(input_file,"r");
        if (inFile == NULL) {
            perror(input_file);
            return 1;
        }
        PR_Free(input_file);
    }
    if (output_file) {
        outFile = fopen(output_file,"w+");
        if (outFile == NULL) {
            perror(output_file);
            return 1;
        }
        PR_Free(output_file);
    }
    if (log_file) {
        logFile = fopen(log_file,"w+");
        if (logFile == NULL) {
            perror(log_file);
            return 1;
        }
        PR_Free(log_file);
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
        SECU_PrintError (program_name, "NSS_Init failed");
        retval = 1;
        goto prdone;
    }

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */

    while ((c = getc(inFile)) != EOF) {
        if (c == 'M') {
            char *dataString = NULL;
            SECItem *inText;

            rv = getData(inFile, &dataString);
            if (!rv) {
                fputs(dataString,outFile);
                free(dataString);
                continue;
            }
            inText = NSSBase64_DecodeBuffer(NULL, NULL, dataString,
                                            strlen(dataString));
            if ((inText == NULL) || (inText->len == 0)) {
                if (logFile) {
                    fprintf(logFile,"Base 64 decode failed on <%s>\n",
                            dataString);
                    fprintf(logFile," Error %x: %s\n",PORT_GetError(),
                            SECU_Strerror(PORT_GetError()));
                }
                fputs(dataString,outFile);
                free(dataString);
                continue;
            }
            result.data = NULL;
            result.len  = 0;
            rv = PK11SDR_Decrypt(inText, &result, &pwdata);
            SECITEM_FreeItem(inText, PR_TRUE);
            if (rv != SECSuccess) {
                if (logFile) {
                    fprintf(logFile,"SDR decrypt failed on <%s>\n",
                            dataString);
                    fprintf(logFile," Error %x: %s\n",PORT_GetError(),
                            SECU_Strerror(PORT_GetError()));
                }
                fputs(dataString,outFile);
                free(dataString);
                SECITEM_ZfreeItem(&result, PR_FALSE);
                continue;
            }
            /* result buffer has no extra space for a NULL */
            fprintf(outFile, "%.*s", result.len, result.data);
            SECITEM_ZfreeItem(&result, PR_FALSE);
        } else {
            putc(c,outFile);
        }
    }

    fclose(outFile);
    fclose(inFile);
    if (logFile) {
        fclose(logFile);
    }

    if (NSS_Shutdown() != SECSuccess) {
        SECU_PrintError (program_name, "NSS_Shutdown failed");
        exit(1);
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Esempio n. 12
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    char	*program_name;
    char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    char  *output_file = NULL;	/* write new encrypted data here */
    char  *log_file = NULL;	/* write new encrypted data here */
    FILE	*inFile = stdin;
    FILE	*outFile = stdout;
    FILE	*logFile = NULL;
    PLOptStatus optstatus;
    secuPWData  pwdata = { PW_NONE, NULL };


    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return 1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return 1;

	  case 'H':
	    long_usage (program_name);
	    return 1;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

          case 'i':
            input_file = PL_strdup(optstate->value);
            break;

          case 'o':
            output_file = PL_strdup(optstate->value);
            break;

          case 'l':
            log_file = PL_strdup(optstate->value);
            break;

          case 'f':
            pwdata.source = PW_FROMFILE;
            pwdata.data = PL_strdup(optstate->value);
            break;

          case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PL_strdup(optstate->value);
            break;

	}
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
	short_usage (program_name);
	return 1;
    }

    if (input_file) {
        inFile = fopen(input_file,"r");
        if (inFile == NULL) {
	    perror(input_file);
	    return 1;
        }
        PR_Free(input_file);
    }
    if (output_file) {
        outFile = fopen(output_file,"w+");
        if (outFile == NULL) {
	    perror(output_file);
	    return 1;
        }
        PR_Free(output_file);
    }
    if (log_file) {
	if (log_file[0] == '-')
	    logFile = stderr;
	else
	    logFile = fopen(log_file,"w+");
	if (logFile == NULL) {
	    perror(log_file);
	    return 1;
	}
        PR_Free(log_file);
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	retval = 1;
	goto prdone;
    }

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */
    while (fgets(dataString, sizeof dataString, inFile)) {
	unsigned char c = dataString[0];

	if (c == 'M' && isBase64(dataString)) {
	    doDecrypt(dataString, outFile, logFile, &pwdata);
        } else if (c == '~' && isBase64(dataString + 1)) {
	    doDecode(dataString, outFile, logFile);
	} else {
	    fputs(dataString, outFile);
	}
    }
    if (pwdata.data)
    	PR_Free(pwdata.data);

    fclose(outFile);
    fclose(inFile);
    if (logFile && logFile != stderr) {
	fclose(logFile);
    }

    if (NSS_Shutdown() != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Shutdown failed");
        exit(1);
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Esempio n. 13
0
/*
 *  m a n i f e s t o _ f n
 *
 *  Called by pointer from manifesto(), once for
 *  each file within the directory.
 *
 */
static int	manifesto_fn 
(char *relpath, char *basedir, char *reldir, char *filename, void *arg)
{
    int	use_js;

    JAR_Digest dig;
    char	fullname [FNSIZE];

    if (verbosity >= 0) {
	PR_fprintf(outputFD, "--> %s\n", relpath);
    }

    /* extension matching */
    if (extensionsGiven) {
	char	*ext = PL_strrchr(relpath, '.');
	if (!ext) 
	    return 0;
	if (!PL_HashTableLookup(extensions, ext)) 
	    return 0;
    }

    sprintf (fullname, "%s/%s", basedir, relpath);

    fprintf (mf, "\n");

    use_js = 0;

    if (scriptdir && !PORT_Strcmp (scriptdir, reldir))
	use_js++;

    /* sign non-.js files inside .arc directories using the javascript magic */

    if ( (PL_strcaserstr(filename, ".js") != filename + strlen(filename) - 3)
         && (PL_strcaserstr(reldir, ".arc") == reldir + strlen(filename) - 4))
	use_js++;

    if (use_js) {
	fprintf (mf, "Name: %s\n", filename);
	fprintf (mf, "Magic: javascript\n");

	if (optimize == 0)
	    fprintf (mf, "javascript.id: %s\n", filename);

	if (metafile)
	    add_meta (mf, filename);
    } else {
	fprintf (mf, "Name: %s\n", relpath);
	if (metafile)
	    add_meta (mf, relpath);
    }

    JAR_digest_file (fullname, &dig);


    if (optimize == 0) {
	fprintf (mf, "Digest-Algorithms: MD5 SHA1\n");
	fprintf (mf, "MD5-Digest: %s\n", BTOA_DataToAscii (dig.md5,
	     MD5_LENGTH));
    }

    fprintf (mf, "SHA1-Digest: %s\n", BTOA_DataToAscii (dig.sha1, SHA1_LENGTH));

    if (!use_js) {
	JzipAdd(fullname, relpath, zipfile, compression_level);
    }

    return 0;
}
Esempio n. 14
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    PLOptStatus  optstatus;
    char	*program_name;
    const char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    const char  *output_file = NULL;	/* write new encrypted data here */
    const char  *value = default_value;	/* Use this for plaintext */
    SECItem     data;
    SECItem     result = {0, 0, 0};
    SECItem     text;
    PRBool      ascii = PR_FALSE;
    secuPWData  pwdata = { PW_NONE, 0 };

    pr_stderr = PR_STDERR;
    result.data = 0;
    text.data = 0; text.len = 0;

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "?Had:i:o:t:vf:p:");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return -1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return retval;

	  case 'H':
	    long_usage (program_name);
	    return retval;

	  case 'a':
	    ascii = PR_TRUE;
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

          case 'i':
            input_file = optstate->value;
            break;

          case 'o':
            output_file = optstate->value;
            break;

          case 't':
            value = optstate->value;
            break;

	  case 'f':
	    if (pwdata.data) {
		PORT_Free(pwdata.data);
		short_usage(program_name);
		return -1;
	    }
	    pwdata.source = PW_FROMFILE;
	    pwdata.data = PORT_Strdup(optstate->value);
	    break;

	  case 'p':
	    if (pwdata.data) {
		PORT_Free(pwdata.data);
		short_usage(program_name);
		return -1;
	    }
	    pwdata.source = PW_PLAINTEXT;
	    pwdata.data = PORT_Strdup(optstate->value);
	    break;

          case 'v':
            verbose = PR_TRUE;
            break;
	}
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
	short_usage (program_name);
	return -1;
    }
    if (!output_file && !input_file && value == default_value) {
	short_usage (program_name);
	PR_fprintf (pr_stderr, "Must specify at least one of -t, -i or -o \n");
	return -1;
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);

    if (output_file) {
	rv = NSS_InitReadWrite(SECU_ConfigDirectory(NULL));
    } else {
	rv = NSS_Init(SECU_ConfigDirectory(NULL));
    }
    if (rv != SECSuccess) {
	SECU_PrintError(program_name, "NSS_Init failed");
	retval = -1;
	goto prdone;
    }

    /* Convert value into an item */
    data.data = (unsigned char *)value;
    data.len = strlen(value);

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */
    if (input_file)
    {
      if (verbose) printf("Reading data from %s\n", input_file);

      if (!strcmp(input_file, "-")) {
	retval = readStdin(&result);
        ascii = PR_TRUE;
      } else {
        retval = readInputFile(input_file, &result);
      }
      if (retval != 0) 
	goto loser;
      if (ascii) {
	/* input was base64 encoded.  Decode it. */
	SECItem newResult = {0, 0, 0};
	SECItem *ok = NSSBase64_DecodeBuffer(NULL, &newResult, 
	                       (const char *)result.data, result.len);
	if (!ok) {
	  SECU_PrintError(program_name, "Base 64 decode failed");
	  retval = -1;
	  goto loser;
	}
	SECITEM_ZfreeItem(&result, PR_FALSE);
	result = *ok;
      }
    }
    else
    {
      SECItem keyid = { 0, 0, 0 };
      SECItem outBuf = { 0, 0, 0 };
      PK11SlotInfo *slot = NULL;

      /* sigh, initialize the key database */
      slot = PK11_GetInternalKeySlot();
      if (slot && PK11_NeedUserInit(slot)) {
	switch (pwdata.source) {
	case PW_FROMFILE:
	    rv = SECU_ChangePW(slot, 0, pwdata.data);
	    break;
	case PW_PLAINTEXT:
	    rv = SECU_ChangePW(slot, pwdata.data, 0);
	    break;
	default:
            rv = SECU_ChangePW(slot, "", 0);
	    break;
	}
        if (rv != SECSuccess) {
            SECU_PrintError(program_name, "Failed to initialize slot \"%s\"",
                                    PK11_GetSlotName(slot));
            return SECFailure;
        }
      }
      if (slot) {
	PK11_FreeSlot(slot);
      }

      rv = PK11SDR_Encrypt(&keyid, &data, &result, &pwdata);
      if (rv != SECSuccess) {
        if (verbose) 
	  SECU_PrintError(program_name, "Encrypt operation failed\n");
        retval = -1;
        goto loser;
      }

      if (verbose) printf("Encrypted result is %d bytes long\n", result.len);

      if (!strcmp(output_file, "-")) {
        ascii = PR_TRUE;
      }

      if (ascii) {
      	/* base64 encode output. */
	char * newResult = NSSBase64_EncodeItem(NULL, NULL, 0, &result);
	if (!newResult) {
	  SECU_PrintError(program_name, "Base 64 encode failed\n");
	  retval = -1;
	  goto loser;
	}
	outBuf.data = (unsigned char *)newResult;
	outBuf.len  = strlen(newResult);
	if (verbose) 
	  printf("Base 64 encoded result is %d bytes long\n", outBuf.len);
      } else {
	outBuf = result;
      }

      /* -v printf("Result is %.*s\n", text.len, text.data); */
      if (output_file) {
         PRFileDesc *file;
         PRInt32 count;

         if (verbose) printf("Writing result to %s\n", output_file);
	 if (!strcmp(output_file, "-")) {
	   file = PR_STDOUT;
	 } else {
	   /* Write to file */
	   file = PR_Open(output_file, PR_CREATE_FILE|PR_WRONLY, 0666);
	 }
         if (!file) {
            if (verbose) 
		SECU_PrintError(program_name, 
                                "Open of output file %s failed\n",
                                output_file);
            retval = -1;
            goto loser;
         }

         count = PR_Write(file, outBuf.data, outBuf.len);

	 if (file == PR_STDOUT) {
	   puts("");
	 } else {
	   PR_Close(file);
	 }

         if (count != outBuf.len) {
           if (verbose) SECU_PrintError(program_name, "Write failed\n");
           retval = -1;
           goto loser;
         }
	 if (ascii) {
	   free(outBuf.data);
	 }
      }
    }

    /* Decrypt the value */
    rv = PK11SDR_Decrypt(&result, &text, &pwdata);
    if (rv != SECSuccess) {
      if (verbose) SECU_PrintError(program_name, "Decrypt operation failed\n");
      retval = -1; 
      goto loser;
    }

    if (verbose) printf("Decrypted result is \"%.*s\"\n", text.len, text.data);

    /* Compare to required value */
    if (text.len != data.len || memcmp(data.data, text.data, text.len) != 0)
    {
      if (verbose) PR_fprintf(pr_stderr, "Comparison failed\n");
      retval = -1;
      goto loser;
    }

loser:
    if (text.data) SECITEM_ZfreeItem(&text, PR_FALSE);
    if (result.data) SECITEM_ZfreeItem(&result, PR_FALSE);
    if (NSS_Shutdown() != SECSuccess) {
       exit(1);
    }

prdone:
    PR_Cleanup ();
    if (pwdata.data) {
	PORT_Free(pwdata.data);
    }
    return retval;
}