NS_IMETHODIMP
nsFileProtocolHandler::ReadURLFile(nsIFile* aFile, nsIURI** aURI)
{
    nsresult rv;

    nsCOMPtr<nsILocalFileOS2> os2File (do_QueryInterface(aFile, &rv));
    if (NS_FAILED(rv))
        return NS_ERROR_NOT_AVAILABLE;

    // see if this file is a WPS UrlObject
    PRBool isUrl;
    rv = os2File->IsFileType(NS_LITERAL_CSTRING("UniformResourceLocator"),
                             &isUrl);
    if (NS_FAILED(rv) || !isUrl)
        return NS_ERROR_NOT_AVAILABLE;

    // if so, open it & get its size
    PRFileDesc *file;
    rv = os2File->OpenNSPRFileDesc(PR_RDONLY, 0, &file);
    if (NS_FAILED(rv))
        return NS_ERROR_NOT_AVAILABLE;

    PRInt64 fileSize;
    os2File->GetFileSize(&fileSize);
    rv = NS_ERROR_NOT_AVAILABLE;

    // get a buffer, read the entire file, then create
    // an nsURI;  we assume the string is already escaped
    char * buffer = (char*)NS_Alloc(fileSize+1);
    if (buffer) {
        PRInt32 cnt = PR_Read(file, buffer, fileSize);
        if (cnt > 0) {
            buffer[cnt] = '\0';
            if (NS_SUCCEEDED(NS_NewURI(aURI, nsDependentCString(buffer))))
                rv = NS_OK;
        }
        NS_Free(buffer);
    }
    PR_Close(file);

    return rv;
}
Example #2
0
void
beginReadingRDFFile (RDFFile file)
{
	char		*url;
	int		method = 0;

#ifndef MOZILLA_CLIENT

   /* If standalone, we just use  to open the file */
   NET_StreamClass stream;
   PRFileDesc *fd;
   PRFileInfo fi;
   PRBool bSuccess = FALSE;
    
   url = file->url;
   fd = CallPROpenUsingFileURL(url, PR_RDONLY, 0);
   if(fd)
   {
      if(PR_GetOpenFileInfo(fd, &fi) == PR_SUCCESS)
      {
         char* buf = malloc(fi.size);
         if(PR_Read(fd, buf, fi.size))
         {
            stream.data_object = file;
            if(parseNextRDFXMLBlob (&stream, buf, fi.size))
               bSuccess = TRUE;
         }
         free(buf);
      }
      PR_Close(fd);
   }
   if(bSuccess == TRUE)
      rdf_complete(&stream);
#else

	url = file->url;
	if (file->fileType == ES_RT)	method = URL_INDEX_METHOD;
	rdf_GetURL (gRDFMWContext(file->db), method, NULL, file);

#endif
}
Example #3
0
//---------------------------------------------
// nsZipArchive::CopyItemToDisk
//---------------------------------------------
nsresult
nsZipArchive::CopyItemToDisk(PRUint32 itemSize, PRUint32 itemCrc, PRFileDesc* outFD)
/*
 * This function copies an archive item to disk, to the
 * file specified by outFD. If outFD is zero, the extracted data is
 * not written, only checked for CRC, so this is in effect same as 'Test'.
 */
{
  PRUint32    chunk, pos, crc;
  char buf[ZIP_BUFLEN];

  //-- initialize crc
  crc = crc32(0L, Z_NULL, 0);

  //-- copy chunks until file is done
  for (pos = 0; pos < itemSize; pos += chunk)
  {
    chunk = (itemSize - pos < ZIP_BUFLEN) ? (itemSize - pos) : ZIP_BUFLEN;
    
    if (PR_Read(mFd, buf, chunk) != (READTYPE)chunk)
    {
      //-- unexpected end of data in archive
      return ZIP_ERR_CORRUPT;
    }

    //-- incrementally update crc32
    crc = crc32(crc, (const unsigned char*)buf, chunk);

    if (outFD && PR_Write(outFD, buf, chunk) < (READTYPE)chunk)
    {
      //-- Couldn't write all the data (disk full?)
      return ZIP_ERR_DISK;
    }
  }

  //-- verify crc32
  if (crc != itemCrc)
      return ZIP_ERR_CORRUPT;

  return ZIP_OK;
}
Example #4
0
void * _MD_MemMap(PRFileMap *fmap, PROffset64 offset, PRUint32 len)
{
    PRUint32 rv;
    void *addr;

    /* prevent mappings beyond EOF + remainder of page */
    if (offset + len > fmap->md.maxExtent) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return NULL;
    }
    if (PR_Seek64(fmap->fd, offset, PR_SEEK_SET) == -1) {
        return NULL;
    }
    /* try for high memory, fall back to low memory if hi-mem fails */
#if defined(MOZ_OS2_HIGH_MEMORY)
    rv = DosAllocMem(&addr, len, OBJ_ANY | PAG_COMMIT | PAG_READ | PAG_WRITE);
    if (rv)
