Exemple #1
0
/*
** Perform a three way test against PR_smprintf, PR_snprintf, and sprintf.
** Make sure the results are identical
*/
static void test_s(char *pattern, char *ss)
{
    char *s;
    unsigned char before[8];
    char buf[200];
    unsigned char after[8];
    int n;

    memset(before, 0xBB, 8);
    memset(after, 0xAA, 8);

    /* try all three routines */
    s = PR_smprintf(pattern, ss);
    PR_ASSERT(s != 0);
    n = PR_snprintf(buf, sizeof(buf), pattern, ss);
    PR_ASSERT(n <= sizeof(buf));
    sprintf(sbuf, pattern, ss);

    for (n = 0; n < 8; n++) {
	PR_ASSERT(before[n] == 0xBB);
	PR_ASSERT(after[n] == 0xAA);
    }

    /* compare results */
    if ((strncmp(s, buf, sizeof(buf)) != 0) ||
	(strncmp(s, sbuf, sizeof(sbuf)) != 0)) {
	fprintf(stderr,
	   "pattern='%s' ss=%.20s\nPR_smprintf='%s'\nPR_snprintf='%s'\n    sprintf='%s'\n",
	   pattern, ss, s, buf, sbuf);
	printf("FAIL\n");
	PR_smprintf_free(s);
	exit(-1);
    }
	PR_smprintf_free(s);
}
Exemple #2
0
/*************************************************************************
 *
 * F i p s M o d e
 * If arg=="true", enable FIPS mode on the internal module.  If arg=="false",
 * disable FIPS mode on the internal module.
 */
