int main(int argc, char **argv)
{
    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "dh");
    PRFileDesc* fd;
    PRErrorCode err;

    /* parse command line options */
    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option) {
            case 'd':  /* debug mode */
                debug_mode = PR_TRUE;
                break;
            case 'h':
            default:
                Help();
                return 2;
        }
    }
    PL_DestroyOptState(opt);

    lm = PR_NewLogModule( "testcase" );

    (void) PR_MkDir( DIRNAME, 0777);
    fd = PR_Open( DIRNAME FILENAME, PR_CREATE_FILE|PR_RDWR, 0666);
    if (fd == 0) {
        PRErrorCode err = PR_GetError();
        fprintf(stderr, "create file fails: %d: %s\n", err,
            PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        failed_already = PR_TRUE;
        goto Finished;
    }
 
    PR_Close(fd);

    if (PR_RmDir( DIRNAME ) == PR_SUCCESS) {
        fprintf(stderr, "remove directory succeeds\n");
        failed_already = PR_TRUE;
        goto Finished;
    }
 
    err = PR_GetError();
    fprintf(stderr, "remove directory fails with: %d: %s\n", err,
        PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));

    (void) PR_Delete( DIRNAME FILENAME);
    (void) PR_RmDir( DIRNAME );

    return 0;

Finished:
    if ( debug_mode ) printf("%s\n", ( failed_already ) ? "FAILED" : "PASS" );
    return( (failed_already)? 1 : 0 );
}  /* --- end main() */
Example #2
0
am_status_t am_policy_destroy(am_policy_t policy_handle)
{
    am_status_t retVal = AM_SUCCESS;

    try {
	enginePtr->destroy_service(policy_handle);
    } catch(InternalException &ie) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_destroy: InternalException in %s, Message is %s, Status code is %d.",
		 ie.getThrowingMethod(), ie.getMessage(),ie.getStatusCode());

	retVal = ie.getStatusCode();
    } catch(NSPRException &ne) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_destroy: NSPRException inside %s when calling "
		 "NSPR method %s. Error code:%s",
		 ne.getThrowingMethod(), ne.getNsprMethod(),
		 PR_ErrorToString(ne.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
	retVal = AM_NSPR_ERROR;
    } catch(std::bad_alloc) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_destroy: Memory allocation problem.");
	retVal = AM_NO_MEMORY;
    } catch(std::exception &ex) {
	// Log:ERROR
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR, ex);
	retVal = AM_FAILURE;
    } catch(...) {
	// Mother of all catches.
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_destroy: Unkown exception occured.");
	retVal = AM_FAILURE;
    }
    return retVal;
}
Example #3
0
/*
 * Method to check if notification is enabled in the SDK.
 *
 * Returns:
 *  If notification is enabled returns non-zero, otherwise zero.
 */
extern "C" boolean_t
am_policy_is_notification_enabled(am_policy_t policy_handle) {
    try {
	return (enginePtr->isNotificationEnabled(policy_handle)==true)?B_TRUE:B_FALSE;
    }  catch(InternalException &ie) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_is_notification_enabled: InternalException in %s "
		 "with error message:%s and code:%s",
		 ie.getThrowingMethod(), ie.getMessage(),
		 am_status_to_string(ie.getStatusCode()));
    } catch(NSPRException &ne) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_is_notification_enabled: NSPRException inside %s "
		 "when calling NSPR method %s. Error code:%s",
		 ne.getThrowingMethod(), ne.getNsprMethod(),
		 PR_ErrorToString(ne.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
    } catch(std::bad_alloc &ex) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
	 "am_policy_is_notification_enabled: Memory allocation problem.");
    } catch(std::exception &ex) {
	// Log:ERROR
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR, ex);
    } catch(...) {
	// Mother of all catches.
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_is_notification_enabled: Unknown exception occured.");
	return B_FALSE;
    }

    return B_FALSE;
}
Example #4
0
void
nssError (void)
{
  PRErrorCode errorNumber;
  char *errorText;
  
  /* See if PR_GetError can tell us what the error is.  */
  errorNumber = PR_GetError ();
  fprintf(stderr, "(%d) ", errorNumber);

  /* PR_ErrorToString always returns a valid string for errors in this range.  */
  if (errorNumber >= PR_NSPR_ERROR_BASE && errorNumber <= PR_MAX_ERROR)
    {
      fprintf (stderr, "%s\n", PR_ErrorToString(errorNumber, PR_LANGUAGE_EN));
      return;
    }

  /* PR_ErrorToString does not handle errors outside the range above, so
     we handle them ourselves.  */
  switch (errorNumber) {
  default: errorText = "(unknown)"; break;
#define NSSYERROR(code,msg) case code: errorText = msg; break
#include "stapsslerr.h"
#undef NSSYERROR
    }

  fprintf (stderr, "%s\n", errorText);
}
Example #5
0
static void 
lperror(const char *string) {
    PRErrorCode errorcode;

    errorcode = PR_GetError();
    PR_fprintf(PR_STDERR, "%s: %d: %s\n", string, errorcode,
                PR_ErrorToString(errorcode, PR_LANGUAGE_I_DEFAULT));
}
Example #6
0
/*
 * Method to evaluate a non-boolean policy question for a resource.
 */
