NSFC_PR_Open(const char *name,
             PRIntn flags,
             PRIntn mode)
{
    PRFileDesc *fd;

#ifdef ESTALE
    // Retry PR_Open() up to NSFC_ESTALE_RETRIES times if it returns ESTALE.
    // Bug 545152
    int retries = NSFC_ESTALE_RETRIES;
    do {
        fd = PR_Open(name, flags, mode);
    } while (!fd && PR_GetOSError() == ESTALE && retries--);
#else
    fd = PR_Open(name, flags, mode);
#endif

#ifdef XP_WIN32
    /* Work-around for NSPR error mapping deficiency */
    if ((fd == NULL) && (PR_GetError() == PR_UNKNOWN_ERROR) 
        && (PR_GetOSError() == ERROR_SHARING_VIOLATION))
        PR_SetError(PR_FILE_IS_BUSY_ERROR, ERROR_SHARING_VIOLATION);
#endif

    return fd;
}
예제 #2
0
nsresult ParseData(char* anInputStream,char* anOutputStream) {
  NS_ENSURE_ARG_POINTER(anInputStream);
  NS_ENSURE_ARG_POINTER(anOutputStream);
	
  nsresult result = NS_OK;

  // Create a parser
  nsCOMPtr<nsIParser> parser(do_CreateInstance(kParserCID, &result));
  if (NS_FAILED(result)) {
    printf("\nUnable to create a parser\n");
    return result;
  }
  // Create a sink
  nsCOMPtr<nsILoggingSink> sink(do_CreateInstance(kLoggingSinkCID, &result));
  if (NS_FAILED(result)) {
    printf("\nUnable to create a sink\n");
    return result;
  }

  PRFileDesc* in = PR_Open(anInputStream, PR_RDONLY, 0777);
  if (!in) {
    printf("\nUnable to open input file - %s\n", anInputStream);
    return result;
  }
  
  PRFileDesc* out = PR_Open(anOutputStream,
                            PR_CREATE_FILE|PR_TRUNCATE|PR_RDWR, 0777);
  if (!out) {
    printf("\nUnable to open output file - %s\n", anOutputStream);
    return result;
  }

  nsString stream;
  char buffer[1024] = {0}; // XXX Yikes!
  bool done = false;
  PRInt32 length = 0;
  while(!done) {
    length = PR_Read(in, buffer, sizeof(buffer));
    if (length != 0) {
      stream.Append(NS_ConvertUTF8toUTF16(buffer, length));
    }
    else {
      done=true;
    }
  }

  sink->SetOutputStream(out);
  parser->SetContentSink(sink);
  result = parser->Parse(stream, 0, NS_LITERAL_CSTRING("text/html"), true);
  
  PR_Close(in);
  PR_Close(out);

  return result;
}
예제 #3
0
/*
 * Serve_TransmitFile_Client
 *    Thread, started by the server, for serving a client connection.
 *    Trasmits a small file, with a header, and a large file, without
 *    a header
 */