#endif
    {
        rv = DosAllocMem(&addr, len, PAG_COMMIT | PAG_READ | PAG_WRITE);
        if (rv) {
            PR_SetError(PR_OUT_OF_MEMORY_ERROR, rv);
            return NULL;
        }
    }
    if (PR_Read(fmap->fd, addr, len) == -1) {
        DosFreeMem(addr);
        return NULL;
    }
    /* don't permit writes if readonly */
    if (fmap->prot == PR_PROT_READONLY) {
        rv = DosSetMem(addr, len, PAG_READ);
        if (rv) {
            DosFreeMem(addr);
            PR_SetError(PR_UNKNOWN_ERROR, rv);
            return NULL;
        }
    }
    return addr;
}
Example #5
0
int
readInputFile(const char * filename, SECItem * result)
{
  PRFileDesc *file /* = PR_OpenFile(input_file, 0) */;
  PRFileInfo info;
  PRStatus s;
  PRInt32 count;
  int retval = -1;

  file = PR_Open(filename, PR_RDONLY, 0);
  if (!file) {
    if (verbose) PR_fprintf(pr_stderr, "Open of file %s failed\n", filename);
    goto loser;
  }

  s = PR_GetOpenFileInfo(file, &info);
  if (s != PR_SUCCESS) {
    if (verbose) PR_fprintf(pr_stderr, "File info operation failed\n");
    goto file_loser;
  }

  result->len = info.size;
  result->data = (unsigned char *)PR_Malloc(result->len);
  if (!result->data) {
    if (verbose) PR_fprintf(pr_stderr, "Allocation of buffer failed\n");
    goto file_loser;
  }

  count = PR_Read(file, result->data, result->len);
  if (count != result->len) {
    if (verbose) PR_fprintf(pr_stderr, "Read failed\n");
    goto file_loser;
  }
  retval = 0;

file_loser:
  PR_Close(file);
loser:
  return retval;
}
Example #6
0
char *getNSSPassword(PK11SlotInfo *slot, PRBool retry, void *arg)
{
     secuPWData *pwdInfo = (secuPWData *)arg;
     PRFileDesc *fd;
     PRInt32 nb; /*number of bytes*/
     char* password;
     const long maxPwdFileSize = 4096;

     if(retry) return 0;
     

     if(pwdInfo->source == PW_FROMFILE) {
     	if(pwdInfo->data !=NULL) {
        fd = PR_Open(pwdInfo->data, PR_RDONLY, 0);
			if (!fd) {
			openswan_log("No password file \"%s\" exists.", pwdInfo->data);
			return 0;
		    }

	    password=PORT_ZAlloc(maxPwdFileSize);
	    nb = PR_Read(fd, password, maxPwdFileSize);
	    PR_Close(fd);

			if (nb == 0) {
        	openswan_log("password file contains no data");
        	PORT_Free(password);
        	return 0;
        	}
	    password[nb-1]='\0'; 
        openswan_log("Password passed to NSS is %s", password);
        return password;
	    }
	    else {
	    openswan_log("File with Password to NSS DB is not provided");
        return 0;
	    }
     }
openswan_log("nss password source is not specified as file");
return 0;
}
NS_IMETHODIMP
nsTemporaryFileInputStream::ReadSegments(nsWriteSegmentFun writer,
                                         void *            closure,
                                         uint32_t          count,
                                         uint32_t *        result)
{
  NS_ASSERTION(result, "null ptr");
  NS_ASSERTION(mStartPos <= mEndPos, "bad stream state");
  *result = 0;

  if (mClosed) {
    return NS_BASE_STREAM_CLOSED;
  }

  mozilla::MutexAutoLock lock(mFileDescOwner->FileMutex());
  PR_Seek64(mFileDescOwner->mFD, mStartPos, PR_SEEK_SET);

  count = std::min(count, uint32_t(mEndPos - mStartPos));
  uint32_t remainBufCount = count;

  char buf[4096];
  while (remainBufCount > 0) {
    uint32_t bufCount = std::min(remainBufCount, (uint32_t)sizeof(buf));
    int32_t read_result = PR_Read(mFileDescOwner->mFD, buf, bufCount);
    if (read_result < 0) {
      return NS_ErrorAccordingToNSPR();
    }
    uint32_t write_result = 0;
    nsresult rv = writer(this, closure, buf,
                         count - remainBufCount, bufCount, &write_result);
    remainBufCount -= bufCount;
    if (NS_SUCCEEDED(rv)) {
      NS_ASSERTION(write_result <= bufCount,
                   "writer should not write more than we asked it to write");
    }
    mStartPos += bufCount;
  }
  *result = count;
  return NS_OK;
}
Example #8
0
int ssl_read(void *conn, char *buf, int len)
{
	int st;
	PRErrorCode PR_err;

	if (!((struct scd *)conn)->established) {
		ssl_errno = SSL_NOHANDSHAKE;
		return -1;
	}

	st = PR_Read(((struct scd *)conn)->prfd, buf, len);
	PR_err = PR_GetError();

	ssl_errno = SSL_OK;
	if (PR_err == PR_WOULD_BLOCK_ERROR)
		ssl_errno = SSL_AGAIN;

	if (SSLDEBUG && getenv("BITLBEE_DEBUG") && st > 0)
		len = write(STDERR_FILENO, buf, st);

	return st;
}
Example #9
0
nsresult
FileLocation::Data::Copy(char* aBuf, uint32_t aLen)
{
  if (mFd) {
    for (uint32_t totalRead = 0; totalRead < aLen;) {
      int32_t read = PR_Read(mFd, aBuf + totalRead,
                             XPCOM_MIN(aLen - totalRead, uint32_t(INT32_MAX)));
      if (read < 0) {
        return NS_ErrorAccordingToNSPR();
      }
      totalRead += read;
    }
    return NS_OK;
  } else if (mItem) {
    nsZipCursor cursor(mItem, mZip, reinterpret_cast<uint8_t*>(aBuf),
                       aLen, true);
    uint32_t readLen;
    cursor.Copy(&readLen);
    return (readLen == aLen) ? NS_OK : NS_ERROR_FILE_CORRUPTED;
  }
  return NS_ERROR_NOT_INITIALIZED;
}
Example #10
0
static nsresult
ReadFromFile(nsIFile* aPath,
             const nsACString& aFileName,
             nsACString& aOutData,
             int32_t aMaxLength)
{
  nsCOMPtr<nsIFile> path;
  nsresult rv = aPath->Clone(getter_AddRefs(path));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = path->AppendNative(aFileName);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  PRFileDesc* f = nullptr;
  rv = path->OpenNSPRFileDesc(PR_RDONLY | PR_CREATE_FILE, PR_IRWXU, &f);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  auto size = PR_Seek(f, 0, PR_SEEK_END);
  PR_Seek(f, 0, PR_SEEK_SET);

  if (size > aMaxLength) {
    return NS_ERROR_FAILURE;
  }
  aOutData.SetLength(size);

  auto len = PR_Read(f, aOutData.BeginWriting(), size);
  PR_Close(f);
  if (NS_WARN_IF(len != size)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}
Example #11
0
NS_IMETHODIMP
nsFileInputStream::Read(char* aBuf, PRUint32 aCount, PRUint32* aResult)
{
    if (!mFD) {
        *aResult = 0;
        return NS_OK;
    }

    PRInt32 bytesRead = PR_Read(mFD, aBuf, aCount);
    if (bytesRead == -1) {
        return NS_ErrorAccordingToNSPR();
    }
    // Check if we're at the end of file and need to close
    if (mBehaviorFlags & CLOSE_ON_EOF) {
        if (bytesRead == 0) {
            Close();
        }
    }

    *aResult = bytesRead;
    return NS_OK;
}
Example #12
0
int NrSocket::read(void* buf, size_t maxlen, size_t *len) {
  ASSERT_ON_THREAD(ststhread_);
  int _status;
  int32_t status;

  if (!connect_invoked_)
    ABORT(R_FAILED);

  status = PR_Read(fd_, buf, maxlen);
  if (status < 0) {
    if (PR_GetError() == PR_WOULD_BLOCK_ERROR)
      ABORT(R_WOULDBLOCK);
    ABORT(R_IO_ERROR);
  }
  if (status == 0)
    ABORT(R_EOD);

  *len = (size_t)status;  // Guaranteed to be > 0
  _status = 0;
abort:
  return(_status);
}
Example #13
0
SECStatus
secu_StdinToItem(SECItem *dst)
{
    unsigned char buf[1000];
    PRInt32 numBytes;
    PRBool notDone = PR_TRUE;

    dst->len = 0;
    dst->data = NULL;

    while (notDone) {
        numBytes = PR_Read(PR_STDIN, buf, sizeof(buf));

        if (numBytes < 0) {
            return SECFailure;
        }

        if (numBytes == 0)
            break;

        if (dst->data) {
            unsigned char *p = dst->data;
            dst->data = (unsigned char *)PORT_Realloc(p, dst->len + numBytes);
            if (!dst->data) {
                PORT_Free(p);
            }
        } else {
            dst->data = (unsigned char *)PORT_Alloc(numBytes);
        }
        if (!dst->data) {
            return SECFailure;
        }
        PORT_Memcpy(dst->data + dst->len, buf, numBytes);
        dst->len += numBytes;
    }

    return SECSuccess;
}
Example #14
0
/*
 * replacement for fgets
 * This isn't like the real fgets.  It fills in 's' but strips off any
 * trailing linefeed character(s).  The return value is 0 if it went
 * okay.
 */
int PR_GetLine(PRFileDesc *fd, char *s, unsigned int n)
{
    PRInt32 start, newstart;
    int x;
    char *p;

    /* grab current location in file */
    start = PR_Seek(fd, 0, PR_SEEK_CUR);
    x = PR_Read(fd, s, n-1);
    if (x <= 0) return 1;   /* EOF or other error */
    s[x] = 0;
    p = strchr(s, '\n');
    if (p == NULL) p = strchr(s, '\r');
    if (p == NULL) {
        /* assume there was one anyway */
        return 0;
    }
    *p = 0;
    newstart = start+strlen(s)+1;
    if ((p != s) && (*(p-1) == '\r')) *(p-1) = 0;
    PR_Seek(fd, newstart, PR_SEEK_SET);
    return 0;
}
nsresult
nsEmbedChromeRegistry::ReadChromeRegistry()
{
    nsresult rv;
    nsCOMPtr<nsIProperties> directoryService =
        do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsILocalFile> listFile;
    rv = directoryService->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsILocalFile),
                               getter_AddRefs(listFile));
    if (NS_FAILED(rv)) return rv;

    rv = listFile->AppendRelativeNativePath(NS_LITERAL_CSTRING("installed-chrome.txt"));
    if (NS_FAILED(rv)) return rv;

    PRFileDesc *file;
    rv = listFile->OpenNSPRFileDesc(PR_RDONLY, 0, &file);
    if (NS_FAILED(rv)) return rv;

    PRFileInfo finfo;

    if (PR_GetOpenFileInfo(file, &finfo) == PR_SUCCESS) {
        char *dataBuffer = new char[finfo.size+1];
        if (dataBuffer) {
            PRInt32 bufferSize = PR_Read(file, dataBuffer, finfo.size);
            if (bufferSize > 0) {
                dataBuffer[bufferSize] = '\r';
                rv = ProcessNewChromeBuffer(dataBuffer, bufferSize);
            }
            delete [] dataBuffer;
        }
    }
    PR_Close(file);

    return rv;
}
Example #16
0
//---------------------------------------------
// nsZipArchive::SeekToItem
//---------------------------------------------
nsresult  nsZipArchive::SeekToItem(nsZipItem* aItem, PRFileDesc* aFd)
{
  PR_ASSERT (aItem);

  //-- the first time an item is used we need to calculate its offset
  if (!aItem->hasDataOffset)
  {
    //-- read local header to get variable length values and calculate
    //-- the real data offset
    //--
    //-- NOTE: extralen is different in central header and local header
    //--       for archives created using the Unix "zip" utility. To set
    //--       the offset accurately we need the _local_ extralen.
    if (!ZIP_Seek(aFd, aItem->headerOffset, PR_SEEK_SET))
      return ZIP_ERR_CORRUPT;

    ZipLocal   Local;
    if ((PR_Read(aFd, (char*)&Local, ZIPLOCAL_SIZE) != (READTYPE) ZIPLOCAL_SIZE) || 
        (xtolong(Local.signature) != LOCALSIG))
    {
      //-- read error or local header not found
      return ZIP_ERR_CORRUPT;
    }

    aItem->dataOffset = aItem->headerOffset +
                        ZIPLOCAL_SIZE +
                        xtoint(Local.filename_len) +
                        xtoint(Local.extrafield_len);
    aItem->hasDataOffset = PR_TRUE;
  }

  //-- move to start of file in archive
  if (!ZIP_Seek(aFd, aItem->dataOffset, PR_SEEK_SET))
    return  ZIP_ERR_CORRUPT;

  return ZIP_OK;
}
Example #17
0
bool
PollableEvent::Clear()
{
  // necessary because of the "dont signal on socket thread" optimization
  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

  SOCKET_LOG(("PollableEvent::Clear\n"));
  mSignaled = false;
  if (!mReadFD) {
    SOCKET_LOG(("PollableEvent::Clear mReadFD is null\n"));
    return false;
  }
  char buf[2048];
  int32_t status = PR_Read(mReadFD, buf, 2048);
  SOCKET_LOG(("PollableEvent::Signal PR_Read %d\n", status));

  if (status == 1) {
    return true;
  }
  if (status == 0) {
    SOCKET_LOG(("PollableEvent::Clear EOF!\n"));
    return false;
  }
  if (status > 1) {
    MOZ_ASSERT(false);
    SOCKET_LOG(("PollableEvent::Clear Unexpected events\n"));
    Clear();
    return true;
  }
  PRErrorCode code = PR_GetError();
  if (code == PR_WOULD_BLOCK_ERROR) {
    return true;
  }
  SOCKET_LOG(("PollableEvent::Clear unexpected error %d\n", code));
  return false;
}
Example #18
0
static nsresult
GetFileContents(nsIFile* aFile, nsACString& data)
{
  nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(aFile);
  NS_ENSURE_TRUE(localFile, NS_ERROR_FAILURE);

  PRFileDesc* fd;
  nsresult rv = localFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_OK;
  PRInt32 filesize = PR_Available(fd);
  if (filesize <= 0) {
    rv = NS_ERROR_FILE_NOT_FOUND;
  }
  else {
    data.SetLength(filesize);
    if (PR_Read(fd, data.BeginWriting(), filesize) == -1) {
      rv = NS_ERROR_FAILURE;
    }
  }
  PR_Close(fd);
  return rv;
}
Example #19
0
/**************************************************************************
 *
 * P R _ f g e t s
 *
 * fgets implemented with NSPR.
 */