extern "C" am_status_t
am_policy_evaluate_ignore_url_notenforced(am_policy_t policy_handle,
		      const char *sso_token,
		      const char *resource_name,
		      const char *action_name,
		      const am_map_t env_table,
		      am_map_t policy_response_map_ptr,
		      am_policy_result_t *policy_res,
		      am_bool_t ignorePolicyResult,
		      am_properties_t properties) {
    try {
	enginePtr->policy_evaluate(policy_handle,
				   sso_token,
				   resource_name,
				   action_name,
				   env_table,
				   policy_response_map_ptr,
				   policy_res,
				   ignorePolicyResult,
				   *reinterpret_cast<Properties *>(properties));
    } catch(InternalException &ie) {
	Log::Level lvl = Log::LOG_ERROR;
	if(ie.getStatusCode() == AM_INVALID_SESSION) {
	    lvl = Log::LOG_INFO;
	} else  if(ie.getStatusCode() == AM_NO_POLICY) {
            lvl = Log::LOG_WARNING;
        }

	Log::log(enginePtr->getModuleID(), lvl,
		 "am_policy_evaluate: InternalException in %s with error message:%s and code:%d",
		 ie.getThrowingMethod(), ie.getMessage(), ie.getStatusCode());

	return ie.getStatusCode();
    } catch(NSPRException &ne) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_evaluate: NSPRException inside %s when "
		 "calling NSPR method %s. Error code:%s",
		 ne.getThrowingMethod(), ne.getNsprMethod(),
		 PR_ErrorToString(ne.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
	return AM_NSPR_ERROR;
    } catch(std::bad_alloc &ex) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_evaluate: Memory allocation problem.");
	return AM_NO_MEMORY;
    } catch(std::exception &ex) {
	// Log:ERROR
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR, ex);
	return AM_FAILURE;
    } catch(...) {
	// Mother of all catches.
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_evaluate: Unknown exception occured.");
	return AM_FAILURE;
    }

    return AM_SUCCESS;
}
Example #7
0
File: nss.c Project: flashfoxter/sx
static CERTCertificate *load_cert_file(sxc_client_t *sx, const char *file, struct PK11_ctx *ctx) {
    const char *slot_name = "PEM Token #0";
    CK_OBJECT_CLASS obj_class;
    CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
    unsigned attr_cnt = 0;
    CK_BBOOL cktrue = CK_TRUE;
    SECMODModule *mod;
    CERTCertificate *cert = NULL;

    if(!file || !ctx) {
        sxi_seterr(sx, SXE_EARG, "NULL argument");
        return NULL;
    }
    memset(ctx, 0, sizeof(*ctx));

    mod = SECMOD_LoadUserModule("library=libnsspem.so name=PEM", NULL, PR_FALSE);
    if (!mod || !mod->loaded) {
        if (mod)
            SECMOD_DestroyModule(mod);
        sxi_setsyserr(sx, SXE_ECFG, "Failed to load NSS PEM library");
        return NULL;
    }

    sxi_crypto_check_ver(NULL);
    ctx->slot = PK11_FindSlotByName(slot_name);
    if (ctx->slot) {
        obj_class = CKO_CERTIFICATE;
        PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
        PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
        PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)file,
                      strlen(file) + 1);

        if(CKO_CERTIFICATE == obj_class) {
            CK_BBOOL *pval = &cktrue;
            PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
        }

        ctx->obj = PK11_CreateGenericObject(ctx->slot, attrs, attr_cnt, PR_FALSE);
        if (!ctx->obj) {
            sxi_seterr(sx, SXE_ECFG, "Cannot load certificate from '%s': %s, %s",
                       file, PR_ErrorToString(PR_GetError(), PR_LANGUAGE_I_DEFAULT),
                       PR_ErrorToName(PR_GetError()));
            return NULL;
        }
        ctx->list = PK11_ListCertsInSlot(ctx->slot);
        if (ctx->list) {
            CERTCertListNode *node = CERT_LIST_HEAD(ctx->list);
            cert = node ? node->cert : NULL;
        }
    } else {
        sxi_seterr(sx, SXE_ECFG, "Failed to initialize NSS PEM token");
        return NULL;
    }

    return cert;
}
Example #8
0
/**
 * Throws NSPRException upon NSPR error
 */