static void
Serve_TransmitFile_Client(void *arg)
{
    Serve_Client_Param *scp = (Serve_Client_Param *) arg;
    PRFileDesc *sockfd;
    PRInt32 bytes;
    PRFileDesc *local_small_file_fd=NULL;
    PRFileDesc *local_large_file_fd=NULL;

    sockfd = scp->sockfd;
    local_small_file_fd = PR_Open(SMALL_FILE_NAME, PR_RDONLY,0);

    if (local_small_file_fd == NULL) {
        fprintf(stderr,"prsocket_test failed to open file for transmitting %s\n",
            SMALL_FILE_NAME);
        failed_already=1;
        goto done;
    }
    local_large_file_fd = PR_Open(LARGE_FILE_NAME, PR_RDONLY,0);

    if (local_large_file_fd == NULL) {
        fprintf(stderr,"prsocket_test failed to open file for transmitting %s\n",
            LARGE_FILE_NAME);
        failed_already=1;
        goto done;
    }
    bytes = PR_TransmitFile(sockfd, local_small_file_fd, small_file_header,
        SMALL_FILE_HEADER_SIZE, PR_TRANSMITFILE_KEEP_OPEN,
        PR_INTERVAL_NO_TIMEOUT);
    if (bytes != (SMALL_FILE_SIZE+ SMALL_FILE_HEADER_SIZE)) {
        fprintf(stderr,
            "prsocet_test: PR_TransmitFile failed: (%ld, %ld)\n",
            PR_GetError(), PR_GetOSError());
        failed_already=1;
    }
    bytes = PR_TransmitFile(sockfd, local_large_file_fd, NULL, 0,
        PR_TRANSMITFILE_CLOSE_SOCKET, PR_INTERVAL_NO_TIMEOUT);
    if (bytes != LARGE_FILE_SIZE) {
        fprintf(stderr,
            "prsocket_test: PR_TransmitFile failed: (%ld, %ld)\n",
            PR_GetError(), PR_GetOSError());
        failed_already=1;
    }
done:
    if (local_small_file_fd != NULL)
        PR_Close(local_small_file_fd);
    if (local_large_file_fd != NULL)
        PR_Close(local_large_file_fd);
}
예제 #4
0
int
ReadBuf(char *inFile, SECItem *item)
{
    int len;
    int ret;
    PRFileDesc* fd = PR_Open(inFile, PR_RDONLY, 0);
    if (NULL == fd) {
        SECU_PrintError("symkeyutil", "PR_Open failed");
	return -1;
    }

    len = GetLen(fd);
    if (len < 0) {
	SECU_PrintError("symkeyutil", "PR_GetOpenFileInfo failed");
	return -1;
    }
    item->data = (unsigned char *)PORT_Alloc(len);
    if (item->data == NULL) {
	fprintf(stderr,"Failed to allocate %d to read file %s\n",len,inFile);
	return -1;
    }

    ret = PR_Read(fd,item->data,item->len);
    if (ret < 0) {
	SECU_PrintError("symkeyutil", "PR_Read failed");
	PORT_Free(item->data);
	item->data = NULL;
	return -1;
    }
    PR_Close(fd);
    item->len = len;
    return 0;
}
예제 #5
0
static
nsresult
GenerateRandomBytes(uint32_t aSize,
                    uint8_t* _buffer)
{
  // On Windows, we'll use its built-in cryptographic API.
#if defined(XP_WIN)
  HCRYPTPROV cryptoProvider;
  BOOL rc = CryptAcquireContext(&cryptoProvider, 0, 0, PROV_RSA_FULL,
                                CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
  if (rc) {
    rc = CryptGenRandom(cryptoProvider, aSize, _buffer);
    (void)CryptReleaseContext(cryptoProvider, 0);
  }
  return rc ? NS_OK : NS_ERROR_FAILURE;

  // On Unix, we'll just read in from /dev/urandom.
#elif defined(XP_UNIX)
  NS_ENSURE_ARG_MAX(aSize, INT32_MAX);
  PRFileDesc* urandom = PR_Open("/dev/urandom", PR_RDONLY, 0);
  nsresult rv = NS_ERROR_FAILURE;
  if (urandom) {
    int32_t bytesRead = PR_Read(urandom, _buffer, aSize);
    if (bytesRead == static_cast<int32_t>(aSize)) {
      rv = NS_OK;
    }
    (void)PR_Close(urandom);
  }
  return rv;
#endif
}
예제 #6
0
int main(int argc, char **argv)
{


#ifdef XP_MAC
	SetupMacPrintfLog("pr_open_re.log");
#endif
	

	
    PR_STDIO_INIT();
	t1 = PR_Open("/usr/tmp/err02.tmp",  PR_RDWR, 0666);
	if (t1 == NULL) 
		if (PR_GetError() == PR_FILE_NOT_FOUND_ERROR) {

				printf ("error code is %d \n", PR_GetError());
				printf ("PASS\n");
				return 0;
		}
		else {
					printf ("error code is %d \n", PR_GetError());
					printf ("FAIL\n");
					return 1;
		}
}			
// Returns true if the contents of |file| match |contents|.
static PRBool CheckFileContents(nsILocalFile *file, const char *contents)
{
  nsCString nativePath;
  file->GetNativePath(nativePath);

  // Now read in the file contents and compare to the expected output
  PRFileInfo info;
  ASSERT_TRUE_RET(PR_GetFileInfo(nativePath.get(), &info) == PR_SUCCESS,
                  PR_FALSE);

  char *buf = new char[info.size + 1];
  ASSERT_TRUE_RET(buf, PR_FALSE);

  PRFileDesc *fd = PR_Open(nativePath.get(), PR_RDONLY, 0);
  ASSERT_TRUE_RET(fd, PR_FALSE);

  ASSERT_TRUE_RET(PR_Read(fd, buf, info.size) == info.size, PR_FALSE);
  PR_Close(fd);
  buf[info.size] = '\0';

  // Leave the file in place if the test failed
  ASSERT_TRUE_RET(!strcmp(buf, contents), PR_FALSE);
  PR_Delete(nativePath.get());
  delete[] buf;
  return PR_TRUE;
}
예제 #8
0
am_status_t Properties::store(const std::string& fileName) const
{
    am_status_t status = AM_SUCCESS;
    PRFileDesc *propFile;

    propFile = PR_Open(fileName.c_str(),
		       PR_WRONLY|PR_CREATE_FILE|PR_TRUNCATE, 0644);
    if (NULL != propFile) {
	PRUint32 rc = 0;

	for (const_iterator iter = begin(); iter != end(); ++iter) {
	    rc = PR_fprintf(propFile, "%s=%s\n", iter->first.c_str(),
			    iter->second.c_str());
	    if (static_cast<PRUint32>(-1) == rc) {
		break;
	    }
	}
	if (PR_SUCCESS != PR_Close(propFile) ||
	    static_cast<PRUint32>(-1) == rc) {
	    status = AM_NSPR_ERROR;
	}
    } else {
	status = AM_NSPR_ERROR;
    }

    return status;
}
예제 #9
0
nsresult
AutoMemMap::init(const char* filePath, int flags, int mode, PRFileMapProtect prot)
{
  MOZ_ASSERT(!fd);
  MOZ_ASSERT(!fileMap);
  MOZ_ASSERT(!addr);

  if (PR_GetFileInfo64(filePath, &fileInfo) != PR_SUCCESS)
    return NS_ERROR_FILE_NOT_FOUND;

  // Check if the file is too big to memmap.
  if (fileInfo.size > int64_t(UINT32_MAX))
    return NS_ERROR_INVALID_ARG;
  auto length = uint32_t(fileInfo.size);

  fd = PR_Open(filePath, flags, flags);
  if (!fd)
    return NS_ERROR_UNEXPECTED;

  fileMap = PR_CreateFileMap(fd, fileInfo.size, prot);
  if (!fileMap)
    return NS_ERROR_UNEXPECTED;

  addr = PR_MemMap(fileMap, 0, length);
  if (!addr)
    return NS_ERROR_UNEXPECTED;

  return NS_OK;
}
예제 #10
0
/**
 * ZIP_OpenArchive
 *
 * opens the named zip/jar archive and returns a handle that
 * represents the archive in other ZIP_ calls.
 *
 * @param   zipname   archive filename
 * @param   hZip      receives handle if archive opened OK
 * @return  status code
 */
PR_PUBLIC_API(PRInt32) ZIP_OpenArchive(const char * zipname, void** hZip)
{
  PRInt32 status;

  /*--- error check args ---*/
  if (hZip == 0)
    return ZIP_ERR_PARAM;

  /*--- NULL output to prevent use by bozos who don't check errors ---*/
  *hZip = 0;

  /*--- create and open the archive ---*/
  nsZipArchive* zip = new nsZipArchive();
  if (zip == 0)
    return ZIP_ERR_MEMORY;

  PRFileDesc * fd = PR_Open(zipname, PR_RDONLY, 0400);
  if (!fd) {
    delete zip;
    return ZIP_ERR_DISK;
  }

  status = zip->OpenArchive(fd);
  if (status == ZIP_OK)
    *hZip = static_cast<void*>(zip);
  else {
    delete zip;
    PR_Close(fd);
  }

  return status;
}
예제 #11
0
void RNG_FileForRNG(const char *filename)
{
    PRFileDesc *    file;
    int             nBytes;
    PRFileInfo      infoBuf;
    unsigned char   buffer[1024];

    if (PR_GetFileInfo(filename, &infoBuf) != PR_SUCCESS)
        return;

    RNG_RandomUpdate((unsigned char*)&infoBuf, sizeof(infoBuf));

    file = PR_Open(filename, PR_RDONLY, 0);
    if (file != NULL) {
        for (;;) {
            PRInt32 bytes = PR_Read(file, buffer, sizeof buffer);

            if (bytes <= 0)
                break;

            RNG_RandomUpdate(buffer, bytes);
            totalFileBytes += bytes;
            if (totalFileBytes > maxFileBytes)
                break;
        }

        PR_Close(file);
    }

    nBytes = RNG_GetNoise(buffer, 20);  // get up to 20 bytes
    RNG_RandomUpdate(buffer, nBytes);
}
예제 #12
0
void
db_put_dn(char *data_dn)
{
    int ret;
	char *db_path = DATABASE;
	char *db_path_bak = DATABASE_BACK;
	PRFileInfo64 info;
	PRFileDesc *prfd;
	PRInt32 data_sz;
	char *data_dnp = NULL;

	if(db_lock == NULL){
		db_lock = PR_NewLock();
	}
	PR_Lock(db_lock);
	/* if db_path is a directory, rename it */
	ret =  PR_GetFileInfo64(db_path, &info);
	if (PR_SUCCESS == ret) {
		if (PR_FILE_DIRECTORY == info.type) {    /* directory */
			ret =  PR_GetFileInfo64(db_path_bak, &info);
			if (PR_SUCCESS == ret) {
				if (PR_FILE_DIRECTORY != info.type) {    /* not a directory */
					PR_Delete(db_path_bak);
				}
			}
			PR_Rename(db_path, db_path_bak);
		}
	}

	/* open a file */
	if ((prfd = PR_Open(db_path, PR_RDWR | PR_CREATE_FILE | PR_APPEND, 0600)) == NULL ) {
		slapi_log_error(SLAPI_LOG_FATAL, DB_PLUGIN_NAME,
				"db: Could not open file \"%s\" for read/write; %d (%s)\n",
				db_path, PR_GetError(), slapd_pr_strerror(PR_GetError()));
		return;
	}

	data_dnp = slapi_ch_smprintf("%s\n", data_dn);
	data_sz = (PRInt32)strlen(data_dnp);

	ret = PR_Write(prfd, data_dnp, data_sz);
	if (ret == data_sz) {
		slapi_log_error(SLAPI_LOG_PLUGIN, DB_PLUGIN_NAME,
						"db: %s: key stored.\n", data_dn);
		ret = 0;
	} else  {
		slapi_log_error(SLAPI_LOG_FATAL, DB_PLUGIN_NAME,
				"db: Failed to store key \"%s\"; %d (%s)\n",
				data_dn, PR_GetError(), slapd_pr_strerror(PR_GetError()));
		ret = 1;
	}
    if(ret) {
		slapi_log_error(SLAPI_LOG_FATAL, DB_PLUGIN_NAME,
						"db: Error detected in db_put_dn \n");
    }
	slapi_ch_free_string(&data_dnp);
	PR_Close(prfd);
	PR_Unlock(db_lock);
	return;
}
예제 #13
0
CERTCertificate*
find_certificate(CERTCertDBHandle *handle, const char *name, PRBool ascii)
{
    CERTCertificate *cert = NULL;
    SECItem der;
    PRFileDesc *certFile;

    if (handle == NULL || name == NULL)
        return NULL;

    if (ascii == PR_FALSE) { 
        /* by default need to check if there is cert nick is given */
        cert = CERT_FindCertByNicknameOrEmailAddr (handle, (char *) name);
        if (cert != NULL)
            return cert;
    }

    certFile = PR_Open(name, PR_RDONLY, 0);
    if (certFile == NULL) {
        return NULL;
    }

    if (SECU_ReadDERFromFile(&der, certFile, ascii, PR_FALSE) == SECSuccess) {
        cert = CERT_DecodeCertFromPackage((char*)der.data, der.len);
        SECITEM_FreeItem(&der, PR_FALSE);
    }
    PR_Close(certFile);

    return cert;
}
예제 #14
0
void
dumpCertChain(CERTCertificate *cert, SECCertUsage usage)
{
    CERTCertificateList *certList;
    unsigned int count = 0;

    certList = CERT_CertChainFromCert(cert, usage, PR_TRUE);
    if (certList == NULL) {
        errWarn("CERT_CertChainFromCert");
        return;
    }

    for(count = 0; count < (unsigned int)certList->len; count++) {
        char certFileName[16];
        PRFileDesc *cfd;

        PR_snprintf(certFileName, sizeof certFileName, "cert.%03d",
                    count);
        cfd = PR_Open(certFileName, PR_WRONLY|PR_CREATE_FILE|PR_TRUNCATE, 
                      0664);
        if (!cfd) {
            PR_fprintf(PR_STDOUT,
                       "Error: couldn't save cert der in file '%s'\n",
                       certFileName);
        } else {
            PR_Write(cfd,  certList->certs[count].data,  certList->certs[count].len);
            PR_Close(cfd);
            PR_fprintf(PR_STDOUT, "Cert file %s was created.\n", certFileName);
        }
    }
    CERT_DestroyCertificateList(certList);
}
예제 #15
0
파일: prtrace.c 프로젝트: MekliCZ/positron
static PRFileDesc * InitializeRecording( void )
{
    char    *logFileName;
    PRFileDesc  *logFile;

    /* Self initialize, if necessary */
    if ( traceLock == NULL )
        _PR_InitializeTrace();

    PR_LOG( lm, PR_LOG_DEBUG,
        ("PR_RecordTraceEntries: begins"));

    logLostData = 0; /* reset at entry */
    logState = LogReset;

    /* Get the filename for the logfile from the environment */
    logFileName = PR_GetEnvSecure( "NSPR_TRACE_LOG" );
    if ( logFileName == NULL )
    {
        PR_LOG( lm, PR_LOG_ERROR,
            ("RecordTraceEntries: Environment variable not defined. Exiting"));
        return NULL;
    }
    
    /* Open the logfile */
    logFile = PR_Open( logFileName, PR_WRONLY | PR_CREATE_FILE, 0666 );
    if ( logFile == NULL )
    {
        PR_LOG( lm, PR_LOG_ERROR,
            ("RecordTraceEntries: Cannot open %s as trace log file. OS error: %ld", 
		logFileName, PR_GetOSError()));
        return NULL;
    }
    return logFile;
} /* end InitializeRecording() */
예제 #16
0
파일: nss.c 프로젝트: 3s3s/simple_server
static SECStatus nss_load_crl(const char* crlfilename)
{
  PRFileDesc *infile;
  PRFileInfo  info;
  SECItem filedata = { 0, NULL, 0 };
  SECItem crlDER = { 0, NULL, 0 };
  char *body;

  infile = PR_Open(crlfilename, PR_RDONLY, 0);
  if(!infile)
    return SECFailure;

  if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
    goto fail;

  if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
    goto fail;

  if(info.size != PR_Read(infile, filedata.data, info.size))
    goto fail;

  /* place a trailing zero right after the visible data */
  body = (char*)filedata.data;
  body[--filedata.len] = '\0';

  body = strstr(body, "-----BEGIN");
  if(body) {
    /* assume ASCII */
    char *trailer;
    char *begin = PORT_Strchr(body, '\n');
    if(!begin)
      begin = PORT_Strchr(body, '\r');
    if(!begin)
      goto fail;

    trailer = strstr(++begin, "-----END");
    if(!trailer)
      goto fail;

    /* retrieve DER from ASCII */
    *trailer = '\0';
    if(ATOB_ConvertAsciiToItem(&crlDER, begin))
      goto fail;

    SECITEM_FreeItem(&filedata, PR_FALSE);
  }
  else
    /* assume DER */
    crlDER = filedata;

  PR_Close(infile);
  return nss_cache_crl(&crlDER);

fail:
  PR_Close(infile);
  SECITEM_FreeItem(&filedata, PR_FALSE);
  return SECFailure;
}
예제 #17
0
/****************************************************************
 *
 * J z i p O p e n
 *
 * Opens a new ZIP file and creates a new ZIPfile structure to
 * control the process of installing files into a zip.
 */
ZIPfile *
JzipOpen(char *filename, char *comment)
{
    ZIPfile *zipfile;
    PRExplodedTime prtime;

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

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

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

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

    return zipfile;
}
static PKIX_PL_Cert *
createCert(char *inFileName)
{
        PKIX_PL_ByteArray *byteArray = NULL;
        void *buf = NULL;
        PRFileDesc *inFile = NULL;
        PKIX_UInt32 len;
        SECItem certDER;
        SECStatus rv;
        /* default: NULL cert (failure case) */
        PKIX_PL_Cert *cert = NULL;

        PKIX_TEST_STD_VARS();

        certDER.data = NULL;

        inFile = PR_Open(inFileName, PR_RDONLY, 0);

        if (!inFile){
                pkixTestErrorMsg = "Unable to open cert file";
                goto cleanup;
        } else {
                rv = SECU_ReadDERFromFile(&certDER, inFile, PR_FALSE);
                if (!rv){
                        buf = (void *)certDER.data;
                        len = certDER.len;

                        PKIX_TEST_EXPECT_NO_ERROR
                                (PKIX_PL_ByteArray_Create
                                (buf, len, &byteArray, plContext));

                        PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_Cert_Create
                                                (byteArray, &cert, plContext));

                        SECITEM_FreeItem(&certDER, PR_FALSE);
                } else {
                        pkixTestErrorMsg = "Unable to read DER from cert file";
                        goto cleanup;
                }
        }

cleanup:

        if (inFile){
                PR_Close(inFile);
        }

        if (PKIX_TEST_ERROR_RECEIVED){
                SECITEM_FreeItem(&certDER, PR_FALSE);
        }

        PKIX_TEST_DECREF_AC(byteArray);

        PKIX_TEST_RETURN();

        return (cert);
}
예제 #19
0
static int
xmlSecNssAppReadSECItem(SECItem *contents, const char *fn) {
    PRFileInfo info;
    PRFileDesc *file = NULL;
    PRInt32 numBytes;
    PRStatus prStatus;
    int ret = -1;

    xmlSecAssert2(contents != NULL, -1);
    xmlSecAssert2(fn != NULL, -1);

    file = PR_Open(fn, PR_RDONLY, 00660);
    if (file == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "PR_Open",
                    XMLSEC_ERRORS_R_IO_FAILED,
                    "filename=%s",
                    xmlSecErrorsSafeString(fn));
        goto done;
    }

    prStatus = PR_GetOpenFileInfo(file, &info);
    if (prStatus != PR_SUCCESS) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "PR_GetOpenFileInfo",
                    XMLSEC_ERRORS_R_IO_FAILED,
                    "filename=%s",
                    xmlSecErrorsSafeString(fn));
        goto done;
    }

    contents->data = 0;
    if (!SECITEM_AllocItem(NULL, contents, info.size)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "SECITEM_AllocItem",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }

    numBytes = PR_Read(file, contents->data, info.size);
    if (numBytes != info.size) {
        SECITEM_FreeItem(contents, PR_FALSE);
        goto done;
    }

    ret = 0;
