Esempio n. 1
0
///*
int encryptccm(unsigned char *message, unsigned char *key, unsigned char *IV,
	unsigned char *C, unsigned char *tag)
{
	int outlen;
	int ciphertext_len = 0;
	EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx, EVP_aes_256_ccm(), NULL, key, IV);
    if(1 != EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_IVLEN, 7, NULL))
		handleErrors("set IV len to 7");

	// Set tag length 
	EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_SET_TAG, 14, NULL);
	if(1 != EVP_EncryptInit_ex(&ctx, NULL, NULL, key, IV))
		handleErrors("initialize key and IV");

	if(1 != EVP_EncryptUpdate(&ctx, NULL, &outlen, NULL, strlen(message)))
		handleErrors("provide total plaintext length");

	if(!EVP_EncryptUpdate(&ctx, C, &outlen, message, strlen(message)))
	{
               // Error
		puts("data encrypting..");
		return 0;
	}
	ciphertext_len += outlen;
	if(1 != EVP_EncryptFinal_ex(&ctx, C + outlen, &outlen))
		handleErrors("finalize encryption");
	ciphertext_len += outlen;
    if(1 != EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_CCM_GET_TAG, 14, tag))
		handleErrors("get the tag");

	return ciphertext_len;
}
Esempio n. 2
0
struct sec performDH(char *pubkeyRec,DH *privkey){
	
	struct sec s;
	int secret_size;
	/* Send the public key to the peer.
	* How this occurs will be specific to your situation (see main text below) */


	/* Receive the public key from the peer. In this example we're just hard coding a value */
	BIGNUM *pubkey = NULL;
	if(0 == (BN_dec2bn(&pubkey, pubkeyRec))) handleErrors();

	/* Compute the shared secret */
	unsigned char *secret;
	if(NULL == (secret = OPENSSL_malloc(sizeof(unsigned char) * (DH_size(privkey))))) handleErrors();

	if(0 > (secret_size = DH_compute_key(secret, pubkey, privkey))) handleErrors();

	/* Do something with the shared secret */
	/* Note secret_size may be less than DH_size(privkey) */
	printf("The shared secret is:\n");
	
	strcpy(s.value,secret);
	s.length=secret_size;
	/* Clean up */
	OPENSSL_free(secret);
	BN_free(pubkey);
	DH_free(privkey);

	return s;
}
Esempio n. 3
0
void OnlineSearchBioRxiv::resultsPageDone() {
    emit progress(++curStep, numSteps);
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

    if (handleErrors(reply)) {
        /// ensure proper treatment of UTF-8 characters
        const QString htmlCode = QString::fromUtf8(reply->readAll().constData());

        static const QRegExp contentRegExp(QStringLiteral("/content/early/[12]\\d{3}/[01]\\d/\\d{2}/\\d+"));
        int p = -1;
        while ((p = contentRegExp.indexIn(htmlCode, p + 1)) > 0) {
            const QUrl url = QUrl(QStringLiteral("http://biorxiv.org") + contentRegExp.cap(0));
            d->resultPageUrls.insert(url);
        }

        if (d->resultPageUrls.isEmpty())
            stopSearch(resultNoError);
        else {
            const QUrl firstUrl = *d->resultPageUrls.constBegin();
            d->resultPageUrls.remove(firstUrl);
            QNetworkRequest request(firstUrl);
            QNetworkReply *reply = InternalNetworkAccessManager::self()->get(request);
            InternalNetworkAccessManager::self()->setNetworkReplyTimeout(reply);
            connect(reply, &QNetworkReply::finished, this, &OnlineSearchBioRxiv::resultPageDone);
        }
    }
}
Esempio n. 4
0
void OnlineSearchBioRxiv::resultPageDone() {
    emit progress(++curStep, numSteps);
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

    if (handleErrors(reply)) {
        /// ensure proper treatment of UTF-8 characters
        const QString htmlCode = QString::fromUtf8(reply->readAll().constData());

        static const QRegExp highwireRegExp(QStringLiteral("/highwire/citation/\\d+/bibtex"));
        if (highwireRegExp.indexIn(htmlCode) > 0) {
            const QUrl url = QUrl(QStringLiteral("http://biorxiv.org") + highwireRegExp.cap(0));
            QNetworkRequest request(url);
            QNetworkReply *reply = InternalNetworkAccessManager::self()->get(request);
            InternalNetworkAccessManager::self()->setNetworkReplyTimeout(reply);
            connect(reply, &QNetworkReply::finished, this, &OnlineSearchBioRxiv::bibTeXDownloadDone);
        } else if (!d->resultPageUrls.isEmpty()) {
            const QUrl firstUrl = *d->resultPageUrls.constBegin();
            d->resultPageUrls.remove(firstUrl);
            QNetworkRequest request(firstUrl);
            QNetworkReply *reply = InternalNetworkAccessManager::self()->get(request);
            InternalNetworkAccessManager::self()->setNetworkReplyTimeout(reply);
            connect(reply, &QNetworkReply::finished, this, &OnlineSearchBioRxiv::resultPageDone);
        } else
            stopSearch(resultNoError);
    }
}
Esempio n. 5
0
/* INFO: Decrypting the Message

         Finally we need to define the "decrypt" operation. This is very
         similar to encryption and consists of the following stages: Encrypting
         consists of the following stages:

         * Setting up a context
         * Initialising the decryption operation
         * Providing ciphertext bytes to be decrypted
         * Finalising the decryption operation

         Again through the parameters we will receive the ciphertext to be
         decrypted, the length of the ciphertext, the key and the IV. We'll
         also receive a buffer to place the decrypted text into, and return the
         length of the plaintext we have found.

         Note that we have passed the length of the ciphertext. This is
         required as you cannot use functions such as "strlen" on this data -
         its binary! Similarly, even though in this example our plaintext
         really is ASCII text, OpenSSL does not know that. In spite of the name
         plaintext could be binary data, and therefore no NULL terminator will
         be put on the end(unless you encrypt the NULL as well of course). */