static char*
PR_fgets(char *buf, int size, PRFileDesc *file)
{
    int i;
    int status;
    char c;

    i=0;
    while(i < size-1) {
        status = PR_Read(file, (void*) &c, 1);
        if(status==-1) {
            return NULL;
        } else if(status==0) {
            break;
        }
        buf[i++] = c;
        if(c=='\n') {
            break;
        }
    }
    buf[i]='\0';

    return buf;
}
Example #20
0
/**
 * Reads configuration file and puts name value
 * pair into the global hashtable.
 */
static int ReadLine(PRFileDesc *f, char *buf, int buf_len, int *removed_return)
{
       char *cur = buf;
       int sum = 0;
       PRInt32 rc;

       *removed_return = 0;
       while (1) {
         rc = PR_Read(f, cur, 1);
         if (rc == -1 || rc == 0)
             break;
         if (*cur == '\r') {
             continue;
         }
         if (*cur == '\n') {
             *cur = '\0';
             *removed_return = 1;
             break;
         }
         sum++;
         cur++;
       }
       return sum;
}
Example #21
0
nsresult nsProfileLock::Lock(nsIFile* aProfileDir,
                             nsIProfileUnlocker* *aUnlocker)
{
#if defined (XP_MACOSX)
    NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock");
    NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "parent.lock");