Connection::Connection(const ServerInfo& server,
		       const std::string &certDBPasswd,
		       const std::string &certNickName,
		       bool alwaysTrustServerCert) 
    : socket(NULL), certdbpasswd(NULL), certnickname(NULL)
{
    char      buffer[PR_NETDB_BUF_SIZE];
    PRNetAddr address;
    PRHostEnt hostEntry;
    PRIntn    hostIndex;
    PRStatus	prStatus;
    SECStatus	secStatus;

    prStatus = PR_GetHostByName(server.getHost().c_str(), buffer,
				sizeof(buffer), &hostEntry);
    if (PR_SUCCESS != prStatus) {
        throw NSPRException("Connection::Connection", "PR_GetHostByName");
    }

    hostIndex = PR_EnumerateHostEnt(0, &hostEntry, server.getPort(), &address);
    if (hostIndex < 0) {
        throw NSPRException("Connection::Connection", "PR_EnumerateHostEnt");
    }

    socket = createSocket(address, server.useSSL(),
			  certDBPasswd,
			  certNickName,
			  alwaysTrustServerCert);

    if (server.useSSL()) {
	secStatus = SSL_SetURL(socket, server.getHost().c_str());
	if (SECSuccess != secStatus) {
	    PRErrorCode error = PR_GetError();

	    PR_Shutdown(socket, PR_SHUTDOWN_BOTH);
	    PR_Close(socket);
	    Log::log(Log::ALL_MODULES, Log::LOG_ERROR,
		     "SSL_SetURL() returned error: %s",
		     PR_ErrorToString(error, PR_LANGUAGE_I_DEFAULT));
	    throw NSPRException("Connection::Connection",
				"SSL_SetURL", error);
	}
    }

    prStatus = PR_Connect(socket, &address, connect_timeout);

    if (prStatus != PR_SUCCESS) {
	PRErrorCode error = PR_GetError();

	PR_Shutdown(socket, PR_SHUTDOWN_BOTH);
	PR_Close(socket);
	throw NSPRException("Connection::Connection PR_Connect", "PR_Connect", error);
    }
}
Example #9
0
bool GetErrorText(JSContext *cx, IN JS::HandleObject obj, OUT JS::MutableHandleValue rval) {

	JL_CHK( JL_GetReservedSlot(obj, 0, rval) );  // (TBD) use the obj.name proprety directly instead of slot 0 ?
	if ( rval.isUndefined() )
		return true;
	PRErrorCode errorCode;
	errorCode = rval.toInt32();
	JL_CHK( jl::setValue( cx, rval, PR_ErrorToString( errorCode, PR_LANGUAGE_EN ) ) );
	return true;
	JL_BAD;
}
Example #10
0
/*
 * Method to initialize a policy evaluator object.
 */