static int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
	unsigned char *iv, unsigned char *plaintext) {
	EVP_CIPHER_CTX *ctx;

	int len;

	int plaintext_len;

	/* INFO: Create and initialise the context */
	if(!(ctx = EVP_CIPHER_CTX_new())) {
		handleErrors();
	}

	/* INFO: Initialise the decryption operation. IMPORTANT - ensure you
	         use a key and IV size appropriate for your cipher. In this
	         example we are using 256 bit AES(i.e. a 256 bit key). The IV
	         size for *most* modes is the same as the block size. For AES
	         this is 128 bits */
	if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) {
		handleErrors();
	}

	/* INFO: Provide the message to be decrypted, and obtain the plaintext
	         output. EVP_DecryptUpdate can be called multiple times if
	         necessary */
	if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext,
			ciphertext_len)) {
		handleErrors();
	}

	plaintext_len = len;

	/* INFO: Finalise the decryption. Further plaintext bytes may be
	         written at this stage.	*/
	if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) {
		handleErrors();
	}

	plaintext_len += len;

	/* INFO: Clean up */
	EVP_CIPHER_CTX_free(ctx);

	return plaintext_len;
}
Esempio n. 6
0
void digest_message(
    const unsigned char *message,
    size_t               message_len,
    unsigned char      **digest,
    unsigned int        *digest_len )
{
	if( 1 != EVP_DigestInit_ex( mdctx, EVP_sha256(), NULL ) )
		handleErrors();

	if( 1 != EVP_DigestUpdate( mdctx, message, message_len ) )
		handleErrors();

	if( ( *digest = (unsigned char *)OPENSSL_malloc( EVP_MD_size( EVP_sha256() ) ) ) == NULL )
		handleErrors();

	if( 1 != EVP_DigestFinal_ex( mdctx, *digest, digest_len ) )
		handleErrors();
}
Esempio n. 7
0
// https://wiki.openssl.org/index.php/EVP_Authenticated_Encryption_and_Decryption#Authenticated_Encryption_using_GCM_mode
int eap_fast_encrypt(uint8_t const *plaintext, size_t plaintext_len,
		     uint8_t const *aad, size_t aad_len,
		     uint8_t const *key, uint8_t *iv, unsigned char *ciphertext,
		     uint8_t *tag)
{
	EVP_CIPHER_CTX *ctx;

	int len;

	int ciphertext_len;


	/* Create and initialise the context */
	if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

	/* Initialise the encryption operation. */
	if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
		handleErrors();

	/* Set IV length if default 12 bytes (96 bits) is not appropriate */
	if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
		handleErrors();

	/* Initialise key and IV */
	if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

	/* Provide any AAD data. This can be called zero or more times as
	 * required
	 */
	if (1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
		handleErrors();

	/* Provide the message to be encrypted, and obtain the encrypted output.
	 * EVP_EncryptUpdate can be called multiple times if necessary
	 */
	if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
		handleErrors();
	ciphertext_len = len;

	/* Finalise the encryption. Normally ciphertext bytes may be written at
	 * this stage, but this does not occur in GCM mode
	 */
	if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
	ciphertext_len += len;

	/* Get the tag */
	if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
		handleErrors();

	/* Clean up */
	EVP_CIPHER_CTX_free(ctx);

	return ciphertext_len;
}
Esempio n. 8
0
/**
*	Constructor
*
*	@param QWidget parent	The parent Widget
**/
Window::Window()
{
	this->secondUpload = false;
    //QList<ImageShackObject *>  listeImages ;
	QNetworkProxy * proxy = new QNetworkProxy(QNetworkProxy::HttpProxy,QString("proxy.rennes.enst-bretagne.fr"),3128);

    ImageShackObject * pc = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Argentina.gif","mc,notmac,pub",true);
    ImageShackObject * biere   = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Australia.gif","biere,pub",true);
    ImageShackObject * plus  = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Austria.gif","plus,priv",false);
    //ImageShackObject * cpu      = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/","cpu,priv",false);

    listeImages << pc;
    listeImages << biere;
    listeImages << plus;
    //listeImages2 << biere;
    //listeImages2 << plus;
    //listeImages2 << cpu;
    //listeImages << fire;
    //listeImages << a;

    //ImageShackObject * basket = new ImageShackObject("/home/christ/Images/Basket/basket.jpg","basket,fire,pub",true);
    //ImageShackObject * dunk   = new ImageShackObject("/home/christ/Images/Basket/test.jpg","dunk,nba,priv",false);

	//basket->setResizeOption("200x200");
	//dunk->setResizeOption("50x300");

    //listeImages << dunk;
   // listeImages << basket;

    uploader = new ImageShackUploader(QString("EFI0O4JZd1897eb3d86758fa0ee582a34385405e"));
    //uploader->setProxy(proxy);

	//uploader->checkUserPassword(QString("kwentakill"),QString("rousseau"));

   //uploader->anonymousUploadImages(listeImage);
	qDebug() << "Window.cpp : Nombre de fichiers =" << listeImages.size();
    //uploader->uploadImages(listeImages,"kwentakill","rousseau");

	//QTimer::singleShot(500, this, SLOT(oneUploadDone()));

    //uploader->anonymousUploadImage(fichier,"basket");
	//uploader->setRemoveInformationBar(false);	
    //uploader->userUploadImage(fichier,"kwentakill","rousseau","dunk");
    //uploader->userUploadImage(fichier,"kwentakill","rousea","dunk","150x150");

    uploader->checkUserPassword("*****@*****.**","rousseau");
    connect(uploader,SIGNAL(authentificationResponse(bool)),this,SLOT(manageResponse(bool)));
	connect(uploader,SIGNAL(uploadDone(ImageShackResponse *)),this,SLOT(oneUploadDone(ImageShackResponse *)));
    connect(uploader,SIGNAL(endOfUploads()),this,SLOT(manageEndUpload()));
	connect(uploader,SIGNAL(uploadError(ImageShackError::UploadError)),this,SLOT(handleErrors(ImageShackError::UploadError)));
	connect(uploader,SIGNAL(uploadProgress(ImageShackObject *,qint64,qint64)),this,SLOT(handleProgressions(ImageShackObject *,qint64,qint64)));


}
Esempio n. 9
0
int encrypt_sym(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
	EVP_CIPHER_CTX *ctx;

	int len;
	int ciphertext_len;

	if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

	if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors();
    
	if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors();
	ciphertext_len = len;

	if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
	ciphertext_len += len;

	EVP_CIPHER_CTX_free(ctx);

	return ciphertext_len;
}
short ExExeUtilTcb::restoreCQS()
{
  Lng32 rc = cliInterface()->
    executeImmediate("control query shape restore;");
  if (rc < 0)
    {
      handleErrors(rc);

      return -1;
    }

  return 0;
}
Esempio n. 11
0
int AesFileEnc::encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
  unsigned char *iv, unsigned char *ciphertext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int ciphertext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) this->handleErrors();

  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    handleErrors();

  /* Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */
  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    handleErrors();
  ciphertext_len = len;

  /* Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */
  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}