#elif defined (XP_UNIX)
    NS_NAMED_LITERAL_STRING(OLD_LOCKFILE_NAME, "lock");
    NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, ".parentlock");
#else
    NS_NAMED_LITERAL_STRING(LOCKFILE_NAME, "parent.lock");
#endif

    nsresult rv;
    if (aUnlocker)
        *aUnlocker = nullptr;

    NS_ENSURE_STATE(!mHaveLock);

    bool isDir;
    rv = aProfileDir->IsDirectory(&isDir);
    if (NS_FAILED(rv))
        return rv;
    if (!isDir)
        return NS_ERROR_FILE_NOT_DIRECTORY;

    nsCOMPtr<nsIFile> lockFile;
    rv = aProfileDir->Clone(getter_AddRefs(lockFile));
    if (NS_FAILED(rv))
        return rv;

    rv = lockFile->Append(LOCKFILE_NAME);
    if (NS_FAILED(rv))
        return rv;
        
#if defined(XP_MACOSX)
    // First, try locking using fcntl. It is more reliable on
    // a local machine, but may not be supported by an NFS server.

    rv = LockWithFcntl(lockFile);
    if (NS_FAILED(rv) && (rv != NS_ERROR_FILE_ACCESS_DENIED))
    {
        // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED,
        // assume we tried an NFS that does not support it. Now, try with symlink.
        rv = LockWithSymlink(lockFile, false);
    }
    
    if (NS_SUCCEEDED(rv))
    {
        // Check for the old-style lock used by pre-mozilla 1.3 builds.
        // Those builds used an earlier check to prevent the application
        // from launching if another instance was already running. Because
        // of that, we don't need to create an old-style lock as well.
        struct LockProcessInfo
        {
            ProcessSerialNumber psn;
            unsigned long launchDate;
        };

        PRFileDesc *fd = nullptr;
        int32_t ioBytes;
        ProcessInfoRec processInfo;
        LockProcessInfo lockProcessInfo;

        rv = lockFile->SetLeafName(OLD_LOCKFILE_NAME);
        if (NS_FAILED(rv))
            return rv;
        rv = lockFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd);
        if (NS_SUCCEEDED(rv))
        {
            ioBytes = PR_Read(fd, &lockProcessInfo, sizeof(LockProcessInfo));
            PR_Close(fd);

            if (ioBytes == sizeof(LockProcessInfo))
            {
#ifdef __LP64__
                processInfo.processAppRef = nullptr;
#else
                processInfo.processAppSpec = nullptr;
#endif
                processInfo.processName = nullptr;
                processInfo.processInfoLength = sizeof(ProcessInfoRec);
                if (::GetProcessInformation(&lockProcessInfo.psn, &processInfo) == noErr &&
                    processInfo.processLaunchDate == lockProcessInfo.launchDate)
                {
                    return NS_ERROR_FILE_ACCESS_DENIED;
                }
            }
            else
            {
                NS_WARNING("Could not read lock file - ignoring lock");
            }
        }
        rv = NS_OK; // Don't propagate error from OpenNSPRFileDesc.
    }