Error
FipsMode(char *arg)
{
    char *internal_name;

    if (!PORT_Strcasecmp(arg, "true")) {
        if (!PK11_IsFIPS()) {
            internal_name = PR_smprintf("%s",
                                        SECMOD_GetInternalModule()->commonName);
            if (SECMOD_DeleteInternalModule(internal_name) != SECSuccess) {
                PR_fprintf(PR_STDERR, "%s\n", SECU_Strerror(PORT_GetError()));
                PR_smprintf_free(internal_name);
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_smprintf_free(internal_name);
            if (!PK11_IsFIPS()) {
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_fprintf(PR_STDOUT, msgStrings[FIPS_ENABLED_MSG]);
        } else {
            PR_fprintf(PR_STDERR, errStrings[FIPS_ALREADY_ON_ERR]);
            return FIPS_ALREADY_ON_ERR;
        }
    } else if (!PORT_Strcasecmp(arg, "false")) {
        if (PK11_IsFIPS()) {
            internal_name = PR_smprintf("%s",
                                        SECMOD_GetInternalModule()->commonName);
            if (SECMOD_DeleteInternalModule(internal_name) != SECSuccess) {
                PR_fprintf(PR_STDERR, "%s\n", SECU_Strerror(PORT_GetError()));
                PR_smprintf_free(internal_name);
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_smprintf_free(internal_name);
            if (PK11_IsFIPS()) {
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_fprintf(PR_STDOUT, msgStrings[FIPS_DISABLED_MSG]);
        } else {
            PR_fprintf(PR_STDERR, errStrings[FIPS_ALREADY_OFF_ERR]);
            return FIPS_ALREADY_OFF_ERR;
        }
    } else {
        PR_fprintf(PR_STDERR, errStrings[INVALID_FIPS_ARG]);
        return INVALID_FIPS_ARG;
    }

    return SUCCESS;
}
void sbDeviceXMLInfo::LogIfFailed(nsresult aRV, const char * aPrintf, ...)
{
  // Do nothing if no failure
  if (NS_SUCCEEDED(aRV)) {
    return;
  }

  // Check logging pref:
  if (!mLogDeviceInfo) {
    return;
  }

  // Resolve the args to a string
  va_list etc;
  va_start(etc, aPrintf);
  char *why =
    PR_vsmprintf(aPrintf ? aPrintf : "while loading device info", etc);
  va_end(etc);

  // Compose the error message
  nsString msg(NS_LITERAL_STRING("sbDeviceXMLInfo "));
  msg.AppendLiteral(
    sbDeviceUtils::GetDeviceIdentifier(mDevice).BeginReading());
  msg.AppendLiteral(":\nERROR [0x");
  msg.AppendInt(aRV, 16);
  msg.AppendLiteral("]\n");
  msg.Append(NS_ConvertUTF8toUTF16(why));
  PR_smprintf_free(why);

  // Log the error message
  sbErrorConsole::Error("sbDeviceXMLInfo", msg);
}
Exemple #4
0
static void
nssutil_freePair(char *pair)
{
    if (pair && pair != nssutil_nullString) {
        PR_smprintf_free(pair);
    }
}
NS_IMETHODIMP
nsNSSCertificate::GetValidEVPolicyOid(nsACString &outDottedOid)
{
  nsNSSShutDownPreventionLock locker;
  if (isAlreadyShutDown())
    return NS_ERROR_NOT_AVAILABLE;

  SECOidTag oid_tag;
  PRBool valid;
  nsresult rv = getValidEVOidTag(oid_tag, valid);
  if (NS_FAILED(rv))
    return rv;

  if (valid) {
    SECOidData *oid_data = SECOID_FindOIDByTag(oid_tag);
    if (!oid_data)
      return NS_ERROR_FAILURE;

    char *oid_str = CERT_GetOidString(&oid_data->oid);
    if (!oid_str)
      return NS_ERROR_FAILURE;

    outDottedOid = oid_str;
    PR_smprintf_free(oid_str);
  }
  return NS_OK;
}
Exemple #6
0
/* This function does NOT expect a DER type and length. */
SECOidTag
SECU_PrintObjectID(FILE *out, SECItem *oid, char *m, int level)
{
    SECOidData *oiddata;
    char *oidString = NULL;
    
    oiddata = SECOID_FindOID(oid);
    if (oiddata != NULL) {
	    const char *name = oiddata->desc;
	    SECU_Indent(out, level);
	    if (m != NULL)
	        fprintf(out, "%s: ", m);
	    fprintf(out, "%s\n", name);
	    return oiddata->offset;
    } 
    oidString = CERT_GetOidString(oid);
    if (oidString) {
	    SECU_Indent(out, level);
	    if (m != NULL)
	        fprintf(out, "%s: ", m);
	    fprintf(out, "%s\n", oidString);
	    PR_smprintf_free(oidString);
	    return SEC_OID_UNKNOWN;
    }
    SECU_PrintAsHex(out, oid, m, level);
    return SEC_OID_UNKNOWN;
}
Exemple #7
0
  void Print(const char* aName, LogLevel aLevel, const char* aFmt, va_list aArgs)
  {
    const size_t kBuffSize = 1024;
    char buff[kBuffSize];

    char* buffToWrite = buff;

    // For backwards compat we need to use the NSPR format string versions
    // of sprintf and friends and then hand off to printf.
    va_list argsCopy;
    va_copy(argsCopy, aArgs);
    size_t charsWritten = PR_vsnprintf(buff, kBuffSize, aFmt, argsCopy);
    va_end(argsCopy);

    if (charsWritten == kBuffSize - 1) {
      // We may have maxed out, allocate a buffer instead.
      buffToWrite = PR_vsmprintf(aFmt, aArgs);
      charsWritten = strlen(buffToWrite);
    }

    // Determine if a newline needs to be appended to the message.
    const char* newline = "";
    if (charsWritten == 0 || buffToWrite[charsWritten - 1] != '\n') {
      newline = "\n";
    }

    FILE* out = mOutFile ? mOutFile : stderr;

    // This differs from the NSPR format in that we do not output the
    // opaque system specific thread pointer (ie pthread_t) cast
    // to a long. The address of the current PR_Thread continues to be
    // prefixed.
    //
    // Additionally we prefix the output with the abbreviated log level
    // and the module name.
    if (!mAddTimestamp) {
      fprintf_stderr(out,
                     "[%p]: %s/%s %s%s",
                     PR_GetCurrentThread(), ToLogStr(aLevel),
                     aName, buffToWrite, newline);
    } else {
      PRExplodedTime now;
      PR_ExplodeTime(PR_Now(), PR_GMTParameters, &now);
      fprintf_stderr(
          out,
          "%04d-%02d-%02d %02d:%02d:%02d.%06d UTC - [%p]: %s/%s %s%s",
          now.tm_year, now.tm_month + 1, now.tm_mday,
          now.tm_hour, now.tm_min, now.tm_sec, now.tm_usec,
          PR_GetCurrentThread(), ToLogStr(aLevel),
          aName, buffToWrite, newline);
    }

    if (mIsSync) {
      fflush(out);
    }

    if (buffToWrite != buff) {
      PR_smprintf_free(buffToWrite);
    }
  }
Exemple #8
0
static void
error(Pk11Install_Error errcode, ...)
#endif
{

    va_list ap;
    char *errstr;
    Pk11Install_ErrorHandler handler;

    if (!errorHandlerLock) {
        errorHandlerLock = PR_NewLock();
    }

    PR_Lock(errorHandlerLock);

    handler = errorHandler;

    PR_Unlock(errorHandlerLock);

    if (handler) {
#ifdef OSF1
        va_start(ap);
        errstr = PR_vsmprintf(errorString[va_arg(ap, Pk11Install_Error)], ap);
#else
        va_start(ap, errcode);
        errstr = PR_vsmprintf(errorString[errcode], ap);
#endif
        handler(errstr);
        PR_smprintf_free(errstr);
        va_end(ap);
    }
}
Exemple #9
0
/**
 * Output a string to the user.  This method is really only meant to be used to
 * output last-ditch error messages designed for developers NOT END USERS.
 *
 * @param isError
 *        Pass true to indicate severe errors.
 * @param fmt
 *        printf-style format string followed by arguments.
 */
static void Output(PRBool isError, const char *fmt, ... )
{
  va_list ap;
  va_start(ap, fmt);

#if (defined(XP_WIN) && !MOZ_WINCONSOLE) || defined(WINCE)
  char *msg = PR_vsmprintf(fmt, ap);
  if (msg)
  {
    UINT flags = MB_OK;
    if (isError)
      flags |= MB_ICONERROR;
    else
      flags |= MB_ICONINFORMATION;
    
    wchar_t wide_msg[2048];
    MultiByteToWideChar(CP_ACP,
			0,
			msg,
			-1,
			wide_msg,
			sizeof(wide_msg) / sizeof(wchar_t));
    
    MessageBoxW(NULL, wide_msg, L"XULRunner", flags);

    PR_smprintf_free(msg);
  }
#else
  vfprintf(stderr, fmt, ap);
#endif

  va_end(ap);
}
Exemple #10
0
/*
 * this is a legacy configuration function which used to be part of
 * the PKCS #11 internal token.
 */
void
PK11_ConfigurePKCS11(const char *man, const char *libdesc, const char *tokdesc,
	const char *ptokdesc, const char *slotdesc, const char *pslotdesc, 
	const char *fslotdesc, const char *fpslotdesc, int minPwd, 
	int pwRequired)
{
    char * strings;

    strings = nss_MkConfigString(man,libdesc,tokdesc,ptokdesc,slotdesc,
	pslotdesc,fslotdesc,fpslotdesc,minPwd);
    if (strings == NULL) {
	return;
    }

    if (libdesc) {
	if (pk11_config_name != NULL) {
	    PORT_Free(pk11_config_name);
	}
	pk11_config_name = PORT_Strdup(libdesc);
    }

    if (pk11_config_strings != NULL) {
	PR_smprintf_free(pk11_config_strings);
    }
    pk11_config_strings = strings;
    pk11_password_required = pwRequired;

    return;
}
/*
 * FUNCTION: pkix_pl_OID_ToString
 * (see comments for PKIX_PL_ToStringCallback in pkix_pl_system.h)
 * Use this function only for printing OIDs and not to make any
 * critical security decision.
 */
static PKIX_Error *
pkix_pl_OID_ToString(
        PKIX_PL_Object *object,
        PKIX_PL_String **pString,
        void *plContext)
{
        PKIX_PL_OID *oid = NULL;
        char *oidString = NULL;

        PKIX_ENTER(OID, "pkix_pl_OID_toString");
        PKIX_NULLCHECK_TWO(object, pString);

        PKIX_CHECK(pkix_CheckType(object, PKIX_OID_TYPE, plContext),
                    PKIX_OBJECTNOTANOID);
        oid = (PKIX_PL_OID*)object;
        oidString = CERT_GetOidString(&oid->derOid);
        
        PKIX_CHECK(PKIX_PL_String_Create
                (PKIX_ESCASCII, oidString , 0, pString, plContext),
                PKIX_STRINGCREATEFAILED);
cleanup:
        PR_smprintf_free(oidString);
        
        PKIX_RETURN(OID);
}
//-------------------------------------------------------------------
// VerifyHash
//
// Returns true if the file hash matches the expected value (or if
// the item has no hash value). False if we can't verify the hash
// for any reason
//
PRBool nsXPInstallManager::VerifyHash(nsXPITriggerItem* aItem)
{
    NS_ASSERTION(aItem, "Null nsXPITriggerItem passed to VerifyHash");

    nsresult rv;
    if (!aItem->mHasher)
      return PR_FALSE;

    nsCOMPtr<nsIInputStream> stream;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(stream), aItem->mFile);
    if (NS_FAILED(rv)) return PR_FALSE;

    rv = aItem->mHasher->UpdateFromStream(stream, PR_UINT32_MAX);
    if (NS_FAILED(rv)) return PR_FALSE;

    nsCAutoString binaryHash;
    rv = aItem->mHasher->Finish(PR_FALSE, binaryHash);
    if (NS_FAILED(rv)) return PR_FALSE;

    char* hash = nsnull;
    for (PRUint32 i=0; i < binaryHash.Length(); ++i)
    {
        hash = PR_sprintf_append(hash,"%.2x", (PRUint8)binaryHash[i]);
    }

    PRBool result = aItem->mHash.EqualsIgnoreCase(hash);

    PR_smprintf_free(hash);
    return result;
}
Exemple #13
0
static char *
lg_keydb_name_cb(void *arg, int dbVersion)
{
    const char *configdir = (const char *)arg;
    const char *dbver;
    char *smpname = NULL;
    char *dbname = NULL;
    
    switch (dbVersion) {
      case 4:
	dbver = "4";
	break;
      case 3:
	dbver = "3";
	break;
      case 1:
	dbver = "1";
	break;
      case 2:
      default:
	dbver = "";
	break;
    }

    smpname = PR_smprintf(KEY_DB_FMT, configdir, dbver);
    if (smpname) {
	dbname = PORT_Strdup(smpname);
	PR_smprintf_free(smpname);
    }
    return dbname;
}
Exemple #14
0
static CK_RV
lg_OpenKeyDB(const char * configdir, const char *prefix, PRBool readOnly,
    						NSSLOWKEYDBHandle **keydbPtr)
{
    NSSLOWKEYDBHandle *keydb;
    char * name = NULL;
    char * appName = NULL;

    if (prefix == NULL) {
	prefix = "";
    }
    configdir = lg_EvaluateConfigDir(configdir, &appName);

    name = PR_smprintf("%s" PATH_SEPARATOR "%s",configdir,prefix);	
    if (name == NULL) 
	return CKR_HOST_MEMORY;
    keydb = nsslowkey_OpenKeyDB(readOnly, appName, prefix, 
					lg_keydb_name_cb, (void *)name);
    PR_smprintf_free(name);
    if (appName) PORT_Free(appName);
    if (keydb == NULL)
	return CKR_NETSCAPE_KEYDB_FAILED;
    *keydbPtr = keydb;

    return CKR_OK;
}
nsresult nsPluginFile::FreePluginInfo(nsPluginInfo& info)
{
  if (info.fName)
    PL_strfree(info.fName);

  if (info.fDescription)
    PL_strfree(info.fDescription);

  if (info.fMimeTypeArray)
    FreeStringArray(info.fVariantCount, info.fMimeTypeArray);

  if (info.fMimeDescriptionArray)
    FreeStringArray(info.fVariantCount, info.fMimeDescriptionArray);

  if (info.fExtensionArray)
    FreeStringArray(info.fVariantCount, info.fExtensionArray);

  if (info.fFullPath)
    PL_strfree(info.fFullPath);

  if (info.fFileName)
    PL_strfree(info.fFileName);

  if (info.fVersion)
    PR_smprintf_free(info.fVersion);

  ZeroMemory((void *)&info, sizeof(info));

  return NS_OK;
}
Exemple #16
0
/*
** Perform a three way test against PR_smprintf, PR_snprintf, and sprintf.
** Make sure the results are identical
*/
static void test_ll(char *pattern, char *spattern, PRInt64 l)
{
    char *s;
    char buf[200];
    int n;

    /* try all three routines */
    s = PR_smprintf(pattern, l);
    PR_ASSERT(s != 0);
    n = PR_snprintf(buf, sizeof(buf), pattern, l);
    PR_ASSERT(n <= sizeof(buf));
#if defined(HAVE_LONG_LONG)
    sprintf(sbuf, spattern, l);

    /* compare results */
    if ((strncmp(s, buf, sizeof(buf)) != 0) ||
	(strncmp(s, sbuf, sizeof(sbuf)) != 0)) {
#if PR_BYTES_PER_LONG == 8
#define FORMAT_SPEC "%ld"
#elif defined(WIN16)
#define FORMAT_SPEC "%Ld"
#elif defined(WIN32)
#define FORMAT_SPEC "%I64d"
#else
#define FORMAT_SPEC "%lld"
#endif
	fprintf(stderr,
	    "pattern='%s' ll=" FORMAT_SPEC "\nPR_smprintf='%s'\nPR_snprintf='%s'\n    sprintf='%s'\n",
	    pattern, l, s, buf, sbuf);
	printf("FAIL\n");
	PR_smprintf_free(s);
	exit(-1);
    }
	PR_smprintf_free(s);
#else
    /* compare results */
    if ((strncmp(s, buf, sizeof(buf)) != 0)) {
	fprintf(stderr,
	    "pattern='%s'\nPR_smprintf='%s'\nPR_snprintf='%s'\n    sprintf='%s'\n",
	    pattern, s, buf, sbuf);
	printf("FAIL\n");
	PR_smprintf_free(s);
        exit(-1);
    }
	PR_smprintf_free(s);
#endif
}
// This function takes a message uri, converts it into a file path & msgKey
// pair. It then turns that into a mailbox url object. It also registers a url
// listener if appropriate. AND it can take in a mailbox action and set that field
// on the returned url as well.
nsresult nsMailboxService::PrepareMessageUrl(const char * aSrcMsgMailboxURI, nsIUrlListener * aUrlListener,
                                             nsMailboxAction aMailboxAction, nsIMailboxUrl ** aMailboxUrl,
                                             nsIMsgWindow *msgWindow)
{
  nsresult rv = CallCreateInstance(NS_MAILBOXURL_CONTRACTID, aMailboxUrl);
  if (NS_SUCCEEDED(rv) && aMailboxUrl && *aMailboxUrl)
  {
    // okay now generate the url string
    char * urlSpec;
    nsCAutoString folderURI;
    nsMsgKey msgKey;
    nsCString folderPath;
    const char *part = PL_strstr(aSrcMsgMailboxURI, "part=");
    const char *header = PL_strstr(aSrcMsgMailboxURI, "header=");
    rv = nsParseLocalMessageURI(aSrcMsgMailboxURI, folderURI, &msgKey);
    NS_ENSURE_SUCCESS(rv,rv);
    rv = nsLocalURI2Path(kMailboxRootURI, folderURI.get(), folderPath);

    if (NS_SUCCEEDED(rv))
    {
      // set up the url spec and initialize the url with it.
      nsCAutoString buf;
      MsgEscapeURL(folderPath,
                   nsINetUtil::ESCAPE_URL_DIRECTORY | nsINetUtil::ESCAPE_URL_FORCED, buf);
      if (mPrintingOperation)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&header=print", buf.get(), msgKey);
      else if (part)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&%s", buf.get(), msgKey, part);
      else if (header)
        urlSpec = PR_smprintf("mailbox://%s?number=%lu&%s", buf.get(), msgKey, header);
      else
        urlSpec = PR_smprintf("mailbox://%s?number=%lu", buf.get(), msgKey);

      nsCOMPtr <nsIMsgMailNewsUrl> url = do_QueryInterface(*aMailboxUrl);
      url->SetSpec(nsDependentCString(urlSpec));
      PR_smprintf_free(urlSpec);

      (*aMailboxUrl)->SetMailboxAction(aMailboxAction);

      // set up the url listener
      if (aUrlListener)
        rv = url->RegisterListener(aUrlListener);

      url->SetMsgWindow(msgWindow);
      nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(url);
      if (msgUrl)
      {
        msgUrl->SetOriginalSpec(aSrcMsgMailboxURI);
        msgUrl->SetUri(aSrcMsgMailboxURI);
      }

    } // if we got a url
  } // if we got a url

  return rv;
}
void sbDeviceXMLInfo::LogArgs(const char * aFmt,
                              va_list aArgs)
{
  char *msg = PR_vsmprintf(aFmt, aArgs);
  sbErrorConsole::Message(
                     "sbDeviceXMLInfo %s:\n%s",
                     sbDeviceUtils::GetDeviceIdentifier(mDevice).BeginReading(),
                     msg);
  PR_smprintf_free(msg);
}
void nsTSubstring_CharT::AppendPrintf( const char* format, ...)
  {
    char *buf;
    va_list ap;
    va_start(ap, format);
    buf = PR_vsmprintf(format, ap);
    AppendASCII(buf);
    PR_smprintf_free(buf);
    va_end(ap);
  }
int main(int argc, char* argv[])
{
  ScopedLogging log;

  nsCOMPtr<nsILocalFile> appini;
  nsresult rv = XRE_GetBinaryPath(argv[0], getter_AddRefs(appini));
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.");
    return 255;
  }
  appini->SetNativeLeafName(NS_LITERAL_CSTRING("application.ini"));

  // Allow firefox.exe to launch XULRunner apps via -app <application.ini>
  // Note that -app must be the *first* argument.
  char *appEnv = nsnull;
  const char *appDataFile = PR_GetEnv("XUL_APP_FILE");
  if (appDataFile && *appDataFile) {
    rv = XRE_GetFileFromPath(appDataFile, getter_AddRefs(appini));
    if (NS_FAILED(rv)) {
      Output("Invalid path found: '%s'", appDataFile);
      return 255;
    }
  }
  else if (argc > 1 && IsArg(argv[1], "app")) {
    if (argc == 2) {
      Output("Incorrect number of arguments passed to -app");
      return 255;
    }

    rv = XRE_GetFileFromPath(argv[2], getter_AddRefs(appini));
    if (NS_FAILED(rv)) {
      Output("application.ini path not recognized: '%s'", argv[2]);
      return 255;
    }

    appEnv = PR_smprintf("XUL_APP_FILE=%s", argv[2]);
    PR_SetEnv(appEnv);
    argv[2] = argv[0];
    argv += 2;
    argc -= 2;
  }

  nsXREAppData *appData;
  rv = XRE_CreateAppData(appini, &appData);
  if (NS_FAILED(rv)) {
    Output("Couldn't read application.ini");
    return 255;
  }

  int result = XRE_main(argc, argv, appData);
  XRE_FreeAppData(appData);
  if (appEnv)
    PR_smprintf_free(appEnv);
  return result;
}
Exemple #21
0
void log_print(const PRLogModuleInfo* aModule,
               LogLevel aLevel,
               const char* aFmt, ...)
{
  va_list ap;
  va_start(ap, aFmt);
  char* buff = PR_vsmprintf(aFmt, ap);
  PR_LogPrint("%s", buff);
  PR_smprintf_free(buff);
  va_end(ap);
}
Exemple #22
0
void PK11_UnconfigurePKCS11(void)
{
    if (pk11_config_strings != NULL) {
	PR_smprintf_free(pk11_config_strings);
        pk11_config_strings = NULL;
    }
    if (pk11_config_name) {
        PORT_Free(pk11_config_name);
        pk11_config_name = NULL;
    }
}
Exemple #23
0
/*************************************************************************
 *
 * j a r _ c a l l b a c k
 */
static int
jar_callback(int status, JAR *foo, const char *bar, char *pathname,
	char *errortext) {
	char *string;

	string = PR_smprintf("JAR error %d: %s in file %s\n", status, errortext,
		pathname);
	error(PK11_INSTALL_ERROR_STRING, string);
	PR_smprintf_free(string);
	return 0;
}
Exemple #24
0
static int st_search(SearchThread *st)
{
    char *filterBuffer = NULL;
    char *pFilter;
    struct timeval timeout;
    struct timeval *timeoutp;
    int scope, attrsOnly = 0;
    LDAPMessage *result;
    int ret;

    scope = myScope;
    if (ntable || numeric) {
        char *s = NULL;
        char num[22]; /* string length of unsigned 64 bit integer + 1 */

        if (! numeric) {
            do {
                s = nt_getrand(ntable);
            } while ((s) && (strlen(s) < 1));
        } else {
            sprintf(num, "%d", get_large_random_number() % numeric);
            s = num;
        }
        filterBuffer = PR_smprintf("%s%s",filter, s ? s : "");
        pFilter = filterBuffer;
    } else {
        pFilter = filter;
    }

    /* Try to get attributes from the attrNameTable */
    if (!attrToReturn)
        attrToReturn = nt_get_all(attrTable);

    if (searchTimelimit <= 0) {
        timeoutp = NULL;
    } else {
        timeout.tv_sec = searchTimelimit;
        timeout.tv_usec = 0;
        timeoutp = &timeout;
    }
    ret = ldap_search_ext_s(st->ld, suffix, scope, pFilter, attrToReturn,
                            attrsOnly, NULL, NULL, timeoutp, -1, &result);
    if (ret != LDAP_SUCCESS) {
        fprintf(stderr, "T%d: failed to search 2, error=0x%02X\n",
                st->id, ret);
    }
    ldap_msgfree(result);
    if(filterBuffer){
        PR_smprintf_free(filterBuffer);
    }

    return ret;
}
void
Pk11Install_yyerror(char *message)
{
    char *tmp;
    if (Pk11Install_yyerrstr) {
        tmp = PR_smprintf("%sline %d: %s\n", Pk11Install_yyerrstr,
                          Pk11Install_yylinenum, message);
        PR_smprintf_free(Pk11Install_yyerrstr);
    } else {
        tmp = PR_smprintf("line %d: %s\n", Pk11Install_yylinenum, message);
    }
    Pk11Install_yyerrstr = tmp;
}
Exemple #26
0
/*
 * dnHasAttribute - read an entry if it has a particular attribute
 * Return:
 *   The entry, or NULL
 */
Slapi_PBlock *
dnHasAttribute( const char *baseDN, const char *attrName ) {
	Slapi_PBlock *spb = NULL;
	char *filter = NULL;

	BEGIN
        int sres;
		Slapi_Entry **entries;
		char *attrs[2];

		/* Perform the search - the new pblock needs to be freed */
		attrs[0] = (char *)attrName;
		attrs[1] = NULL;
		filter = PR_smprintf( "%s=*", attrName );
		spb = slapi_search_internal((char *)baseDN, LDAP_SCOPE_BASE,
									filter, NULL, attrs, 0);
		if ( !spb ) {
			op_error(20);
			break;
		}
 
		if ( slapi_pblock_get( spb, SLAPI_PLUGIN_INTOP_RESULT, &sres ) ) {
			op_error(21);
			break;
		} else if (sres) {
			op_error(22);
			break;
		}

		if ( slapi_pblock_get(spb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES,
							  &entries) ) {
			op_error(23);
			break;
		}
		/*
		 * Can only be one entry returned on a base search; just check
		 * the first one
		 */
		if ( !*entries ) {
			/* Clean up */
			slapi_free_search_results_internal(spb);
			slapi_pblock_destroy(spb);
			spb = NULL;
		}
    END

	if (filter) {
		PR_smprintf_free(filter);
	}
	return spb;
}
Exemple #27
0
NS_IMETHODIMP nsPop3Service::VerifyLogon(nsIMsgIncomingServer *aServer,
                                         nsIUrlListener *aUrlListener,
                                         nsIMsgWindow *aMsgWindow,
                                         nsIURI **aURL)
{
  NS_ENSURE_ARG_POINTER(aServer);
  nsCString popHost;
  nsCString popUser;
  PRInt32 popPort = -1;

  nsresult rv = aServer->GetHostName(popHost);
  NS_ENSURE_SUCCESS(rv, rv);

  if (popHost.IsEmpty())
    return NS_MSG_INVALID_OR_MISSING_SERVER;

  rv = aServer->GetPort(&popPort);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aServer->GetUsername(popUser);
  NS_ENSURE_SUCCESS(rv, rv);

  if (popUser.IsEmpty())
    return NS_MSG_SERVER_USERNAME_MISSING;

  nsCString escapedUsername;
  MsgEscapeString(popUser, nsINetUtil::ESCAPE_XALPHAS, escapedUsername);

  nsCOMPtr<nsIPop3IncomingServer> popServer = do_QueryInterface(aServer, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  // now construct a pop3 url...
  // we need to escape the username because it may contain
  // characters like / % or @
  char *urlSpec = PR_smprintf("pop3://%s@%s:%d/?verifyLogon",
                              escapedUsername.get(), popHost.get(), popPort);
  NS_ENSURE_TRUE(urlSpec, NS_ERROR_OUT_OF_MEMORY);

  nsCOMPtr<nsIURI> url;
  rv = BuildPop3Url(urlSpec, nsnull, popServer, aUrlListener,
                    getter_AddRefs(url), aMsgWindow);
  PR_smprintf_free(urlSpec);

  if (NS_SUCCEEDED(rv) && url)
  {
    rv = RunPopUrl(aServer, url);
    if (NS_SUCCEEDED(rv) && aURL)
      url.forget(aURL);
  }

  return rv;
}
/**
 * implementation of InstallVersion.toString()
 */
static JSBool PR_CALLBACK su_verobjToString(JSContext *cx, JSObject *obj, uint argc, jsval *argv, jsval *rval)
{
    char     *str;
    VERSION  v;

    su_objToVers(cx, obj, &v );
    
    str = PR_smprintf("%d.%d.%d.%d", v.major, v.minor, v.release, v.build);

    *rval = STRING_TO_JSVAL( JS_NewStringCopyZ(cx,str) );

    PR_smprintf_free(str);
    return JS_TRUE;
}
Exemple #29
0
// log a message to remote server with a user token id given 
// for the remote server to fill in with user token details.
am_status_t 
Log::rlog(ModuleId module, int remote_log_level, 
	  const char *user_sso_token, const char *format, ...)
    throw()
{
    am_status_t status = AM_SUCCESS;
    char *logMsg = NULL;
    std::string logMessage;
    bool cookieEncoded = false;

    if (rmtLogSvc == NULL || !remoteInitialized) { 
	status = AM_SERVICE_NOT_INITIALIZED;
    }
    else {
	std::va_list args;
	va_start(args, format);
	logMsg = PR_vsmprintf(format, args);
	logMessage = logMsg;
	if (logMsg != NULL) {

            if (logMsg[0] == '\0') {
                Log::log(Log::ALL_MODULES, Log::LOG_WARNING,
                    "Log Record Message is empty");
                return status;
            }

	    try {
		LogRecord logRecord(
			    static_cast<LogRecord::Level>(remote_log_level), 
			    logMessage);
	        std::string userSSOToken = user_sso_token;
		cookieEncoded = userSSOToken.find('%') != std::string::npos;
	        if (cookieEncoded) {
		    userSSOToken = Http::decode(std::string(user_sso_token));
	        }
		logRecord.populateTokenDetails(userSSOToken);
		status = rmtLogSvc->sendLog("", logRecord, "");	
	    }
	    catch (std::exception& exs) {
		status = AM_FAILURE;
	    }
	    catch (...) {
		status = AM_FAILURE;
	    }
	    PR_smprintf_free(logMsg);
	}
	va_end(args);
    }
    return status;
}
Exemple #30
0
static CURLcode init_nss(struct SessionHandle *data)
{
  char *cert_dir;
  struct_stat st;
  if(initialized)
    return CURLE_OK;

  /* First we check if $SSL_DIR points to a valid dir */
  cert_dir = getenv("SSL_DIR");
  if(cert_dir) {
    if((stat(cert_dir, &st) != 0) ||
        (!S_ISDIR(st.st_mode))) {
      cert_dir = NULL;
    }
  }

  /* Now we check if the default location is a valid dir */
  if(!cert_dir) {
    if((stat(SSL_DIR, &st) == 0) &&
        (S_ISDIR(st.st_mode))) {
      cert_dir = (char *)SSL_DIR;
    }
  }

  if(!NSS_IsInitialized()) {
    SECStatus rv;
    initialized = 1;
    infof(data, "Initializing NSS with certpath: %s\n",
          cert_dir ? cert_dir : "none");
    if(!cert_dir) {
      rv = NSS_NoDB_Init(NULL);
    }
    else {
      char *certpath =
        PR_smprintf("%s%s", NSS_VersionCheck("3.12.0") ? "sql:" : "", cert_dir);
      rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY);
      PR_smprintf_free(certpath);
    }
    if(rv != SECSuccess) {
      infof(data, "Unable to initialize NSS database\n");
      initialized = 0;
      return CURLE_SSL_CACERT_BADFILE;
    }
  }

  if(num_enabled_ciphers() == 0)
    NSS_SetDomesticPolicy();

  return CURLE_OK;
}