done:
    if (file) {
        PR_Close(file);
    }

    return (ret);
}
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() */
static void InitialSetup(void)
{
	PRUintn	i;
	PRInt32 nWritten, rv;
	
	t1 = PR_Open("t1.tmp", PR_CREATE_FILE | PR_RDWR, 0);
	PR_ASSERT(t1 != NULL);	
	
	for (i=0; i<TBSIZE; i++)
		tbuf[i] = i;
		
	nWritten = PR_Write((PRFileDesc*)t1, tbuf, TBSIZE);
	PR_ASSERT(nWritten == TBSIZE);	
   		
	rv = PR_Seek(t1,0,PR_SEEK_SET);
	PR_ASSERT(rv == 0);	

   	t2 = PR_Open("t2.tmp", PR_CREATE_FILE | PR_RDWR, 0);
	PR_ASSERT(t2 != NULL);	
}
예제 #22
0
int main(int argc, char **argv)
{
  if (NSS_NoDB_Init(NULL) != SECSuccess) {
    printf(" >>> NSS_NoDB_Init() failed.\n");
    return 1;
  }

  if (argc < 3) {
    printf(" >>> I need a DER encoded file to read and have to know what to do with it [decode, private]!\n");
    return 1;
  }

  PRFileDesc* file = PR_Open(argv[1], PR_RDONLY, 0);

  SECItem data = {0, NULL, 0};
  if (SECU_ReadDERFromFile(&data, file, PR_FALSE, PR_FALSE) != SECSuccess) {
    printf(" >>> SECU_ReadDERFromFile() failed.\n");
    return 1;
  }
  PR_Close(file);

  if (strcmp(argv[2], "decode") == 0) {
    CERTCertificate *cert = CERT_DecodeCertFromPackage((char*)data.data, data.len);
    if (cert){
      printf(" >>> read cert!\n");
      printf(" >>> SN: %s\n", cert->subjectName);
      printf(" >>> IN: %s\n", cert->issuerName);
      CERT_DestroyCertificate(cert);
    } else {
      printf(" >>> CERT_DecodeCertFromPackage failed.\n");
      SECITEM_FreeItem(&data, PR_FALSE);
      return 1;
    }
  }

  if (argv[2] == "private") {
    PK11SlotInfo* slot = PK11_GetInternalSlot();
    if (!slot) {
      printf(" >>> PK11_GetInternalSlot() failed.\n");
      SECITEM_FreeItem(&data, PR_FALSE);
      return 1;
    }

    SECKEYPrivateKey* privKey;
    if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, &data, NULL, NULL, PR_FALSE, PR_FALSE, KU_ALL, &privKey, NULL) != SECSuccess) {
      printf(" >>> PK11_ImportDERPrivateKeyInfoAndReturnKey() failed.\n");
      SECITEM_FreeItem(&data, PR_FALSE);
      return 1;
    }
  }

  printf(" !!! Done.\n");
  return 0;
}
예제 #23
0
PR_IMPLEMENT(PRBool) PR_SetLogFile(const char *file)
{
#ifdef _PR_USE_STDIO_FOR_LOGGING
    FILE *newLogFile;

#ifdef XP_PC
    if ( strcmp( file, "WinDebug") == 0)
    {
        newLogFile = WIN32_DEBUG_FILE;
    }
    else
#endif
    {
        const char *mode = appendToLog ? "a" : "w";
        newLogFile = fopen(file, mode);
        if (!newLogFile)
            return PR_FALSE;

#ifndef WINCE  /* _IONBF does not exist in the Windows Mobile 6 SDK. */
        /* We do buffering ourselves. */
        setvbuf(newLogFile, NULL, _IONBF, 0);
#endif
    }
    if (logFile
        && logFile != stdout
        && logFile != stderr
#ifdef XP_PC
        && logFile != WIN32_DEBUG_FILE
#endif
        ) {
        fclose(logFile);
    }
    logFile = newLogFile;
    return PR_TRUE;
#else
    PRFileDesc *newLogFile;
    PRIntn flags = PR_WRONLY|PR_CREATE_FILE;
    if (appendToLog) {
        flags |= PR_APPEND;
    } else {
        flags |= PR_TRUNCATE;
    }

    newLogFile = PR_Open(file, flags, 0666);
    if (newLogFile) {
        if (logFile && logFile != _pr_stdout && logFile != _pr_stderr) {
            PR_Close(logFile);
        }
        logFile = newLogFile;
    }
    return (PRBool) (newLogFile != 0);
#endif /* _PR_USE_STDIO_FOR_LOGGING */
}
예제 #24
0
CERTCertificate *
getCert(const char *name, PRBool isAscii, const char * progName)
{
    CERTCertificate * cert;
    CERTCertDBHandle *defaultDB;
    PRFileDesc*     fd;
    SECStatus       rv;
    SECItem         item        = {0, NULL, 0};

    defaultDB = CERT_GetDefaultCertDB();

    /* First, let's try to find the cert in existing DB. */
    cert = CERT_FindCertByNicknameOrEmailAddr(defaultDB, name);
    if (cert) {
        return cert;
    }

    /* Don't have a cert with name "name" in the DB. Try to
     * open a file with such name and get the cert from there.*/
    fd = PR_Open(name, PR_RDONLY, 0777); 
    if (!fd) {
	PRIntn err = PR_GetError();
    	fprintf(stderr, "open of %s failed, %d = %s\n", 
	        name, err, SECU_Strerror(err));
	return cert;
    }

    rv = SECU_ReadDERFromFile(&item, fd, isAscii);
    PR_Close(fd);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
	return cert;
    }

    if (!item.len) { /* file was empty */
	fprintf(stderr, "cert file %s was empty.\n", name);
	return cert;
    }

    cert = CERT_NewTempCertificate(defaultDB, &item, 
                                   NULL     /* nickname */, 
                                   PR_FALSE /* isPerm */, 
				   PR_TRUE  /* copyDER */);
    if (!cert) {
	PRIntn err = PR_GetError();
	fprintf(stderr, "couldn't import %s, %d = %s\n",
	        name, err, SECU_Strerror(err));
    }
    PORT_Free(item.data);
    return cert;
}
예제 #25
0
void 
debug_test(SECItem *src, char *filePath)
{
    PRFileDesc *fileDesc;

    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 
			0666);
    if (fileDesc == NULL) {
        printf ("Could not cretae file %s.\n", filePath);
	return;
    }
    PR_Write(fileDesc, src->data, src->len);
    
}
static int
ReadSingleFile(const char *filename)
{
    PRFileDesc *    file;
    unsigned char   buffer[1024];

    file = PR_Open(filename, PR_RDONLY, 0);
    if (file != NULL) {
	while (PR_Read(file, buffer, sizeof buffer) > 0)
	    ;
        PR_Close(file);
    }
    return (file != NULL);
}
예제 #27
0
파일: nametable.c 프로젝트: Firstyear/ds
/* write a nametable out into a file */
int nt_save(NameTable *nt, const char *filename)
{
    PRFileDesc *fd;
    PRUint32 i;

    fd = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 0644);
    if (!fd) return 0;

    for (i = 0; i < nt->size; i++) {
	PR_Write(fd, nt->data[i], strlen(nt->data[i]));
	PR_Write(fd, "\n", 1);
    }
    PR_Close(fd);
    return 1;
}
예제 #28
0
PRStatus TimelineInit(void)
{
    char *timeStr;
    char *fileName;
    PRInt32 secs, msecs;
    PRFileDesc *fd;
    PRInt64 tmp1, tmp2;

    PRStatus status = PR_NewThreadPrivateIndex( &gTLSIndex, ThreadDestruct );
    NS_WARN_IF_FALSE(status==0, "TimelineService could not allocate TLS storage.");

    timeStr = PR_GetEnv("NS_TIMELINE_INIT_TIME");
#ifdef XP_MAC    
    initInterval = PR_IntervalNow();
#endif
    // NS_TIMELINE_INIT_TIME only makes sense for the main thread, so if it
    // exists, set it there.  If not, let normal thread management code take
    // care of setting the init time.
    if (timeStr != NULL && 2 == PR_sscanf(timeStr, "%d.%d", &secs, &msecs)) {
        PRTime &initTime = GetThisThreadData()->initTime;
        LL_MUL(tmp1, (PRInt64)secs, 1000000);
        LL_MUL(tmp2, (PRInt64)msecs, 1000);
        LL_ADD(initTime, tmp1, tmp2);
#ifdef XP_MAC
        initInterval -= PR_MicrosecondsToInterval(
            (PRUint32)(PR_Now() - initTime));
#endif
    }
    // Get the log file.
#ifdef XP_MAC
    fileName = "timeline.txt";
#else
    fileName = PR_GetEnv("NS_TIMELINE_LOG_FILE");
#endif
    if (fileName != NULL
        && (fd = PR_Open(fileName, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                         0666)) != NULL) {
        timelineFD = fd;
        PR_fprintf(fd,
                   "NOTE: due to asynchrony, the indentation that you see does"
                   " not necessarily correspond to nesting in the code.\n\n");
    }

    // Runtime disable of timeline
    if (PR_GetEnv("NS_TIMELINE_ENABLE"))
        gTimelineDisabled = PR_FALSE;
    return PR_SUCCESS;
}
예제 #29
0
파일: prlog.c 프로젝트: soubok/libset
PR_IMPLEMENT(PRBool) PR_SetLogFile(const char *file)
{
#ifdef _PR_USE_STDIO_FOR_LOGGING
    FILE *newLogFile;

#ifdef XP_PC
    if ( strcmp( file, "WinDebug") == 0)
    {
        newLogFile = WIN32_DEBUG_FILE;
    }
    else
#endif
    {
        newLogFile = fopen(file, "w");
        if (!newLogFile)
            return PR_FALSE;

        /* We do buffering ourselves. */
        setvbuf(newLogFile, NULL, _IONBF, 0);
    }
    if (logFile
        && logFile != stdout
        && logFile != stderr
#ifdef XP_PC
        && logFile != WIN32_DEBUG_FILE
#endif
        ) {
        fclose(logFile);
    }
    logFile = newLogFile;
    return PR_TRUE;
#else
    PRFileDesc *newLogFile;

    newLogFile = PR_Open(file, PR_WRONLY|PR_CREATE_FILE|PR_TRUNCATE, 0666);
    if (newLogFile) {
        if (logFile && logFile != _pr_stdout && logFile != _pr_stderr) {
            PR_Close(logFile);
        }
        logFile = newLogFile;
#if defined(XP_MAC)
        SetLogFileTypeCreator(file);
#endif
    }
    return (PRBool) (newLogFile != 0);
#endif /* _PR_USE_STDIO_FOR_LOGGING */
}
예제 #30
0
PRFileDesc *
CallPROpenUsingFileURL(char *fileURL, PRIntn flags, PRIntn mode)
{
	PRFileDesc* result = NULL;
	const char *path;

	char *escapedPath = unescapeURL(fileURL);
	path = convertFileURLToNSPRCopaceticPath(escapedPath);

	if (path != NULL)	{
		result = PR_Open(path, flags, mode);
	}

	if (escapedPath != NULL)	freeMem(escapedPath);

	return result;
}