#elif defined(XP_UNIX)
    // Get the old lockfile name
    nsCOMPtr<nsIFile> oldLockFile;
    rv = aProfileDir->Clone(getter_AddRefs(oldLockFile));
    if (NS_FAILED(rv))
        return rv;
    rv = oldLockFile->Append(OLD_LOCKFILE_NAME);
    if (NS_FAILED(rv))
        return rv;

    // First, try locking using fcntl. It is more reliable on
    // a local machine, but may not be supported by an NFS server.
    rv = LockWithFcntl(lockFile);
    if (NS_SUCCEEDED(rv)) {
        // Check to see whether there is a symlink lock held by an older
        // Firefox build, and also place our own symlink lock --- but
        // mark it "obsolete" so that other newer builds can break the lock
        // if they obtain the fcntl lock
        rv = LockWithSymlink(oldLockFile, true);

        // If the symlink failed for some reason other than it already
        // exists, then something went wrong e.g. the file system
        // doesn't support symlinks, or we don't have permission to
        // create a symlink there.  In such cases we should just
        // continue because it's unlikely there is an old build
        // running with a symlink there and we've already successfully
        // placed a fcntl lock.
        if (rv != NS_ERROR_FILE_ACCESS_DENIED)
            rv = NS_OK;
    }
    else if (rv != NS_ERROR_FILE_ACCESS_DENIED)
    {
        // If that failed for any reason other than NS_ERROR_FILE_ACCESS_DENIED,
        // assume we tried an NFS that does not support it. Now, try with symlink
        // using the old symlink path
        rv = LockWithSymlink(oldLockFile, false);
    }

#elif defined(XP_WIN)
    nsAutoString filePath;
    rv = lockFile->GetPath(filePath);
    if (NS_FAILED(rv))
        return rv;

    lockFile->GetLastModifiedTime(&mReplacedLockTime);

    // always create the profile lock and never delete it so we can use its
    // modification timestamp to detect startup crashes
    mLockFileHandle = CreateFileW(filePath.get(),
                                  GENERIC_READ | GENERIC_WRITE,
                                  0, // no sharing - of course
                                  nullptr,
                                  CREATE_ALWAYS,
                                  0,
                                  nullptr);
    if (mLockFileHandle == INVALID_HANDLE_VALUE) {
        // XXXbsmedberg: provide a profile-unlocker here!
        return NS_ERROR_FILE_ACCESS_DENIED;
    }
#elif defined(XP_OS2)
    nsAutoCString filePath;
    rv = lockFile->GetNativePath(filePath);
    if (NS_FAILED(rv))
        return rv;

    lockFile->GetLastModifiedTime(&mReplacedLockTime);

    ULONG   ulAction = 0;
    APIRET  rc;
    rc = DosOpen(filePath.get(),
                  &mLockFileHandle,
                  &ulAction,
                  0,
                  FILE_NORMAL,
                  OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                  OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYREADWRITE | OPEN_FLAGS_NOINHERIT,
                  0 );
    if (rc != NO_ERROR)
    {
        mLockFileHandle = -1;
        return NS_ERROR_FILE_ACCESS_DENIED;
    }
#elif defined(VMS)
    nsAutoCString filePath;
    rv = lockFile->GetNativePath(filePath);
    if (NS_FAILED(rv))
        return rv;

    lockFile->GetLastModifiedTime(&mReplacedLockTime);

    mLockFileDesc = open_noshr(filePath.get(), O_CREAT, 0666);
    if (mLockFileDesc == -1)
    {
        if ((errno == EVMSERR) && (vaxc$errno == RMS$_FLK))
        {
            return NS_ERROR_FILE_ACCESS_DENIED;
        }
        else
        {
            NS_ERROR("Failed to open lock file.");
            return NS_ERROR_FAILURE;
        }
    }