short ExExeUtilTcb::resetCS(const char * csName, ComDiagsArea * globalDiags)
{
  Lng32 cliRC;

  cliRC = resetCS(csName, cliInterface(), globalDiags);
  if (cliRC < 0)
    {
      handleErrors(cliRC);

      return -1;
    }

  return 0;
}
short ExExeUtilTcb::disableCQS()
{
  // disable any CQS in affect
  Lng32 rc = cliInterface()->
    executeImmediate("control query shape hold;");
  if (rc < 0)
    {
      handleErrors(rc);

      return -1;
    }

  return 0;
}
Esempio n. 14
0
int decryptccm(unsigned char *ciphertext, int ciphertext_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
	unsigned char *plaintext)
{
	EVP_CIPHER_CTX *ctx;
	int len;
	int plaintext_len;
	int ret;

	/* Create and initialise the context */
	if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors("Create and initialise the context");

	/* Initialise the decryption operation. */
	if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), NULL, NULL, NULL))
		handleErrors("Initialise the decryption operation.");

	/* Setting IV len to 7. Not strictly necessary as this is the default
	 * but shown here for the purposes of this example */
	if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, 7, NULL))
		handleErrors("Setting IV len to 7. ");

	/* Set expected tag value. */
	if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, 14, tag))
		handleErrors("Set expected tag value.");

	/* Initialise key and IV */
	if(1 != EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
		handleErrors("Initialise key and IV");


	/* Provide the total ciphertext length
	 */
	if(1 != EVP_DecryptUpdate(ctx, NULL, &len, NULL, ciphertext_len))
		handleErrors("rovide the total ciphertext length");



	/* Provide the message to be decrypted, and obtain the plaintext output.
	 * EVP_DecryptUpdate can be called multiple times if necessary
	 */
	ret = EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len);

	plaintext_len = len;

	/* Clean up */
	EVP_CIPHER_CTX_free(ctx);

	if(ret > 0)
	{
		/* Success */
		return plaintext_len;
	}
	else
	{
		/* Verify failed */
		return -1;
	}
}
Esempio n. 15
0
void crypto_open( void )
{
    /* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

    /* Load all digest and cipher algorithms */
    OpenSSL_add_all_algorithms();

    /* Load config file, and other important initialisation */
    OPENSSL_config(NULL);

	if( ( mdctx = EVP_MD_CTX_create() ) == NULL )
		handleErrors();

}
Esempio n. 16
0
DH *createPubkey(){

	DH *privkey;
	int codes;
	

	/* Generate the parameters to be used */
	if(NULL == (privkey = DH_new())) handleErrors();
	if(1 != DH_generate_parameters_ex(privkey, 512, DH_GENERATOR_2, NULL)) handleErrors();

	if(1 != DH_check(privkey, &codes)) handleErrors();
	if(codes != 0)
	{
	/* Problems have been found with the generated parameters */
	/* Handle these here - we'll just abort for this example */
	printf("DH_check failed\n");
	abort();
	}

	/* Generate the public and private key pair */
	if(1 != DH_generate_key(privkey)) handleErrors();
	return privkey;
	
}
short ExExeUtilTcb::holdAndSetCQD(const char * defaultName, const char * defaultValue,
				  ComDiagsArea * globalDiags)
{
  Lng32 cliRC;

  cliRC = holdAndSetCQD(defaultName, defaultValue, cliInterface(),
			globalDiags);
  if (cliRC < 0)
    {
      handleErrors(cliRC);

      return -1;
    }

  return 0;
}
short ExExeUtilTcb::fetchAllRows(Queue * &infoList, 
				 char * query,
				 Lng32 numOutputEntries,
				 NABoolean varcharFormat,
				 short &rc,
				 NABoolean monitorThis)
{
  rc = cliInterface()->fetchAllRows(infoList, query, numOutputEntries, varcharFormat,
				    monitorThis);
  if (rc < 0)
    {
      handleErrors(rc);
      return -1;
    }
  
  return 0;
}
Esempio n. 19
0
void Game::run() {

	/*TODO:The timer should be an object, Game::run should not call
	 * sdl functions directly
	 */

	LCVAR_Event gameEvent;
	gameEvent.type = NOTHING;
	int startTicks = 0;

	//TODO: Clean this up, do not hardcode
	turn = WHITE;

	bool gameEnd = false;
	short errorCode = 0;

	//TODO: Don't hardcode these settings
	engine->init(32, 600, 600, ".", errorCode);

	handleErrors(errorCode);

	drawEverything();
	refreshScreen();

	while (!gameEnd){

		getEvent(gameEvent);

		if(gameEvent.type == QUIT){

			gameEnd = true;

		}else if (gameEvent.type == MOVE){
			parseUserInput(gameEvent);
		}

		drawEverything();
		refreshScreen();

		gameEvent.type = NOTHING;

	}

}
Esempio n. 20
0
void OnlineSearchBioRxiv::bibTeXDownloadDone() {
    emit progress(++curStep, numSteps);
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());

    if (handleErrors(reply)) {
        /// ensure proper treatment of UTF-8 characters
        const QString bibTeXcode = QString::fromUtf8(reply->readAll().constData());

        if (!bibTeXcode.isEmpty()) {
            FileImporterBibTeX importer;
            File *bibtexFile = importer.fromString(bibTeXcode);

            if (bibtexFile != NULL) {
                for (File::ConstIterator it = bibtexFile->constBegin(); it != bibtexFile->constEnd(); ++it) {
                    QSharedPointer<Entry> entry = (*it).dynamicCast<Entry>();
                    publishEntry(entry);
                }

                delete bibtexFile;
            } else {
                qCWarning(LOG_KBIBTEX_NETWORKING) << "No valid BibTeX file results returned on request on" << reply->url().toDisplayString();
            }
        }
    }

    if (d->resultPageUrls.isEmpty())
        stopSearch(resultNoError);
    else {
        const QUrl firstUrl = *d->resultPageUrls.constBegin();
        d->resultPageUrls.remove(firstUrl);
        QNetworkRequest request(firstUrl);
        QNetworkReply *reply = InternalNetworkAccessManager::self()->get(request);
        InternalNetworkAccessManager::self()->setNetworkReplyTimeout(reply);
        connect(reply, &QNetworkReply::finished, this, &OnlineSearchBioRxiv::resultPageDone);
    }
}
Esempio n. 21
0
static int clangTidyMain(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
                                    cl::ZeroOrMore);

  auto OptionsProvider = createOptionsProvider();
  if (!OptionsProvider)
    return 1;

  StringRef FileName("dummy");
  auto PathList = OptionsParser.getSourcePathList();
  if (!PathList.empty()) {
    FileName = PathList.front();
  }
  ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
  std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);

  if (ListChecks) {
    llvm::outs() << "Enabled checks:";
    for (auto CheckName : EnabledChecks)
      llvm::outs() << "\n    " << CheckName;
    llvm::outs() << "\n\n";
    return 0;
  }

  if (DumpConfig) {
    EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
    llvm::outs() << configurationAsText(
                        ClangTidyOptions::getDefaults().mergeWith(
                            EffectiveOptions))
                 << "\n";
    return 0;
  }

  if (EnabledChecks.empty()) {
    llvm::errs() << "Error: no checks enabled.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  if (PathList.empty()) {
    llvm::errs() << "Error: no input files specified.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  ProfileData Profile;

  std::vector<ClangTidyError> Errors;
  ClangTidyStats Stats =
      runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
                   PathList, &Errors,
                   EnableCheckProfile ? &Profile : nullptr);
  bool FoundErrors =
      std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
        return E.DiagLevel == ClangTidyError::Error;
      }) != Errors.end();

  const bool DisableFixes = Fix && FoundErrors && !FixErrors;

  // -fix-errors implies -fix.
  handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);

  if (!ExportFixes.empty() && !Errors.empty()) {
    std::error_code EC;
    llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
    if (EC) {
      llvm::errs() << "Error opening output file: " << EC.message() << '\n';
      return 1;
    }
    exportReplacements(Errors, OS);
  }

  printStats(Stats);
  if (DisableFixes)
    llvm::errs()
        << "Found compiler errors, but -fix-errors was not specified.\n"
           "Fixes have NOT been applied.\n\n";

  if (EnableCheckProfile)
    printProfileData(Profile, llvm::errs());

  return 0;
}
Esempio n. 22
0
//////////////////////////////////////////////////////
// work() for ExTimeoutTcb
//////////////////////////////////////////////////////
short ExTimeoutTcb::work()
{
  while (1) {
    // if no parent request, return
    if (qparent_.down->isEmpty())
      return WORK_OK;
      
    // if no room in up queue, won't be able to return data/status.
    // Come back later.
    if (qparent_.up->isFull()) return WORK_OK;
      
    ex_queue_entry * pentry_down = qparent_.down->getHeadEntry(); 
    ExTimeoutPrivateState & pstate =
      *((ExTimeoutPrivateState*) pentry_down->pstate);

    // Calculate the timeout actual value
    Lng32 timeoutValue = 0; 
    NABoolean goodTimeoutValue = TRUE ;
    if (timeoutValueExpr()) {
      if ( timeoutValueExpr()->eval(pentry_down->getAtp(), workAtp_) 
	   == ex_expr::EXPR_ERROR ) { // expression did not yield a valid value
	handleErrors(pentry_down, pentry_down->getAtp()->getDiagsArea()); 
	goodTimeoutValue = FALSE ;
      } else {
	tupp TP = workAtp_->getTupp(timeoutTdb().workCriDesc_->noTuples()-1);
	timeoutValue = *(Lng32 *)TP.getDataPointer(); // pointer is (char *)
      }
    }

    /****************************************************/
    /********   Do the actual SET TIMEOUT work   ********/
    /**                                                **/
    /** The scope of the work is only making changes   **/
    /** to the global timeout data kept at the context **/
    /****************************************************/

    // Get the global timeout-data object
    ContextCli * currContext = getGlobals()->castToExExeStmtGlobals()->
      castToExMasterStmtGlobals()->getStatement()->getContext();
    
    TimeoutData * GlobalTimeouts = currContext->getTimeouts();

#if _DEBUG    // For debugging only !!!!!
    if ( getenv("DEBUG_TIMEOUT") ) {
      ComDiagsArea* diagsArea = 
	ComDiagsArea::allocate (getGlobals()->getDefaultHeap());
      char errmsg[120];

      if ( timeoutTdb().isStream() ) {   // it was a SET STREAM TIMEOUT
	if ( GlobalTimeouts->isStreamTimeoutSet() ) {
	  sprintf(errmsg, "Stream timeout set to %d\n",
		  GlobalTimeouts->getStreamTimeout() );
	} else sprintf(errmsg, "Stream timeout was NOT SET ! \n");
      } // lock timeout -- not stream
      else {
	if ( theTableName_[0] == '*' ) { // For all tables
	  sprintf(errmsg, "Number of lock timeouts set: %d\n",
		  GlobalTimeouts->entries() );
	} else {
	  Lng32 timeoutValue;
	  NABoolean found = 
	    GlobalTimeouts->getLockTimeout(theTableName_, timeoutValue );
	  if ( ! found ) 
	    sprintf(errmsg, "Lock timeout for table %s was NOT SET ! \n",
		    theTableName_ );
	  else sprintf(errmsg, "Lock timeout for table %s is %d \n",
		       theTableName_ , timeoutValue );
	}
      }
      // emit message as an error ( msg 3066 has no text of its own )
      *diagsArea << DgSqlCode(-3066)
		<< DgString0(errmsg) ;
      ExHandleArkcmpErrors(qparent_, pentry_down, 0, getGlobals(), 
			   diagsArea, (ExeErrorCode) -3066 );
    }  // end of debugging section  
    else   
#endif    

    if ( goodTimeoutValue ) {

      // Update the globals as needed
      if ( timeoutTdb().isStream() ) {   // it was a SET STREAM TIMEOUT
	if ( timeoutTdb().isReset() )  // it was a RESET
	  GlobalTimeouts->resetStreamTimeout(); 
	else                           // it was a SET (with a value)
	  GlobalTimeouts->setStreamTimeout(timeoutValue);
      }
      else {                     // setting a LOCK TIMEOUT
	// TBD =============>>> Check if FORALL string includes CAT.SCH ......
	if ( theTableName_[0] == '*' ) { // For all tables
	  if ( timeoutTdb().isReset() )  // it was a RESET
	    GlobalTimeouts->resetAllLockTimeout();
	  else GlobalTimeouts->setAllLockTimeout(timeoutValue);
	}
	else {  // per specific table
	  if ( timeoutTdb().isReset() )  // it was a RESET
	    GlobalTimeouts->resetTableLockTimeout( theTableName_ );
	  else GlobalTimeouts->setTableLockTimeout(theTableName_,timeoutValue);
	}
      }

      // execution of every SET TIMEOUT stmt increments the change counter !!
      currContext->incrementTimeoutChangeCounter();

      // clear up (i.e. deallocate) the global timeout data, if possible
      if ( GlobalTimeouts->noLockTimeoutsSet() &&
	   ! GlobalTimeouts->isStreamTimeoutSet() )
	currContext->clearTimeoutData();

    } // end of if ( goodTimeoutValue )

    /**********  at this point the actual work is done  ******************/
      
    // all ok. Return EOF.
    ex_queue_entry * up_entry = qparent_.up->getTailEntry();
      
    up_entry->upState.parentIndex = 
      pentry_down->downState.parentIndex;
      
    up_entry->upState.setMatchNo(0);
    up_entry->upState.status = ex_queue::Q_NO_DATA;
      
    // insert into parent
    qparent_.up->insert();
    
    qparent_.down->removeHead();
  }  
  return WORK_OK;
}
Esempio n. 23
0
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
    int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
    unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx;
    int len;
    int plaintext_len;
    int ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    /*
    if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
        handleErrors();
        */

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    /*
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
        handleErrors();
        */

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
     */
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0)
    {
        /* Success */
        plaintext_len += len;
        return plaintext_len;
    }
    else
    {
        /* Verify failed */
        return -1;
    }
}
Esempio n. 24
0
int main(int argc, char **argv) {
  int i;
  for (i=1;i<argc;i++) {
    if (argv[i][0]=='-') {
      // option
      char *a = argv[i];
      if (!strcmp(a,"-h") || !strcmp(a,"--help")) {
        show_help();
        exit(1);
      } else if (!strcmp(a,"-e") || !strcmp(a,"--eval")) {
        if (i+1>=argc) die("Expecting an extra argument\n");
        jshInit();
        jsvInit();
        jsiInit(true);
        addNativeFunction("quit", nativeQuit);
        jsvUnLock(jspEvaluate(argv[i+1], false));
        int errCode = handleErrors();
        isRunning = !errCode;
        bool isBusy = true;
        while (isRunning && (jsiHasTimers() || isBusy))
          isBusy = jsiLoop();
        jsiKill();
        jsvKill();
        jshKill();
        exit(errCode);
      } else if (!strcmp(a,"--test")) {
        if (i+1>=argc) die("Expecting an extra argument\n");
        bool ok = run_test(argv[i+1]);
        exit(ok ? 0 : 1);
      } else if (!strcmp(a,"--test-all")) {
        bool ok = run_all_tests();
        exit(ok ? 0 : 1);
      } else if (!strcmp(a,"--test-mem-all")) {
        bool ok = run_memory_tests(0);
        exit(ok ? 0 : 1);
      } else if (!strcmp(a,"--test-mem")) {
        if (i+1>=argc) die("Expecting an extra argument\n");
        bool ok = run_memory_test(argv[i+1], 0);
        exit(ok ? 0 : 1);
      } else if (!strcmp(a,"--test-mem-n")) {
        if (i+2>=argc) die("Expecting an extra 2 arguments\n");
        bool ok = run_memory_test(argv[i+1], atoi(argv[i+2]));
        exit(ok ? 0 : 1);
      } else {
        printf("Unknown Argument %s\n", a);
        show_help();
        exit(1);
      }
    }
  }

  if (argc==1) {
    printf("Interactive mode.\n");
  } else if (argc==2) {
    // single file - just run it
    char *buffer = read_file(argv[1]);
    if (!buffer) exit(1);
    // check for '#' as the first char, and if so, skip the first line
    char *cmd = buffer;
    if (cmd[0]=='#') {
      while (cmd[0] && cmd[0]!='\n') cmd++;
      if (cmd[0]=='\n') cmd++;
    }
    jshInit();
    jsvInit();
    jsiInit(false /* do not autoload!!! */);
    addNativeFunction("quit", nativeQuit);
    jsvUnLock(jspEvaluate(cmd, true));
    int errCode = handleErrors();
    free(buffer);
    isRunning = !errCode;
    bool isBusy = true;
    while (isRunning && (jsiHasTimers() || isBusy))
      isBusy = jsiLoop();
    jsiKill();
    jsvKill();
    jshKill();
    exit(errCode);
  } else {
    printf("Unknown arguments!\n");
    show_help();
    exit(1);
  }

  printf("Size of JsVar is now %d bytes\n", (int)sizeof(JsVar));
  printf("Size of JsVarRef is now %d bytes\n", (int)sizeof(JsVarRef));

#ifndef __MINGW32__
  struct sigaction sa;
  sa.sa_handler = sig_handler;
  sa.sa_flags = 0;
  sigemptyset(&sa.sa_mask);
  if (sigaction(SIGINT, &sa, NULL) == -1)
    printf("Adding SIGINT hook failed\n");
  else
    printf("Added SIGINT hook\n");
  if (sigaction(SIGHUP, &sa, NULL) == -1)
    printf("Adding SIGHUP hook failed\n");
  else
    printf("Added SIGHUP hook\n");
  if (sigaction(SIGTERM, &sa, NULL) == -1)
    printf("Adding SIGTERM hook failed\n");
  else
    printf("Added SIGTERM hook\n");
#endif//!__MINGW32__

  jshInit();
  jsvInit();
  jsiInit(true);

  addNativeFunction("quit", nativeQuit);
  addNativeFunction("interrupt", nativeInterrupt);

  while (isRunning) {
    jsiLoop();
  }
  jsiConsolePrint("\n");
  jsiKill();
  jsvGarbageCollect();
  jsvShowAllocated();
  jsvKill();
  jshKill();

  return 0;
}
Esempio n. 25
0
bool KNNntpClient::openConnection()
{
    currentGroup = QString::null;

    QString oldPrefix = errorPrefix;
    errorPrefix = i18n("Unable to connect.\nThe following error occurred:\n");

    if(!KNProtocolClient::openConnection())
        return false;

    progressValue = 30;

    int rep;
    if(!getNextResponse(rep))
        return false;

    if((rep < 200) || (rep > 299))          // RFC977: 2xx - Command ok
    {
        handleErrors();
        return false;
    }

    progressValue = 50;

    if(!sendCommand("MODE READER", rep))
        return false;

    if(rep == 500)
    {
#ifndef NDEBUG
        qDebug("knode: \"MODE READER\" command not recognized.");
#endif
    }
    else if((rep < 200) || (rep > 299))           // RFC977: 2xx - Command ok
    {
        handleErrors();
        return false;
    }

    progressValue = 60;

    // logon now, some newsserver send a incomplete group list otherwise
    if(account.needsLogon() && !account.user().isEmpty())
    {
        //qDebug("knode: user: %s",account.user().latin1());

        QCString command = "AUTHINFO USER ";
        command += account.user().local8Bit();
        if(!KNProtocolClient::sendCommand(command, rep))
            return false;

        if(rep == 381)           // 381 PASS required
        {
            //qDebug("knode: Password required");

            if(!account.pass().length())
            {
                job->setErrorString(i18n("Authentication failed.\nCheck your username and password."));
                job->setAuthError(true);
                return false;
            }

            //qDebug("knode: pass: %s",account.pass().latin1());

            command = "AUTHINFO PASS ";
            command += account.pass().local8Bit();
            if(!KNProtocolClient::sendCommand(command, rep))
                return false;

            if(rep == 281)          // 281 authorization success
            {
#ifndef NDEBUG
                qDebug("knode: Authorization successful");
#endif
            }
            else
            {
#ifndef NDEBUG
                qDebug("knode: Authorization failed");
#endif
                job->setErrorString(i18n("Authentication failed.\nCheck your username and password.\n\n%1").arg(getCurrentLine()));
                job->setAuthError(true);
                closeConnection();
                return false;
            }
        }
        else
        {
            if(rep == 281)          // 281 authorization success
            {
#ifndef NDEBUG
                qDebug("knode: Authorization successful");
#endif
            }
            else
            {
                if((rep == 482) || (rep == 500))  //482 Authentication rejected
                {
#ifndef NDEBUG
                    qDebug("knode: Authorization failed");    // we don't care, the server can refuse the info
#endif
                }
                else
                {
                    handleErrors();
                    return false;
                }
            }
        }
    }

    progressValue = 70;

    errorPrefix = oldPrefix;
    return true;
}
Esempio n. 26
0
void KNNntpClient::doFetchNewHeaders()
{
    KNGroup *target = static_cast<KNGroup *>(job->data());
    char *s;
    int first = 0, last = 0, oldlast = 0, toFetch = 0, rep = 0;
    QCString cmd;

    target->setLastFetchCount(0);

    sendSignal(TSdownloadNew);
    errorPrefix = i18n("No new articles could be retrieved for\n%1/%2.\nThe following error occurred:\n")
                  .arg(account.server()).arg(target->groupname());

    cmd = "GROUP ";
    cmd += target->groupname().utf8();
    if(!sendCommandWCheck(cmd, 211))         // 211 n f l s group selected
    {
        return;
    }

    currentGroup = target->groupname();

    progressValue = 90;

    s = strchr(getCurrentLine(), ' ');
    if(s)
    {
        s++;
        s = strchr(s, ' ');
    }
    if(s)
    {
        s++;
        first = atoi(s);
        target->setFirstNr(first);
        s = strchr(s, ' ');
    }
    if(s)
    {
        last = atoi(s);
    }
    else
    {
        QString tmp = i18n("No new articles could be retrieved.\nThe server sent a malformatted response:\n");
        tmp += getCurrentLine();
        job->setErrorString(tmp);
        closeConnection();
        return;
    }

    if(target->lastNr() == 0)   //first fetch
    {
        if(first > 0)
            oldlast = first - 1;
        else
            oldlast = first;
    }
    else
        oldlast = target->lastNr();

    toFetch = last - oldlast;
    //qDebug("knode: last %d  oldlast %d  toFetch %d\n",last,oldlast,toFetch);

    if(toFetch <= 0)
    {
        //qDebug("knode: No new Articles in group\n");
        target->setLastNr(last);     // don't get stuck when the article numbers wrap
        return;
    }

    if(toFetch > target->maxFetch())
    {
        toFetch = target->maxFetch();
        //qDebug("knode: Fetching only %d articles\n",toFetch);
    }

    progressValue = 100;
    predictedLines = toFetch;

    // get list of additional headers provided by the XOVER command
    // see RFC 2980 section 2.1.7
    QStrList headerformat;
    cmd = "LIST OVERVIEW.FMT";
    if(sendCommand(cmd, rep) && rep == 215)
    {
        QStrList tmp;
        if(getMsg(tmp))
        {
            for(QCString s = tmp.first(); s; s = tmp.next())
            {
                s = s.stripWhiteSpace();
                // remove the mandatory xover header
                if(s == "Subject:" || s == "From:" || s == "Date:" || s == "Message-ID:"
                        || s == "References:" || s == "Bytes:" || s == "Lines:")
                    continue;
                else
                    headerformat.append(s);
            }
        }
    }

    //qDebug("knode: KNNntpClient::doFetchNewHeaders() : xover %d-%d", last-toFetch+1, last);
    cmd.sprintf("xover %d-%d", last - toFetch + 1, last);
    if(!sendCommand(cmd, rep))
        return;

    // no articles in selected range...
    if(rep == 420)          // 420 No article(s) selected
    {
        target->setLastNr(last);
        return;
    }
    else if(rep != 224)     // 224 success
    {
        handleErrors();
        return;
    }

    QStrList headers;
    if(!getMsg(headers))
    {
        return;
    }

    progressValue = 1000;
    sendSignal(TSprogressUpdate);

    sendSignal(TSsortNew);

    mutex.lock();
    target->insortNewHeaders(&headers, &headerformat, this);
    target->setLastNr(last);
    mutex.unlock();
}
Esempio n. 27
0
bool ScriptManager::_evaluate(QScriptProgram program) {
    mLastReturnValue = mScriptEngine->evaluate(program);
    return handleErrors(program.fileName());
}
Esempio n. 28
0
	NONS_VariableMember *ExpressionCompiler::retrieve(NONS_VariableStore *store){
		if (!this->expr)
			return 0;
		this->error=NONS_UNDEFINED_ERROR;

		std::vector<Expression *> full_expression;
		this->expr->vectorize(full_expression);

		operator_f f=full_expression.back()->op;
		bool integer=(f==integer_dereference),
			string=(f==string_dereference),
			array=(f==array_indexing);
		if (!integer && !string && !array){
			this->error=NONS_NOT_A_DEREFERENCE;
			return 0;
		}

		std::vector<Value *> evaluation_stack;
		ErrorCode e=this->run(store,0,full_expression,evaluation_stack,full_expression.size()-1);
		if (e!=NONS_NO_ERROR){
			this->error=e;
			return 0;
		}
		if (integer || string){
			if (evaluation_stack.size()>1){
				freePointerVector(evaluation_stack);
				return 0;
			}
			if (evaluation_stack[0]->type!=Value::INTEGER){
				this->error=NONS_EXPECTED_INTEGRAL_VALUE;
				freePointerVector(evaluation_stack);
				return 0;
			}
			NONS_Variable *var=store->retrieve((Sint32)evaluation_stack[0]->integer,&this->error);
			freePointerVector(evaluation_stack);
			if (!var)
				return 0;
			return (integer)?var->intValue:var->wcsValue;
		}
		ulong indices=full_expression.back()->operands.size()-1,
			base=evaluation_stack.size()-indices-1;
		if (evaluation_stack.size()>indices+1){
			freePointerVector(evaluation_stack);
			return 0;
		}
		Sint32 arrayNo=0;
		std::vector<Sint32> v(indices);
		for (ulong a=base;a<base+indices+1;a++){
			if (evaluation_stack[a]->type!=Value::INTEGER){
				this->error=NONS_EXPECTED_INTEGRAL_VALUE;
				freePointerVector(evaluation_stack);
				return 0;
			}
			((a!=base)?v[a-base-1]:arrayNo)=evaluation_stack[a]->integer;
		}
		freePointerVector(evaluation_stack);
		ulong errored;
		NONS_VariableMember *member=store->retrieveFromArray(arrayNo,v,&e,&errored);
		if (e!=NONS_NO_ERROR){
			this->error=e;
			member=0;
			switch (e){
				case NONS_UNDEFINED_ARRAY:
					handleErrors(this->error,0,"ExpressionCompiler::retrieve",1);
					break;
				case NONS_ARRAY_INDEX_OUT_OF_BOUNDS:
					handleErrors(
						this->error,
						0,"ExpressionCompiler::retrieve",1,
						L"The index is: "+::itoaw(errored)+L" (contains "+::itoaw(v[errored])+L")"
					);
					break;
				case NONS_TOO_MANY_DIMENSIONS:
					handleErrors(this->error,0,"ExpressionCompiler::retrieve",1);
					break;
			}
		}
		return member;
	}