extern "C" am_status_t
am_policy_service_init(const char *service_name,
		       const char *instance_name,
		       am_resource_traits_t rsrcTraits,
		       am_properties_t service_config_params,
		       am_policy_t *policy_handle_ptr)
{
    try {
	*policy_handle_ptr = enginePtr->create_service(service_name,
						       instance_name,
						       rsrcTraits,
						       *reinterpret_cast<Properties *>(service_config_params));
    } catch(InternalException &ie) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_init: InternalException in %s, Message is %s, Status code is %d.",
		 ie.getThrowingMethod(), ie.getMessage(),ie.getStatusCode());

	return ie.getStatusCode();
    } catch(NSPRException &ne) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_init: NSPRException inside %s when calling "
		 "NSPR method %s. Error code:%s",
		 ne.getThrowingMethod(), ne.getNsprMethod(),
		 PR_ErrorToString(ne.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
	return AM_NSPR_ERROR;
    } catch(std::bad_alloc) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_init: Memory allocation problem.");
	return AM_NO_MEMORY;
    } catch(std::exception &ex) {
	// Log:ERROR
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR, ex);
	return AM_FAILURE;
    } catch(...) {
	// Mother of all catches.
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_init: Unkown exception occured.");
	return AM_FAILURE;
    }

    return AM_SUCCESS;
}
Example #11
0
// Print out the current NSPR error message to the given output stream.
void NSPR_PrintError(const std::string& errorPrefixString, std::ostream& out)
{
   PRErrorCode  err = PR_GetError();
   const char* err_name = PR_ErrorToName(err);
   const char* err_str = PR_ErrorToString(err,0);

   out << "Error (NSPR): " << errorPrefixString << "(" << err;

   if ( err_name != NULL )
   {
      out << ":" << err_name;
   }

   if ( err_str != NULL )
   {
      out << ", " << err_str;
   }

   out << ")" << std::endl;
}
Example #12
0
File: nss.c Project: flashfoxter/sx
int sxi_sslctxfun(sxc_client_t *sx, curlev_t *ev, const struct curl_tlssessioninfo *info)
{
    CERTCertificate *cert;
    int rc = cert_from_sessioninfo(sx, info, &cert);
    if (rc)
        return rc;
    sxi_conns_t *conns = sxi_curlev_get_conns(ev);
    const char *hostname = sxi_conns_get_sslname(conns);
    SECStatus ret = CERT_VerifyCertName(cert, hostname);
    if (ret == SECSuccess) {
        sxi_curlev_set_verified(ev, 1);
    } else {
        PRInt32 err = PR_GetError();
        sxi_seterr(sx, SXE_ECOMM, "Certificate is not valid for cluster '%s': %s", hostname,
                   PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        sxi_curlev_set_verified(ev, -1);
        return -1;
    }
    return 0;
}
Example #13
0
extern "C" am_status_t
am_policy_user_logout(am_policy_t policy_handle,
                             const char *ssoTokenId,
                             am_properties_t properties) 
{
    Log::ModuleId logID = Log::addModule(AM_POLICY_SERVICE);
    am_status_t status = AM_FAILURE;
    try {
        status = enginePtr->user_logout(policy_handle, 
                     ssoTokenId,
                     *reinterpret_cast<Properties *>(properties));
    } catch (InternalException& ex) {
	Log::log(logID, Log::LOG_ERROR,
		 "am_policy_user_logout(): "
		 "Internal Exception encountered: '%s'",
		 ex.getMessage());
	status = ex.getStatusCode();
    }
    catch (NSPRException& ex) {
	Log::log(logID, Log::LOG_ERROR,
		 "am_policy_user_logout(): "
		 "NSPR Exception encountered: Error code %s",
                  PR_ErrorToString(ex.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
	Log::log(logID, Log::LOG_ERROR, ex);
	status = AM_NSPR_ERROR;
    }
    catch (std::exception& ex) {
	Log::log(logID, Log::LOG_ERROR,
		 "am_policy_user_logout(): "
		 "Unknown Exception encountered: %s", ex.what());
	Log::log(logID, Log::LOG_ERROR, ex);
        status = AM_FAILURE;
    }
    catch (...) {
	Log::log(logID, Log::LOG_ERROR,
		 "am_policy_user_logout(): "
		 "Unknown Exception encountered.");
        status = AM_FAILURE;
    }
    return status;
}
Example #14
0
File: nss.c Project: flashfoxter/sx
static int cert_from_sessioninfo(sxc_client_t *sx, const struct curl_tlssessioninfo *info, CERTCertificate **cert)
{
    if (info->backend != CURLSSLBACKEND_NSS) {
        curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
        sxi_seterr(sx, SXE_ECURL, "SSL backend mismatch: NSS expected, got %d (curl %s)",
                   info->backend, data->ssl_version ? data->ssl_version : "N/A");
        return -1;
    }
    PRFileDesc *desc = info->internals;
    if(!desc) {
        SXDEBUG("NULL PRFileDesc context");
        return -EAGAIN;
    }
    *cert = SSL_PeerCertificate(desc);
    if (!*cert) {
        PRInt32 err = PR_GetError();
        SXDEBUG("Unable to retrieve certificate for cluster: %s",
                PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        return -EAGAIN;
    }
    return 0;
}
Example #15
0
/*
 * Method to refresh policy cache when a policy notification is received
 * by the client.
 */
extern "C" am_status_t
am_policy_notify(am_policy_t policy_handle,
		    const char *notification_data,
		    size_t notification_data_len,
                    boolean_t configChangeNotificationEnabled)
{
    try {
	enginePtr->policy_notify(policy_handle, notification_data,
				 notification_data_len,
                                 configChangeNotificationEnabled);
    } catch(InternalException &ie) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_notify: InternalException in %s with error message:%s and code:%d",
		 ie.getThrowingMethod(), ie.getMessage(), ie.getStatusCode());
	return ie.getStatusCode();
    } catch(NSPRException &ne) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_notify(): NSPRException inside %s "
		 "when calling NSPR method %s. Error code:%s",
		 ne.getThrowingMethod(), ne.getNsprMethod(),
		 PR_ErrorToString(ne.getErrorCode(), PR_LANGUAGE_I_DEFAULT));
	return AM_NSPR_ERROR;
    } catch(std::bad_alloc &ex) {
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_notify(): Memory allocation problem.");
	return AM_NO_MEMORY;
    } catch(std::exception &ex) {
	// Log:ERROR
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR, ex);
	return AM_FAILURE;
    } catch(...) {
	// Mother of all catches.
	Log::log(enginePtr->getModuleID(), Log::LOG_ERROR,
		 "am_policy_notify(): Unknown error occured.");
	return AM_FAILURE;
    }
    return AM_SUCCESS;
}
Example #16
0
void
SECU_PrintError(const char *progName, const char *msg, ...)
{
    va_list args;
    PRErrorCode err = PORT_GetError();
    const char *errName = PR_ErrorToName(err);
    const char *errString = PR_ErrorToString(err, 0);

    va_start(args, msg);

    fprintf(stderr, "%s: ", progName);
    vfprintf(stderr, msg, args);

    if (errName != NULL) {
        fprintf(stderr, ": %s", errName);
    } else {
        fprintf(stderr, ": error %d", (int)err);
    }

    if (errString != NULL && PORT_Strlen(errString) > 0)
        fprintf(stderr, ": %s\n", errString);

    va_end(args);
}
Example #17
0
static void nss_print_error_message(struct SessionHandle *data, PRUint32 err)
{
  failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
}
int
main(int argc, char* argv[])
{
    if (test_common_init(&argc, &argv) != 0)
        return -1;

    int returnCode = 0;
    nsresult rv = NS_OK;
    PRFileDesc *serverFD = nullptr;

    do { // act both as a scope for nsCOMPtrs to be released before XPCOM
        // shutdown, as well as a easy way to abort the test
        PRStatus status = PR_SUCCESS;

        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        UDP_ASSERT(registrar, "Null nsIComponentRegistrar");
        if (registrar)
            registrar->AutoRegister(nullptr);

        // listen for a incoming UDP connection on localhost
        serverFD = PR_OpenUDPSocket(PR_AF_INET);
        UDP_ASSERT(serverFD, "Cannot open UDP socket for listening");

        PRSocketOptionData socketOptions;
        socketOptions.option = PR_SockOpt_Nonblocking;
        socketOptions.value.non_blocking = false;
        status = PR_SetSocketOption(serverFD, &socketOptions);
        UDP_ASSERT_PRSTATUS("Failed to set server socket as blocking");

        PRNetAddr addr;
        status = PR_InitializeNetAddr(PR_IpAddrLoopback, UDP_PORT, &addr);
        UDP_ASSERT_PRSTATUS("Failed to initialize loopback address");

        status = PR_Bind(serverFD, &addr);
        UDP_ASSERT_PRSTATUS("Failed to bind server socket");

        // dummy IOService to get around bug 379890
        nsCOMPtr<nsISupports> ios =
            do_GetService("@mozilla.org/network/io-service;1");

        // and have a matching UDP connection for the client
        nsCOMPtr<nsISocketTransportService> sts =
            do_GetService("@mozilla.org/network/socket-transport-service;1", &rv);
        UDP_ASSERT_NSRESULT("Cannot get socket transport service");

        nsCOMPtr<nsISocketTransport> transport;
        const char *protocol = "udp";
        rv = sts->CreateTransport(&protocol, 1, NS_LITERAL_CSTRING("localhost"),
                                  UDP_PORT, nullptr, getter_AddRefs(transport));
        UDP_ASSERT_NSRESULT("Cannot create transport");

        uint32_t count, read;
        const uint32_t data = 0xFF0056A9;

        // write to the output stream
        nsCOMPtr<nsIOutputStream> outstream;
        rv = transport->OpenOutputStream(nsITransport::OPEN_BLOCKING,
                                         0, 0, getter_AddRefs(outstream));
        UDP_ASSERT_NSRESULT("Cannot open output stream");

        rv = outstream->Write((const char*)&data, sizeof(uint32_t), &count);
        UDP_ASSERT_NSRESULT("Cannot write to output stream");
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not write enough bytes to output stream");

        // read from NSPR to check it's the same
        count = PR_RecvFrom(serverFD, &read, sizeof(uint32_t), 0, &addr, 1);
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not read enough bytes from NSPR");
        status = (read == data ? PR_SUCCESS : PR_FAILURE);
        UDP_ASSERT_PRSTATUS("Did not read expected data from NSPR");

        // write to NSPR
        count = PR_SendTo(serverFD, &data, sizeof(uint32_t), 0, &addr, 1);
        status = (count == sizeof(uint32_t) ? PR_SUCCESS : PR_FAILURE);
        UDP_ASSERT_PRSTATUS("Did not write enough bytes to NSPR");

        // read from stream
        nsCOMPtr<nsIInputStream> instream;
        rv = transport->OpenInputStream(nsITransport::OPEN_BLOCKING,
                                        0, 0, getter_AddRefs(instream));
        UDP_ASSERT_NSRESULT("Cannot open input stream");

        rv = instream->Read((char*)&read, sizeof(uint32_t), &count);
        UDP_ASSERT_NSRESULT("Cannot read from input stream");
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not read enough bytes from input stream");
        UDP_ASSERT(read == data, "Did not read expected data from stream");

    } while (false); // release all XPCOM things
    if (serverFD) {
        PRStatus status = PR_Close(serverFD);
        if (status != PR_SUCCESS) {
            PRErrorCode err = PR_GetError();
            fprintf(stderr, "FAIL: Cannot close server: (%08x) %s\n",
                    err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        }
    }
    rv = NS_ShutdownXPCOM(nullptr);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");

    return returnCode;
}
Example #19
0
File: err.c Project: scotte/pcp
char *
pmErrStr_r(int code, char *buf, int buflen)
{
    int		i;
#ifndef IS_MINGW
    static int	first = 1;
    static char	*unknown = NULL;
#else
    static char	unknown[] = "Unknown error";
#endif

    if (code == 0) {
	strncpy(buf, "No error", buflen);
	buf[buflen-1] = '\0';
	return buf;
    }

    /*
     * Is the code from a library wrapped by libpcp?  (e.g. NSS/SSL/SASL)
     * By good fortune, these libraries are using error codes that do not
     * overlap - by design for NSS/SSL/NSPR, and by sheer luck with SASL.
     */
    if (code < PM_ERR_NYI) {
#ifdef HAVE_SECURE_SOCKETS
#define DECODE_SECURE_SOCKETS_ERROR(c)	((c) - PM_ERR_NYI)	/* negative */
#define DECODE_SASL_SPECIFIC_ERROR(c)	((c) < -1000 ? 0 : (c))

	int error = DECODE_SECURE_SOCKETS_ERROR(code);
	if (DECODE_SASL_SPECIFIC_ERROR(error)) {
	    PM_LOCK(__pmLock_extcall);
	    pmsprintf(buf, buflen, "Authentication - %s", sasl_errstring(error, NULL, NULL));	/* THREADSAFE */
	    PM_UNLOCK(__pmLock_extcall);
	}
	else
	    strncpy(buf, PR_ErrorToString(error, PR_LANGUAGE_EN), buflen);
	buf[buflen-1] = '\0';
	return buf;
#endif
    }

#ifndef IS_MINGW
    PM_LOCK(err_lock);
    if (first) {
	/*
	 * reference message for an unrecognized error code.
	 * For IRIX, strerror() returns NULL in this case.
	 */
	strerror_x(-1, buf, buflen);
	if (buf[0] != '\0') {
	    /*
	     * For Linux et al, strip the last word, expected to be the
	     * error number as in ...
	     *    Unknown error -1
	     * or
	     *    Unknown error 4294967295
	     */
	    char *sp = strrchr(buf, ' ');
	    char *p;

	    if (sp != NULL) {
		sp++;
		if (*sp == '-') sp++;
		for (p = sp; *p != '\0'; p++) {
		    if (!isdigit((int)*p)) break;
		}

		if (*p == '\0') {
PM_FAULT_POINT("libpcp/" __FILE__ ":1", PM_FAULT_ALLOC);
		    *sp = '\0';
		    if ((unknown = strdup(buf)) != NULL)
			unknown[sp - buf] = '\0';
		}
	    }
	}
	first = 0;
    }
    PM_UNLOCK(err_lock);
    if (code < 0 && code > -PM_ERR_BASE) {
	/* intro(2) / errno(3) errors, maybe */
	strerror_x(-code, buf, buflen);
	if (unknown == NULL) {
	    if (buf[0] != '\0')
		return buf;
	}
	else {
	    /* The intention here is to catch variants of "Unknown
	     * error XXX" - in this case we're going to fail the
	     * stncmp() below, fall through and return a pcp error
	     * message, otherwise return the system error message
	     */
	    if (strncmp(buf, unknown, strlen(unknown)) != 0)
		return buf;
	}
    }
#else	/* WIN32 */
    if (code > -PM_ERR_BASE || code < -PM_ERR_NYI) {
	const char	*bp;
	if ((bp = wsastrerror(-code)) != NULL) {
	    strncpy(buf, bp, buflen);
	    buf[buflen-1] = '\0';
	}
	else {
	    /* No strerror_r in MinGW, so need to lock */
	    char	*tbp;
	    PM_LOCK(__pmLock_extcall);
	    tbp = strerror(-code);		/* THREADSAFE */
	    strncpy(buf, tbp, buflen);
	    buf[buflen-1] = '\0';
	    PM_UNLOCK(__pmLock_extcall);
	}

	if (strncmp(buf, unknown, strlen(unknown)) != 0)
	    return buf;
    }
#endif

    for (i = 0; errtab[i].err; i++) {
	if (errtab[i].err == code) {
	    strncpy(buf, errtab[i].errmess, buflen);
	    buf[buflen-1] = '\0';
	    return buf;
	}
    }

    /* failure */
    pmsprintf(buf, buflen, BADCODE,  code);
    return buf;
}
Example #20
0
am_status_t Properties::load(const std::string& fileName)
{
    am_status_t status = AM_SUCCESS;
    PRFileDesc *propFile;

    PRErrorCode pr_errorCode;

    propFile = PR_Open(fileName.c_str(), PR_RDONLY, 0);
    if (NULL != propFile) {
	PRFileInfo fileInfo;

	if (PR_GetOpenFileInfo(propFile, &fileInfo) == PR_SUCCESS) {
	    try {
		PRInt32 readCount;
		char *buffer = new char[fileInfo.size + 1];

		readCount = PR_Read(propFile, buffer, fileInfo.size);
		if (readCount == fileInfo.size) {
		    buffer[readCount] = '\0';
		    status = parseBuffer(buffer);
		} else {
		    Log::log(Log::ALL_MODULES, 
			     Log::LOG_ERROR, 
			     "am_properties_load(): "
			     "Could not load properties file %s: "
			     "Number of bytes read (%d) "
			     "did not match expected file size (%d).\n", 
			     fileName.c_str(), readCount, fileInfo.size);
		    status = AM_NSPR_ERROR;
		}
               
                delete[] buffer;
	    } catch (const std::bad_alloc&) {
		status = AM_NO_MEMORY;
	    }

	} else {
	    pr_errorCode = PR_GetError();
	    Log::log(Log::ALL_MODULES, Log::LOG_ERROR, 
		     "am_properties_load(): "
		     "Error getting info for properties file %s: %s\n", 
		     fileName.c_str(), 
		     PR_ErrorToString(pr_errorCode, PR_LANGUAGE_I_DEFAULT));
	    status = AM_NSPR_ERROR;
	}
	PR_Close(propFile);
    } else {
	pr_errorCode = PR_GetError();

	if (PR_FILE_NOT_FOUND_ERROR == pr_errorCode) {
	    status = AM_NOT_FOUND;
	} else if (PR_NO_ACCESS_RIGHTS_ERROR == pr_errorCode) {
	    status = AM_ACCESS_DENIED;
	} else {
	    Log::log(Log::ALL_MODULES, Log::LOG_ERROR, 
		     "am_properties_load(): "
		     "Error opening properties file '%s': %s\n", 
		     fileName.c_str(), 
		     PR_ErrorToString(pr_errorCode, PR_LANGUAGE_I_DEFAULT));
	    status = AM_NSPR_ERROR;
	}
    }

    return status;
}
Example #21
0
nsresult
nsNSSErrors::getErrorMessageFromCode(PRErrorCode err,
                                     nsINSSComponent *component,
                                     nsString &returnedMessage)
{
  NS_ENSURE_ARG_POINTER(component);
  returnedMessage.Truncate();

  const char *nss_error_id_str = getDefaultErrorStringName(err);
  const char *id_str = getOverrideErrorStringName(err);

  if (id_str || nss_error_id_str)
  {
    nsString defMsg;
    nsresult rv;
    if (id_str)
    {
      rv = component->GetPIPNSSBundleString(id_str, defMsg);
    }
    else
    {
      rv = component->GetNSSBundleString(nss_error_id_str, defMsg);
    }

    if (NS_SUCCEEDED(rv))
    {
      returnedMessage.Append(defMsg);
      returnedMessage.Append(NS_LITERAL_STRING("\n"));
    }
  }
  
  if (returnedMessage.IsEmpty())
  {
    // no localized string available, use NSS' internal
    returnedMessage.AppendASCII(PR_ErrorToString(err, PR_LANGUAGE_EN));
    returnedMessage.Append(NS_LITERAL_STRING("\n"));
  }
  
  if (nss_error_id_str)
  {
    nsresult rv;
    nsCString error_id(nss_error_id_str);
    ToLowerCase(error_id);
    NS_ConvertASCIItoUTF16 idU(error_id);

    const PRUnichar *params[1];
    params[0] = idU.get();

    nsString formattedString;
    rv = component->PIPBundleFormatStringFromName("certErrorCodePrefix", 
                                                  params, 1, 
                                                  formattedString);
    if (NS_SUCCEEDED(rv)) {
      returnedMessage.Append(NS_LITERAL_STRING("\n"));
      returnedMessage.Append(formattedString);
      returnedMessage.Append(NS_LITERAL_STRING("\n"));
    }
    else {
      returnedMessage.Append(NS_LITERAL_STRING("("));
      returnedMessage.Append(idU);
      returnedMessage.Append(NS_LITERAL_STRING(")"));
    }
  }

  return NS_OK;
}
Example #22
0
/** Display last NSPR/NSS error code and user readable message.
*/
static void print_nspr_error(void) {
  fprintf(stderr,"Error (%d): %s\n",PR_GetError(),PR_ErrorToString(PR_GetError(),PR_LANGUAGE_I_DEFAULT));
}