#endif

    mHaveLock = true;

    return rv;
}
Example #22
0
char *
SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg)
{
  char* phrases, *phrase;
  PRFileDesc *fd;
  int32_t nb;
  char *pwFile = arg;
  int i;
  const long maxPwdFileSize = 4096;
  char* tokenName = NULL;
  int tokenLen = 0;

  if (!pwFile)
    return 0;

  if (retry) {
    return 0;  /* no good retrying - the files contents will be the same */
  }

  phrases = PORT_ZAlloc(maxPwdFileSize);

  if (!phrases) {
    return 0; /* out of memory */
  }

  fd = PR_Open(pwFile, PR_RDONLY, 0);
  if (!fd) {
    fprintf(stderr, "No password file \"%s\" exists.\n", pwFile);
    PORT_Free(phrases);
    return NULL;
  }

  nb = PR_Read(fd, phrases, maxPwdFileSize);

  PR_Close(fd);

  if (nb == 0) {
    fprintf(stderr,"password file contains no data\n");
    PORT_Free(phrases);
    return NULL;
  }

  if (slot) {
    tokenName = PK11_GetTokenName(slot);
    if (tokenName) {
      tokenLen = PORT_Strlen(tokenName);
    }
  }
  i = 0;
  do
  {
    int startphrase = i;
    int phraseLen;

    /* handle the Windows EOL case */
    while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++;
    /* terminate passphrase */
    phrases[i++] = '\0';
    /* clean up any EOL before the start of the next passphrase */
    while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) {
      phrases[i++] = '\0';
    }
    /* now analyze the current passphrase */
    phrase = &phrases[startphrase];
    if (!tokenName)
      break;
    if (PORT_Strncmp(phrase, tokenName, tokenLen)) continue;
    phraseLen = PORT_Strlen(phrase);
    if (phraseLen < (tokenLen+1)) continue;
    if (phrase[tokenLen] != ':') continue;
    phrase = &phrase[tokenLen+1];
    break;

  } while (i<nb);

  phrase = PORT_Strdup((char*)phrase);
  PORT_Free(phrases);
  return phrase;
}
Example #23
0
PRIntn main(PRIntn argc, char *argv[])
{
    PRStatus    rc;
    PRInt32     rv;
    PRFileDesc  *fd;
    PRIntn      i;
    PRInt32     sum = 0;

    {   /* Get command line options */
        PLOptStatus os;
        PLOptState *opt = PL_CreateOptState(argc, argv, "vd");

	    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
        {
		    if (PL_OPT_BAD == os) continue;
            switch (opt->option)
            {
            case 'd':  /* debug */
                debug = 1;
                break;
            case 'v':  /* verbose */
                verbose = 1;
                break;
             default:
                break;
            }
        }
	    PL_DestroyOptState(opt);
    } /* end block "Get command line options" */
/* ---------------------------------------------------------------------- */
    fd = PR_Open( "/tmp/nsprAppend", (PR_APPEND | PR_CREATE_FILE | PR_TRUNCATE | PR_WRONLY), 0666 );
    if ( NULL == fd )  {
        if (debug) printf("PR_Open() failed for writing: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }

    for ( i = 0; i < addedBytes ; i++ ) {
        rv = PR_Write( fd, &buf, sizeof(buf));
        if ( sizeof(buf) != rv )  {
            if (debug) printf("PR_Write() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
        rv = PR_Seek( fd, 0 , PR_SEEK_SET );
        if ( -1 == rv )  {
            if (debug) printf("PR_Seek() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
    }
    rc = PR_Close( fd );
    if ( PR_FAILURE == rc ) {
        if (debug) printf("PR_Close() failed after writing: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }
/* ---------------------------------------------------------------------- */
    fd = PR_Open( "/tmp/nsprAppend", PR_RDONLY, 0 );
    if ( NULL == fd )  {
        if (debug) printf("PR_Open() failed for reading: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }

    for ( i = 0; i < addedBytes ; i++ ) {
        rv = PR_Read( fd, &inBuf, sizeof(inBuf));
        if ( sizeof(inBuf) != rv)  {
            if (debug) printf("PR_Write() failed: %d\n", PR_GetError());
            failedAlready = PR_TRUE;
            goto Finished;
        }
        sum += inBuf;
    }

    rc = PR_Close( fd );
    if ( PR_FAILURE == rc ) {
        if (debug) printf("PR_Close() failed after reading: %d\n", PR_GetError());
        failedAlready = PR_TRUE;
        goto Finished;
    }
    if ( sum != addedBytes )  {
        if (debug) printf("Uh Oh! addedBytes: %d. Sum: %d\n", addedBytes, sum);
        failedAlready = PR_TRUE;
        goto Finished;
    }

/* ---------------------------------------------------------------------- */
Finished:
    if (debug || verbose) printf("%s\n", (failedAlready)? "FAILED" : "PASSED" );
    return( (failedAlready)? 1 : 0 );
}  /* main() */
Example #24
0
int main(int argc, char **argv)
{
    PRFileDesc *fd;
    PRInt64 offset, position;
    PRInt32 nbytes;
    char buf[MESSAGE_SIZE];
#ifdef _WIN32
    HANDLE hFile;
    LARGE_INTEGER li;
#endif /* _WIN32 */

    LL_I2L(offset, 1);
    LL_SHL(offset, offset, 32);

#ifdef _WIN32
    hFile = CreateFile(TEST_FILE_NAME, GENERIC_WRITE, 0, NULL,
            CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "CreateFile failed\n");
        exit(1);
    }
    li.QuadPart = offset;
    li.LowPart = SetFilePointer(hFile, li.LowPart, &li.HighPart, FILE_BEGIN);
    if (li.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
        fprintf(stderr, "SetFilePointer failed\n");
        exit(1);
    }
    PR_ASSERT(li.QuadPart == offset);
    strcpy(buf, MESSAGE);
    if (WriteFile(hFile, buf, sizeof(buf), &nbytes, NULL) == 0) {
        fprintf(stderr, "WriteFile failed\n");
        exit(1);
    }
    PR_ASSERT(nbytes == sizeof(buf));
    if (CloseHandle(hFile) == 0) {
        fprintf(stderr, "CloseHandle failed\n");
        exit(1);
    }
#endif /* _WIN32 */

    memset(buf, 0, sizeof(buf));

    fd = PR_Open(TEST_FILE_NAME, PR_RDONLY, 0666);
    if (fd == NULL) {
        fprintf(stderr, "PR_Open failed\n");
        exit(1);
    }
    position = PR_Seek64(fd, offset, PR_SEEK_SET);
    if (!LL_GE_ZERO(position)) {
        fprintf(stderr, "PR_Seek64 failed\n");
        exit(1);
    }
    PR_ASSERT(LL_EQ(position, offset));
    nbytes = PR_Read(fd, buf, sizeof(buf));
    if (nbytes != sizeof(buf)) {
        fprintf(stderr, "PR_Read failed\n");
        exit(1);
    }
    if (strcmp(buf, MESSAGE)) {
        fprintf(stderr, "corrupt data:$%s$\n", buf);
        exit(1);
    }
    if (PR_Close(fd) == PR_FAILURE) {
        fprintf(stderr, "PR_Close failed\n");
        exit(1);
    }

    if (PR_Delete(TEST_FILE_NAME) == PR_FAILURE) {
        fprintf(stderr, "PR_Delete failed\n");
        exit(1);
    }

    printf("PASS\n");
    return 0;
}
NSFC_MakeTempCopy(const char *infile, char *outfile, 
                  NSFCCache cip, PRInt64 *size)
{
    PRFileDesc *infd;
    PRFileDesc *outfd;
    char *cp;
    PRStatus rv = PR_FAILURE;

    infd = NSFC_PR_Open(infile, PR_RDONLY, 0);
    if (infd == NULL) {
        return rv;
    }

    /* Create the output directory if necessary */
    cp = strrchr(outfile, '/');
    if (cp) {

        *cp = 0;
        rv = NSFC_MakeDirectory(outfile, cip);
        *cp = '/';
        if (rv == PR_FAILURE) {
            PR_Close(infd);
            return rv;
        }
    }

    outfd = NSFC_PR_Open(outfile, PR_CREATE_FILE|PR_TRUNCATE|PR_WRONLY, 0660);
    if (outfd != NULL) {

        PRInt32 inlen = -1;
        PRInt32 outlen;
        PRInt64 written = 0;
        char *buffer = (char *)PR_Malloc(COPY_BUFFER_SIZE);

        if (buffer) {
            while (1) {
                inlen = PR_Read(infd, buffer, COPY_BUFFER_SIZE);
                if (inlen <= 0) {
                    break;
                }
                outlen = PR_Write(outfd, buffer, inlen);
                if (outlen != inlen) {
                    break;
                }
                written += outlen;
            }

            PR_Free(buffer);
        }

        PR_Close(outfd);

        if (inlen == 0) {
            rv = PR_SUCCESS;
            struct stat    tempStat;

            *size = written;

            /* VB: bug# 360312
             * Whenever we make a temporary copy of a file, we need to 
             * set the modification/access time of the copy to be that
             * of the original.
             * This is required to avoid the following scenario.
             * 1. Copy file1 preserving timestamp.
             * 2. Edit file1 and access it. This would cause the edited verion
             *    to be cached and a temp copy of the edited verion to be 
             *    created. 
             * 3. Now replace the edited file1 with the original copy preserving
             *    the timestamp. So file 1 has the timestamp at the beginning 
             *    of our test.
             * 4. We would never end up serving this file since the timestamp
             *    of the temp copy would be ahead of that of file1.
             * 5. With this fix, we aviod the case since we can now compare
             *    for inequality (LL_NE) rather than which is newer. (LL_CMP).
             * This is of relevance in raltion to the doc dir being backed up
             * and restored.
             */
            if (stat(infile, &tempStat) == 0) {
                struct utimbuf infileTime;
                infileTime.actime = tempStat.st_atime;
                infileTime.modtime = tempStat.st_mtime;
                if (utime(outfile, &infileTime) == -1) {
                    /* VB: This can happen if the file is owned by someone else
                     * This should not happen unless the server user was changed
                     * Should we be failing in this case ?
                     */
                    int whatDoIdonow = 1;
                }
            }
            else {
                // stat failed. This should happen if infile got deleted.
                // So what - we serve the temp file until the filecache
                // realizes to the contrary.
                int shouldNotMatter = 0;
            }
        } else {
            rv = PR_FAILURE;
            PR_Delete(outfile);
        }
    }

    PR_Close(infd);

    return rv;
}
/*
 * rline
 */
static int rline(sed_commands_t *commands, PRFileDesc *fin,
                 char *lbuf, char *lbend)
{
    char   *p;
    const char *q;
    int    t;
    PRInt32 bytes_read;

    p = lbuf;

    if(commands->eflag) {
        if(commands->eflag > 0) {
            commands->eflag = -1;
            q = commands->earg;
            while((t = *q++) != '\0') {
                if(t == '\n') {
                    commands->saveq = q;
                    goto out1;
                }
                if (p < lbend)
                    *p++ = t;
                if(t == '\\') {
                    if((t = *q++) == '\0') {
                        commands->saveq = NULL;
                        return(-1);
                    }
                    if (p < lbend)
                        *p++ = t;
                }
            }
            commands->saveq = NULL;

        out1:
            if (p == lbend) {
                command_errf(commands, XP_GetAdminStr(DBT_CLTL), commands->linebuf);
                return -1;
            }
            *p = '\0';
            return(1);
        }
        if((q = commands->saveq) == 0)    return(-1);

        while((t = *q++) != '\0') {
            if(t == '\n') {
                commands->saveq = q;
                goto out2;
            }
            if(p < lbend)
                *p++ = t;
            if(t == '\\') {
                if((t = *q++) == '\0') {
                    commands->saveq = NULL;
                    return(-1);
                }
                if (p < lbend)
                    *p++ = t;
            }
        }
        commands->saveq = NULL;

    out2:
        if (p == lbend) {
            command_errf(commands, XP_GetAdminStr(DBT_CLTL), commands->linebuf);
            return -1;
        }
        *p = '\0';
        return(1);
    }

    bytes_read = 1;
    /* XXX extremely inefficient 1 byte reads */
    while (PR_Read(fin, &t, bytes_read) == 1) {
        if(t == '\n') {
            if (p == lbend) {
                command_errf(commands, XP_GetAdminStr(DBT_CLTL), commands->linebuf);
                return -1;
            }
            *p = '\0';
            return(1);
        }
        if (p < lbend)
            *p++ = t;
        if(t == '\\') {
            bytes_read = 1;
            if (PR_Read(fin, &t, bytes_read) != 1) {
                return -1;
            }
            if(p < lbend)
                *p++ = t;
        }
        bytes_read = 1;
    }
    return(-1);
}
Example #27
0
/***********************************************************************
 *
 * R e a d I n p u t F i l e
 *
 * Read tokenname and module name from the file with the indicated name.
 * Pass in the addresses of pointers.  They will be set to point at
 * dynamically-allocated memory.
 *
 * Returns 0 on success, -1 on error with file.
 */
int
ReadInputFile(char *filename, char**tokenname, char**moddbname, char **userpw)
{
	PRFileDesc* file=NULL;
	char readbuf[1025];
	int numbytes=0;
	char *cp;

	*tokenname = NULL;
	*moddbname = NULL;

	/* Open file */
	file = PR_Open(filename, PR_RDONLY, 0);
	if(!file) {
		return -1;
	}

	/* Read in everything */
	numbytes = PR_Read(file, readbuf, 1024);
	if(numbytes==-1) {
		goto loser;
	}
	readbuf[numbytes] = '\0'; /* make sure we're null-terminated */

	/* Get tokenname */
	cp = strtok(readbuf, "\r\n");
	if(cp == NULL) {
		goto loser;
	}
	*tokenname = PR_Malloc(strlen(cp)+1);
	strcpy(*tokenname, cp);

	/* get moddbname */
	cp = strtok(NULL, "\r\n");
	if(cp == NULL) {
		goto loser;
	}
	*moddbname = PR_Malloc(strlen(cp)+1);
	strcpy(*moddbname, cp);

	/* Get module PIN */
	cp = strtok(NULL, "\r\n");
	if(cp == NULL) {
		goto loser;
	}
	*userpw = PR_Malloc(strlen(cp)+1);
	strcpy(*userpw, cp);

	PR_Close(file);
	return 0;

loser:
	if(file) {
		PR_Close(file);
	}
	if(*tokenname) {
		PR_Free(*tokenname);
		*tokenname = NULL;
	}
	if(*moddbname) {
		PR_Free(*moddbname);
		*moddbname = NULL;
	}
	return -1;
}
void Resolver :: ar_receive()
{
    char ar_rcvbuf[HFIXEDSZ + MAXPACKET];
    HEADER* hptr = NULL;        /* Name Server query header */
    DNSSession* session = NULL;
    int rc = 0;
    datapacket* newpkt = NULL;
    unsigned int id = 0;

    if (ar_vc)
        rc = PR_Recv(afd, ar_rcvbuf, HFIXEDSZ+MAXPACKET, 0, 
            PR_INTERVAL_NO_TIMEOUT);
    else
        rc = PR_Read(afd, ar_rcvbuf,  HFIXEDSZ+MAXPACKET);

    ar_reinfo.re_replies++;

    /* Create a reslist_pkt_t to queue against the reslist */
    newpkt = new datapacket();
    PR_ASSERT(newpkt);

    newpkt->next = NULL;
    if (rc >0)
    {
        // packet received

	    /*
	     * Wakeup corresponding thread.
	     */
	    hptr = (HEADER *)ar_rcvbuf;
	    /*
	     * convert things to be in the right order.
	     */
	    id = ntohs(hptr->id);
	    /*
	     * response for an id which we have already received an answer for
	     * just ignore this response.
	     */
	    session = DNShash.lookup(id);
	    if (!session)
        {            
            delete(newpkt);
	        /* Request no longer in queue, so just return. */
	        return;
	    }

        newpkt->buflen = rc;
        memset(newpkt, 0, HFIXEDSZ + MAXPACKET);
        memcpy(newpkt, ar_rcvbuf, rc);
    }
    else
    {
        // no packet received
        newpkt->buflen = 0;
    }

    // Append new data packet to end of known data packets
    session->reslist_add_pkt(newpkt);

    session->setStatus(DNS_RCVD);

    // Wakeup corresponding thread.

    DNShash.remove(session); // remove this completed session from the hash table
    session->complete();
}
Example #29
0
nsresult
CacheFileMetadata::SyncReadMetadata(nsIFile *aFile)
{
  LOG(("CacheFileMetadata::SyncReadMetadata() [this=%p]", this));

  MOZ_ASSERT(!mListener);
  MOZ_ASSERT(!mHandle);
  MOZ_ASSERT(!mHashArray);
  MOZ_ASSERT(!mBuf);
  MOZ_ASSERT(!mWriteBuf);
  MOZ_ASSERT(mKey.IsEmpty());

  nsresult rv;

  int64_t fileSize;
  rv = aFile->GetFileSize(&fileSize);
  if (NS_FAILED(rv)) {
    // Don't bloat the console
    return rv;
  }

  PRFileDesc *fd;
  rv = aFile->OpenNSPRFileDesc(PR_RDONLY, 0600, &fd);
  NS_ENSURE_SUCCESS(rv, rv);

  int64_t offset = PR_Seek64(fd, fileSize - sizeof(uint32_t), PR_SEEK_SET);
  if (offset == -1) {
    PR_Close(fd);
    return NS_ERROR_FAILURE;
  }

  uint32_t metaOffset;
  int32_t bytesRead = PR_Read(fd, &metaOffset, sizeof(uint32_t));
  if (bytesRead != sizeof(uint32_t)) {
    PR_Close(fd);
    return NS_ERROR_FAILURE;
  }

  metaOffset = NetworkEndian::readUint32(&metaOffset);
  if (metaOffset > fileSize) {
    PR_Close(fd);
    return NS_ERROR_FAILURE;
  }

  mBufSize = fileSize - metaOffset;
  mBuf = static_cast<char *>(moz_xmalloc(mBufSize));

  DoMemoryReport(MemoryUsage());

  offset = PR_Seek64(fd, metaOffset, PR_SEEK_SET);
  if (offset == -1) {
    PR_Close(fd);
    return NS_ERROR_FAILURE;
  }

  bytesRead = PR_Read(fd, mBuf, mBufSize);
  PR_Close(fd);
  if (bytesRead != static_cast<int32_t>(mBufSize)) {
    return NS_ERROR_FAILURE;
  }

  rv = ParseMetadata(metaOffset, 0, false);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Example #30
0
char *getNSSPassword(PK11SlotInfo *slot, PRBool retry, void *arg)
{
    secuPWData *pwdInfo = (secuPWData *)arg;
    PRFileDesc *fd;
    PRInt32 nb; /*number of bytes*/
    char* password;
    char* strings;
    char* token=NULL;
    const long maxPwdFileSize = NSSpwdfilesize;
    int i, tlen=0;

    if (slot) {
        token = PK11_GetTokenName(slot);
        if (token) {
            tlen = PORT_Strlen(token);
            /* openswan_log("authentication needed for token name %s with length %d",token,tlen); */
        }
        else {
            return 0;
        }
    }
    else {
        return 0;
    }

    if(retry) return 0;

    strings=PORT_ZAlloc(maxPwdFileSize);
    if(!strings) {
        openswan_log("Not able to allocate memory for reading NSS password file");
        return 0;
    }


    if(pwdInfo->source == PW_FROMFILE) {
        if(pwdInfo->data !=NULL) {
            fd = PR_Open(pwdInfo->data, PR_RDONLY, 0);
            if (!fd) {
                PORT_Free(strings);
                openswan_log("No password file \"%s\" exists.", pwdInfo->data);
                return 0;
            }

            nb = PR_Read(fd, strings, maxPwdFileSize);
            PR_Close(fd);

            if (nb == 0) {
                openswan_log("password file contains no data");
                PORT_Free(strings);
                return 0;
            }

            i = 0;
            do
            {
                int start = i;
                int slen;

                while (strings[i] != '\r' && strings[i] != '\n' && i < nb) i++;
                strings[i++] = '\0';

                while ( (i<nb) && (strings[i] == '\r' || strings[i] == '\n')) {
                    strings[i++] = '\0';
                }

                password = &strings[start];

                if (PORT_Strncmp(password, token, tlen)) continue;
                slen = PORT_Strlen(password);

                if (slen < (tlen+1)) continue;
                if (password[tlen] != ':') continue;
                password = &password[tlen+1];
                break;

            } while (i<nb);

            password = PORT_Strdup((char*)password);
            PORT_Free(strings);

            /* openswan_log("Password passed to NSS is %s with length %d", password, PORT_Strlen(password)); */
            return password;
        }
        else {
            openswan_log("File with Password to NSS DB is not provided");
            return 0;
        }
    }

    openswan_log("nss password source is not specified as file");
    return 0;
}