Esempio n. 29
0
unsigned char * gen_random_key(int keyleninbytes) {
	unsigned char *buffer = (unsigned char *)malloc(keyleninbytes);
	if(1 != RAND_bytes(buffer, keyleninbytes)) handleErrors();
	return buffer;
}
Esempio n. 30
0
int main()
{
	EVP_PKEY_CTX *pctx, *kctx;
	EVP_PKEY_CTX *ctx;
	unsigned char *secret;
	EVP_PKEY *pkey = NULL, *peerkey, *params = NULL;
	/* NB: assumes pkey, peerkey have been already set up */

	/* Create the context for parameter generation */
	if(NULL == (pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))) handleErrors();

	/* Initialise the parameter generation */
	if(1 != EVP_PKEY_paramgen_init(pctx)) handleErrors();

	/* We're going to use the ANSI X9.62 Prime 256v1 curve */
	if(1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) handleErrors();

	/* Create the parameter object params */
	if (!EVP_PKEY_paramgen(pctx, &params)) handleErrors();

	/* Create the context for the key generation */
	if(NULL == (kctx = EVP_PKEY_CTX_new(params, NULL))) handleErrors();

	/* Generate the key */
	if(1 != EVP_PKEY_keygen_init(kctx)) handleErrors();
	if (1 != EVP_PKEY_keygen(kctx, &pkey)) handleErrors();

	/* Get the peer's public key, and provide the peer with our public key -
	 * how this is done will be specific to your circumstances */
	peerkey = get_peerkey(pkey);

	/* Create the context for the shared secret derivation */
	if(NULL == (ctx = EVP_PKEY_CTX_new(pkey, NULL))) handleErrors();

	/* Initialise */
	if(1 != EVP_PKEY_derive_init(ctx)) handleErrors();

	/* Provide the peer public key */
	if(1 != EVP_PKEY_derive_set_peer(ctx, peerkey)) handleErrors();

	/* Determine buffer length for shared secret */
	if(1 != EVP_PKEY_derive(ctx, NULL, secret_len)) handleErrors();

	/* Create the buffer */
	if(NULL == (secret = OPENSSL_malloc(*secret_len))) handleErrors();

	/* Derive the shared secret */
	if(1 != (EVP_PKEY_derive(ctx, secret, secret_len))) handleErrors();

	EVP_PKEY_CTX_free(ctx);
	EVP_PKEY_free(peerkey);
	EVP_PKEY_free(pkey);
	EVP_PKEY_CTX_free(kctx);
	EVP_PKEY_free(params);
	EVP_PKEY_CTX_free(pctx);

	/* Never use a derived secret directly. Typically it is passed
	 * through some hash function to produce a key */

	return 0;
}