Ejemplo n.º 1
0
static void
server (int fd, int server_init)
{
int ret;
char buffer[MAX_BUF + 1];
  /* this must be called once in the program
   */
  global_init ();

  if (debug)
    {
      gnutls_global_set_log_function (server_log_func);
      gnutls_global_set_log_level (4711);
    }

  gnutls_anon_allocate_server_credentials (&anoncred);

  session = initialize_tls_session ();

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);
  gnutls_transport_set_push_function (session, push);

  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
  if (ret < 0)
    {
      close (fd);
      gnutls_deinit (session);
      fail ("server: Handshake has failed (%s)\n\n", gnutls_strerror (ret));
      terminate();
    }
  if (debug)
    success ("server: Handshake was completed\n");

  if (debug)
    success ("server: TLS version is: %s\n",
             gnutls_protocol_get_name (gnutls_protocol_get_version
                                       (session)));

  /* see the Getting peer's information example */
  /* print_info(session); */

  if (server_init)
    {
      if (debug) success("server: Sending dummy packet\n");
      ret = gnutls_rehandshake(session);
      if (ret < 0)
        {
          fail ("gnutls_rehandshake: %s\n", gnutls_strerror(ret));
          terminate();
        }

      if (debug) success("server: Initiating rehandshake\n");
      do 
        {
          ret = gnutls_handshake (session);
        }
      while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

      if (ret < 0)
        {
          fail ("server: 2nd gnutls_handshake: %s\n", gnutls_strerror(ret));
          terminate();
        }
    }

  for (;;)
    {
      memset (buffer, 0, MAX_BUF + 1);

      do {
        ret = gnutls_record_recv (session, buffer, MAX_BUF);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

      if (ret == 0)
        {
          if (debug)
            success ("server: Peer has closed the GnuTLS connection\n");
          break;
        }
      else if (ret < 0)
        {
          if (!server_init && ret == GNUTLS_E_REHANDSHAKE)
            {
              if (debug) success("Initiating rehandshake due to client request\n");
              do 
                {
                  ret = gnutls_handshake (session);
                }
              while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
              if (ret == 0) break;
            }

          fail ("server: Received corrupted data(%s). Closing...\n", gnutls_strerror(ret));
          terminate();
        }
      else if (ret > 0)
        {
          /* echo data back to the client
           */
          do {
            ret = gnutls_record_send (session, buffer, strlen (buffer));
          } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
        }
    }
  

  /* do not wait for the peer to close the connection.
   */
  gnutls_bye (session, GNUTLS_SHUT_WR);

  close (fd);
  gnutls_deinit (session);

  gnutls_anon_free_server_credentials (anoncred);

  gnutls_global_deinit ();

  if (debug)
    success ("server: finished\n");
}
Ejemplo n.º 2
0
static
void
makeprocs(bool dowait)
{
    int i, status, failcount;
    struct usem s1, s2;
    pid_t pids[NJOBS];

    if (dowait) {
        semcreate("1", &s1);
        semcreate("2", &s2);
    }

    tprintf("Job size approximately %lu bytes\n", (unsigned long) JOBSIZE);
    tprintf("Forking %d jobs; total load %luk\n", NJOBS,
            (unsigned long) (NJOBS * JOBSIZE)/1024);

    for (i=0; i<NJOBS; i++) {
        pids[i] = fork();
        if (pids[i]<0) {
            warn("fork");
        }
        if (pids[i]==0) {
            /* child */
            if (dowait) {
                //tsay("Process %d forked\n", i);
                semopen(&s1);
                semopen(&s2);
                semV(&s1, 1);
                semP(&s2, 1);
                semclose(&s1);
                semclose(&s2);
            }
            go(i);
        }
    }

    if (dowait) {
        semopen(&s1);
        semopen(&s2);
        //tsay("Waiting for fork...\n");
        semP(&s1, NJOBS);
        //tsay("Starting computation.\n");
        semV(&s2, NJOBS);
    }

    failcount=0;
    for (i=0; i<NJOBS; i++) {
        if (pids[i]<0) {
            failcount++;
        }
        else {
            if (waitpid(pids[i], &status, 0)<0) {
                err(1, "waitpid");
            }
            if (status_is_failure(status)) {
                failcount++;
            }
        }
    }

    if (failcount>0) {
        printf("%d subprocesses failed\n", failcount);
        exit(1);
    }
    nprintf("\n");
    tprintf("Test complete\n");
    success(TEST161_SUCCESS, SECRET, "/testbin/parallelvm");

    semclose(&s1);
    semclose(&s2);
    semdestroy(&s1);
    semdestroy(&s2);
}
Ejemplo n.º 3
0
void GenericImage::write_png(const char *filename)
{	
    int w = width;
    int h = height;
    int c = components;
    int b = pix_depth;
    void* p = pixels;

    FILE       *filep = NULL;
    png_structp writep = NULL;
    png_infop   infop = NULL;
    png_bytep  *bytep = NULL;

    /* Initialize all PNG import data structures. */

    if (!(filep = fopen(filename, "wb")))
        fail("can't open file\n");
    if (!(writep = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0)))
        fail("can't create png write struct\n");
    if (!(infop = png_create_info_struct(writep)))
        fail("can't create png info struct\n");

    /* Enable the default PNG error handler. */

    if (setjmp(png_jmpbuf(writep)) == 0)
    {
        png_init_io (writep, filep);
        
        /* Set the image information here.  Width and height are up to 2^31,
         * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
         * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
         * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
         * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
         * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
         * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
         */
        int color_type;
        switch (c)
        {
        case 1: color_type = PNG_COLOR_TYPE_GRAY; break;
        case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break;
        case 3: color_type = PNG_COLOR_TYPE_RGB; break;
        case 4: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break;
        default: color_type = PNG_COLOR_TYPE_RGB;
        }
        png_set_compression_level(writep, 9);
        png_set_IHDR(writep, infop, w, h, b*8, color_type,
                     PNG_INTERLACE_NONE, 
                     PNG_COMPRESSION_TYPE_DEFAULT, 
                     PNG_FILTER_TYPE_DEFAULT);
    	png_write_info(writep, infop);
    		
    	/* pack pixels into bytes */
        png_set_packing(writep);
    		      
    	
        bytep = (png_bytep *) png_malloc(writep, 
                                         h * sizeof (png_bytep));
    	for (int k = 0; k < h; k++)
            bytep[k] = (png_bytep)p + k*w*c*b;

        /* write out the entire image data in one call */
        //png_write_image(writep, bytep);
      	/* Write a few rows at a time. */
      	//png_write_rows(writep, &bytep[first_row], number_of_rows);

      	/* If you are only writing one row at a time, this works */
//       	for (int y = 0; y < h; y++)
//       	{
//             png_write_rows(writep, &row_pointers[y], 1);
//       	}

//         png_write_end(writep, infop);
	   	
        //set rows and write png
        png_set_rows(writep, infop, bytep);
        //png_write_png(writep, infop, PNG_TRANSFORM_STRIP_16 |
        //                           PNG_TRANSFORM_PACKING, NULL);   
        png_write_png (writep, infop, PNG_TRANSFORM_SWAP_ENDIAN, NULL);
        free(bytep);
    }
    else fail("can't write png data\n");

    /* Release all resources. */

    png_destroy_write_struct(&writep, &infop);
    fclose(filep);

    success("write png file\n");
}
Ejemplo n.º 4
0
static int test_ftruncate(int len, int mode)
{
    const char *data = testdata;
    int datalen = testdatalen;
    int res;
    int fd;

    start_test("ftruncate(%u) mode: 0%03o", len, mode);
    res = create_file(testfile, data, datalen);
    if (res == -1)
        return -1;

    fd = open(testfile, O_WRONLY);
    if (fd == -1) {
        PERROR("open");
        return -1;
    }

    res = fchmod(fd, mode);
    if (res == -1) {
        PERROR("fchmod");
        close(fd);
        return -1;
    }
    res = check_mode(testfile, mode);
    if (res == -1) {
        close(fd);
        return -1;
    }
    res = ftruncate(fd, len);
    if (res == -1) {
        PERROR("ftruncate");
        close(fd);
        return -1;
    }
    close(fd);
    res = check_size(testfile, len);
    if (res == -1)
        return -1;

    if (len > 0) {
        if (len <= datalen) {
            res = check_data(testfile, data, 0, len);
            if (res == -1)
                return -1;
        } else {
            res = check_data(testfile, data, 0, datalen);
            if (res == -1)
                return -1;
            res = check_data(testfile, zerodata, datalen,
                             len - datalen);
            if (res == -1)
                return -1;
        }
    }
    res = unlink(testfile);
    if (res == -1) {
        PERROR("unlink");
        return -1;
    }
    res = check_nonexist(testfile);
    if (res == -1)
        return -1;

    success();
    return 0;
}
Ejemplo n.º 5
0
static void server(int fd)
{
	int ret;
	gnutls_certificate_credentials_t xcred;
	gnutls_session_t session;

	/* this must be called once in the program
	 */
	global_init();

	if (debug) {
		gnutls_global_set_log_function(server_log_func);
		gnutls_global_set_log_level(4711);
	}

	gnutls_certificate_allocate_credentials(&xcred);

	ret = gnutls_certificate_set_x509_key_mem(xcred,
					    &server_cert, &server_key,
					    GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		exit(1);

	gnutls_init(&session, GNUTLS_SERVER);
	gnutls_handshake_set_timeout(session, 20 * 1000);

	/* avoid calling all the priority functions, since the defaults
	 * are adequate.
	 */
	gnutls_priority_set_direct(session,
				   "NORMAL:-KX-ALL:+ECDHE-RSA",
				   NULL);

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);

	gnutls_transport_set_int(session, fd);

	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret != GNUTLS_E_UNEXPECTED_EXTENSIONS_LENGTH) {
		close(fd);
		gnutls_deinit(session);
		fail("server: Handshake did not fail with GNUTLS_E_UNEXPECTED_EXTENSIONS_LENGTH (%s)\n\n",
		     gnutls_strerror(ret));
		terminate();
	}
	success("server: Handshake failed as expected\n");

	close(fd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(xcred);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Ejemplo n.º 6
0
static void server(int fd)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_certificate_credentials_t serverx509cred;
	gnutls_anon_server_credentials_t anoncred;
	gnutls_session_t session;
	/* this must be called once in the program
	 */
	global_init();

	if (debug) {
		gnutls_global_set_log_function(server_log_func);
		gnutls_global_set_log_level(4711);
	}

	assert(gnutls_anon_allocate_server_credentials(&anoncred) >= 0);
	assert(gnutls_certificate_allocate_credentials(&serverx509cred) >= 0);
	assert(gnutls_certificate_set_x509_key_mem(serverx509cred,
						   &server_cert, &server_key,
						   GNUTLS_X509_FMT_PEM) >= 0);

	gnutls_init(&session, GNUTLS_SERVER | GNUTLS_DATAGRAM);
	gnutls_dtls_set_mtu(session, MTU);

	/* avoid calling all the priority functions, since the defaults
	 * are adequate.
	 */
	assert(gnutls_priority_set_direct(session,
					  "NONE:+VERS-DTLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ECDHE-RSA:+ANON-ECDH:+CURVE-ALL",
					  NULL) >= 0);

	gnutls_credentials_set(session, GNUTLS_CRD_ANON, anoncred);
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, serverx509cred);

	gnutls_transport_set_int(session, fd);
	gnutls_transport_set_push_function(session, push);

	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
	if (ret < 0) {
		close(fd);
		gnutls_deinit(session);
		fail("server: Handshake has failed (%s)\n\n",
		     gnutls_strerror(ret));
		terminate();
	}
	if (debug)
		success("server: Handshake was completed\n");

	if (debug)
		success("server: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));

	if (gnutls_kx_get(session) != GNUTLS_KX_ANON_ECDH) {
		fail("did not negotiate an anonymous ciphersuite on initial auth\n");
	}

	/* see the Getting peer's information example */
	/* print_info(session); */

	if (debug)
		success("server: Sending dummy packet\n");
	ret = gnutls_rehandshake(session);
	if (ret < 0) {
		fail("gnutls_rehandshake: %s\n", gnutls_strerror(ret));
		terminate();
	}

	if (debug)
		success("server: Initiating rehandshake\n");
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("server: 2nd gnutls_handshake: %s\n",
		     gnutls_strerror(ret));
		terminate();
	}

	for (;;) {
		memset(buffer, 0, MAX_BUF + 1);

		do {
			ret = gnutls_record_recv(session, buffer, MAX_BUF);
		} while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

		if (ret == 0) {
			if (debug)
				success
				    ("server: Peer has closed the GnuTLS connection\n");
			break;
		} else if (ret < 0) {
			fail("server: Received corrupted data(%s). Closing...\n", gnutls_strerror(ret));
			terminate();
		} else if (ret > 0) {
			/* echo data back to the client
			 */
			do {
				ret =
				    gnutls_record_send(session, buffer,
							strlen(buffer));
			} while (ret == GNUTLS_E_AGAIN
				 || ret == GNUTLS_E_INTERRUPTED);
		}
	}

	if (gnutls_kx_get(session) != GNUTLS_KX_ECDHE_RSA) {
		fail("did not negotiate a certificate ciphersuite on second auth\n");
	}

	/* do not wait for the peer to close the connection.
	 */
	gnutls_bye(session, GNUTLS_SHUT_WR);

	close(fd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(serverx509cred);
	gnutls_anon_free_server_credentials(anoncred);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Ejemplo n.º 7
0
static void client(int fd)
{
	int ret;
	unsigned int status;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;
	/* Need to enable anonymous KX specifically. */

	gnutls_global_set_time_function(mytime);
	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(7);
	}

	gnutls_certificate_allocate_credentials(&x509_cred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT);

	/* Use default priorities */
	gnutls_priority_set_direct(session, "NORMAL:-KX-ALL:+ECDHE-RSA", NULL);

	gnutls_handshake_set_hook_function(session, GNUTLS_HANDSHAKE_CERTIFICATE_STATUS,
					   GNUTLS_HOOK_POST,
					   handshake_callback);

	/* put the anonymous credentials to the current session
	 */
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret == GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM) {
		/* success */
		goto end;
	}

	if (ret < 0) {
		fail("client: Handshake failed: %s\n", gnutls_strerror(ret));
		terminate();
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

	if (debug)
		success("client: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));

	if (received == 1) {
		fail("client: received certificate status when we shouldn't.\n");
		terminate();
	}

	ret = gnutls_certificate_verify_peers2(session, &status);
	if (ret != GNUTLS_E_SUCCESS) {
		fail("client: Peer certificate validation failed: %s\n", gnutls_strerror(ret));
		terminate();
	}
	else {
		if (status & GNUTLS_CERT_MISSING_OCSP_STATUS) {
			success("client: Validation failed with GNUTLS_CERT_MISSING_OCSP_STATUS\n");
		}
		else {
			fail("client: Validation status does not include GNUTLS_CERT_MISSING_OCSP_STATUS. Status is %d\n", status);
			terminate();
		}
	}

	gnutls_bye(session, GNUTLS_SHUT_WR);

      end:

	close(fd);

	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();
}
Ejemplo n.º 8
0
void KeyCreator::accept()
{
    // Validate data:

    if (editStorePass1->text().length() < 6) {
        emit warning(NULL, tr("Password must be at least 6 characters."));
        editStorePass1->setFocus();
        editStorePass1->selectAll();
        return;
    }

    if (editStorePass1->text() != editStorePass2->text()) {
        emit warning(NULL, tr("Passwords do not match."));
        editStorePass2->setFocus();
        editStorePass2->selectAll();
        return;
    }

    if (editAlias->text().isEmpty()) {
        emit warning(NULL, tr("Enter alias name."));
        editAlias->setFocus();
        editAlias->selectAll();
        return;
    }

    if (editAliasPass1->text() != editAliasPass2->text()) {
        emit warning(NULL, tr("Passwords do not match."));
        editAliasPass2->setFocus();
        editAliasPass2->selectAll();
        return;
    }

    if (editAliasPass1->text().length() < 6) {
        emit warning(NULL, tr("Password must be at least 6 characters."));
        editAliasPass1->setFocus();
        editAliasPass1->selectAll();
        return;
    }

    // Create KeyStore and Alias:

    const QString FILENAME = QFileDialog::getSaveFileName(this, NULL, NULL, "KeyStore (*.keystore)");
    if (FILENAME.isEmpty()) {
        return;
    }
    qDebug() << "Creating KeyStore...";
    const QString ENV_PATH = qgetenv("PATH");
    const QString JAVA_HOME = qgetenv("JAVA_HOME");
    const QString KEYTOOL_CMD =
            QString("keytool -genkeypair -v -keystore \"%1\" -storepass \"%10\""
                    " -alias \"%2\" -keyalg RSA -keysize 2048"
                    " -dname \"CN=%3, OU=%4, O=%5, L=%6, S=%7, C=%8\""
                    " -validity %9 -keypass \"%11\"")
                        .arg(FILENAME)
                        .arg(editAlias->text())
                        .arg(editName->text())
                        .arg(editUnit->text())
                        .arg(editOrgan->text())
                        .arg(editCity->text())
                        .arg(editState->text())
                        .arg(editCountry->text())
                        .arg(editYears->text().toInt() * 365);
    qputenv("PATH", ENV_PATH.toStdString().c_str());
    qputenv("PATH", QString("%1;%2/bin").arg(ENV_PATH, JAVA_HOME).toStdString().c_str());
    qDebug() << qPrintable(KEYTOOL_CMD.arg("*****", "*****"));
    QProcess p;
    p.start(KEYTOOL_CMD.arg(editStorePass1->text(), editAliasPass1->text()));
    qputenv("PATH", ENV_PATH.toStdString().c_str());

    if (p.waitForStarted(-1)) {
        p.waitForFinished(10000);
        if (p.exitCode() != 0) {
            QString error_text = p.readAllStandardError().trimmed();
            if (error_text.isEmpty()) error_text = p.readAllStandardOutput().trimmed();
            qDebug() << qPrintable(QString("Keytool exit code: %1").arg(p.exitCode()));
            qDebug() << error_text;
            emit warning("Keytool", tr("%1: invalid parameters").arg("Keytool"));
            return;
        }
    }
    else {
        const QString ERROR_TEXT = tr("Error starting %1.\n"
                                      "Check your JDK installation and "
                                      "PATH environment variable.").arg("Keytool");
        emit error("Keytool", ERROR_TEXT);
        return;
    }
    qDebug() << "Done.\n";
    emit success("Keytool", tr("KeyStore successfully created/updated!"));
    emit created(FILENAME);
    clear();
    QDialog::accept();
}
Ejemplo n.º 9
0
KeyManager::KeyManager(QWidget *parent) : QDialog(parent)
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowIcon(QIcon(":/gfx/key.png"));
    resize(540, 0);

    keyCreator = new KeyCreator(this);

    radioPem = new QRadioButton(this);
    radioKey = new QRadioButton(this);

    radioPem->setText("PEM/PK8");

    boxPem = new FileBox(this);
    boxPk8 = new FileBox(this);
    boxKey = new FileBox(this);

    boxPem->setTitle("PEM:");
    boxPk8->setTitle("PK8:");

    boxPem->setTitleWidth(26);
    boxPk8->setTitleWidth(26);

    boxPem->setFormats("PEM (*.pem);;");
    boxPk8->setFormats("PK8 (*.pk8);;");
    boxKey->setFormats("KeyStore (*.keystore);;");

    btnNew = new QPushButton(this);
    QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);

    labelAlias = new QLabel(this);
    labelAliasPass = new QLabel(this);
    labelStorePass = new QLabel(this);
    editAlias = new QLineEdit(this);
    editAliasPass = new QLineEdit(this);
    editStorePass = new QLineEdit(this);

    editAliasPass->setEchoMode(QLineEdit::Password);
    editStorePass->setEchoMode(QLineEdit::Password);

    groupPem = new QGroupBox(this);
    QVBoxLayout *layoutPem = new QVBoxLayout;
    layoutPem->addWidget(boxPem);
    layoutPem->addWidget(boxPk8);
    groupPem->setLayout(layoutPem);

    groupKey = new QGroupBox(this);
    QGridLayout *layoutKey = new QGridLayout;
    layoutKey->addWidget(boxKey, 0, 0, 1, 0);
    layoutKey->addWidget(labelStorePass, 1, 0);
    layoutKey->addWidget(editStorePass, 1, 1);
    layoutKey->addWidget(labelAlias, 2, 0, Qt::AlignLeft);
    layoutKey->addWidget(editAlias, 2, 1);
    layoutKey->addWidget(labelAliasPass, 3, 0, Qt::AlignLeft);
    layoutKey->addWidget(editAliasPass, 3, 1);
    layoutKey->addWidget(btnNew, 4, 0, 1, 0);
    groupKey->setLayout(layoutKey);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(radioPem);
    layout->addWidget(radioKey);
    layout->addWidget(groupPem);
    layout->addWidget(groupKey);
    layout->addWidget(buttons);

    connect(radioPem, SIGNAL(clicked()), this, SLOT(setOptionPem()));
    connect(radioKey, SIGNAL(clicked()), this, SLOT(setOptionKey()));
    connect(btnNew, SIGNAL(clicked()), keyCreator, SLOT(open()));
    connect(keyCreator, SIGNAL(created(QString)), this, SLOT(setFileKey(QString)));
    connect(keyCreator, SIGNAL(success(QString, QString)), this, SIGNAL(success(QString, QString)));
    connect(keyCreator, SIGNAL(warning(QString, QString)), this, SIGNAL(warning(QString, QString)));
    connect(keyCreator, SIGNAL(error(QString, QString)), this, SIGNAL(error(QString, QString)));
    connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
}
Ejemplo n.º 10
0
Archivo: name.c Proyecto: phreddrick/GB
void insurgency(int Playernum, int Governor, int APcount)
{
  int who, amount, eligible, them=0;
  racetype *Race, *alien;
  planettype *p;
  double x;
  int changed_hands, chance;
  register int i;
  
  if(Dir[Playernum-1][Governor].level != LEVEL_PLAN) {
      notify(Playernum, Governor, "You must 'cs' to the planet you wish to try it on.\n");
      return;
  }
  if(!control(Playernum, Governor, Stars[Dir[Playernum-1][Governor].snum])) {
      notify(Playernum, Governor, "You are not authorized to do that here.\n");
      return;
  }
/*  if(argn<3) {
      notify(Playernum, Governor, "The correct syntax is 'insurgency <race> <money>'\n");
      return;
  }*/
  if(!enufAP(Playernum,Governor, Stars[Dir[Playernum-1][Governor].snum]->AP[Playernum-1], APcount)) return;
  if(!(who=GetPlayer(args[1]))) {
      sprintf(buf,"No such player.\n");
      notify(Playernum, Governor, buf);
      return;
  }
  Race = races[Playernum-1];
  alien = races[who-1];
  if(alien->Guest) {
      notify(Playernum, Governor, "Don't be such a dickweed.\n");
      return;
  }
  if(who==Playernum) {
      notify(Playernum, Governor, "You can't revolt against yourself!\n");
      return;
  }
  eligible = 0;
  them = 0;
  for(i=0; i<Stars[Dir[Playernum-1][Governor].snum]->numplanets; i++) {
      getplanet(&p,Dir[Playernum-1][Governor].snum,i);
      eligible += p->info[Playernum-1].popn;
      them += p->info[who-1].popn;
      free(p);
  }
  if(!eligible) {
      notify(Playernum, Governor, "You must have population in the star system to attempt insurgency\n.");
      return;
  }
  getplanet(&p,Dir[Playernum-1][Governor].snum,Dir[Playernum-1][Governor].pnum);

  if(!p->info[who-1].popn) {
      notify(Playernum, Governor, "This player does not occupy this planet.\n");
      free(p);
      return;
  }
  
  sscanf(args[2], "%d", &amount);
  if(amount < 0) {
      notify(Playernum, Governor, "You have to use a positive amount of money.\n");
      free(p);
      return;
  }
  if(Race->governor[Governor].money < amount) {
      notify(Playernum, Governor, "Nice try.\n");
      free(p);
      return;
  }

  x = INSURG_FACTOR*(double)amount*
      (double)p->info[who-1].tax/(double)p->info[who-1].popn;
  x *= morale_factor((double)(Race->morale-alien->morale));
  x *= morale_factor((double)(eligible-them)/50.0);
  x *= morale_factor(10.0*(double)(Race->fighters*p->info[Playernum-1].troops-
				  alien->fighters*p->info[who-1].troops))/50.0;
  sprintf(buf, "x = %f\n", x);
  notify(Playernum, Governor, buf);
  chance = round_rand(200.0*atan((double)x)/3.14159265);
  sprintf(long_buf, "%s/%s: %s [%d] tries insurgency vs %s [%d]\n",
	  Stars[Dir[Playernum-1][Governor].snum]->name,
	  Stars[Dir[Playernum-1][Governor].snum]->pnames[Dir[Playernum-1][Governor].pnum],
	  Race->name, Playernum, alien->name, who);
  sprintf(buf, "\t%s: %d total civs [%d]  opposing %d total civs [%d]\n",
	  Stars[Dir[Playernum-1][Governor].snum]->name,
	  eligible, Playernum, them, who);
  strcat(long_buf, buf);
  sprintf(buf, "\t\t %ld morale [%d] vs %ld morale [%d]\n",
	  Race->morale, Playernum, alien->morale, who);
  strcat(long_buf, buf);
  sprintf(buf, "\t\t %d money against %ld population at tax rate %d%%\n",
	  amount, p->info[who-1].popn, p->info[who-1].tax);
  strcat(long_buf, buf);
  sprintf(buf, "Success chance is %d%%\n", chance);
  strcat(long_buf, buf);
  if(success(chance)) {
      changed_hands = revolt(p, who, Playernum);
      notify(Playernum, Governor, long_buf);
      sprintf(buf, "Success!  You liberate %d sector%s.\n", changed_hands,
                   (changed_hands == 1)?"":"s");
      notify(Playernum, Governor, buf);      
      sprintf(buf, 
        "A revolt on /%s/%s instigated by %s [%d] costs you %d sector%s\n", 
         Stars[Dir[Playernum-1][Governor].snum]->name, 
         Stars[Dir[Playernum-1][Governor].snum]->pnames[Dir[Playernum-1][Governor].pnum],
         Race->name, Playernum,
         changed_hands, (changed_hands == 1)?"":"s");
      strcat(long_buf, buf);
      warn(who, (int)Stars[Dir[Playernum-1][Governor].snum]->governor[who-1], long_buf);
      p->info[Playernum-1].tax = p->info[who-1].tax;
      /* you inherit their tax rate (insurgency wars he he ) */
      sprintf(buf, "/%s/%s: Successful insurgency by %s [%d] against %s [%d]\n",
	      Stars[Dir[Playernum-1][Governor].snum]->name,
	      Stars[Dir[Playernum-1][Governor].snum]->pnames[Dir[Playernum-1][Governor].pnum],
	      Race->name, Playernum, alien->name, who);
      post(buf, DECLARATION);
  } else {
      notify(Playernum, Governor, long_buf);
      notify(Playernum, Governor, "The insurgency failed!\n");
      sprintf(buf, 
        "A revolt on /%s/%s instigated by %s [%d] fails\n",
         Stars[Dir[Playernum-1][Governor].snum]->name, 
         Stars[Dir[Playernum-1][Governor].snum]->pnames[Dir[Playernum-1][Governor].pnum],
         Race->name, Playernum);
      strcat(long_buf, buf);
      warn(who, (int)Stars[Dir[Playernum-1][Governor].snum]->governor[who-1], long_buf);
      sprintf(buf, "/%s/%s: Failed insurgency by %s [%d] against %s [%d]\n",
	      Stars[Dir[Playernum-1][Governor].snum]->name,
	      Stars[Dir[Playernum-1][Governor].snum]->pnames[Dir[Playernum-1][Governor].pnum],
	      Race->name, Playernum, alien->name, who);
      post(buf, DECLARATION);
  }
  deductAPs(Playernum, Governor, APcount, Dir[Playernum-1][Governor].snum, 0);
  Race->governor[Governor].money -= amount;
  putrace(Race);
  free(p);
}
Ejemplo n.º 11
0
void doit(void)
{
	gnutls_x509_privkey_t key;
	gnutls_x509_crt_t crt;
	gnutls_pubkey_t pubkey;
	gnutls_privkey_t privkey;
	gnutls_datum_t out, out2;
	int ret;
	size_t i;

	global_init();

	for (i = 0; i < sizeof(key_dat) / sizeof(key_dat[0]); i++) {
		if (debug)
			success("loop %d\n", (int) i);

		ret = gnutls_x509_privkey_init(&key);
		if (ret < 0)
			fail("gnutls_x509_privkey_init\n");

		ret =
		    gnutls_x509_privkey_import(key, &key_dat[i],
					       GNUTLS_X509_FMT_PEM);
		if (ret < 0)
			fail("gnutls_x509_privkey_import\n");

		ret = gnutls_pubkey_init(&pubkey);
		if (ret < 0)
			fail("gnutls_privkey_init\n");

		ret = gnutls_privkey_init(&privkey);
		if (ret < 0)
			fail("gnutls_pubkey_init\n");

		ret = gnutls_privkey_import_x509(privkey, key, 0);
		if (ret < 0)
			fail("gnutls_privkey_import_x509\n");

		ret = gnutls_x509_crt_init(&crt);
		if (ret < 0)
			fail("gnutls_x509_crt_init\n");

		ret =
		    gnutls_x509_crt_import(crt, &cert_dat[i],
					   GNUTLS_X509_FMT_PEM);
		if (ret < 0)
			fail("gnutls_x509_crt_import\n");

		ret = gnutls_pubkey_import_x509(pubkey, crt, 0);
		if (ret < 0)
			fail("gnutls_x509_pubkey_import\n");


		ret =
		    gnutls_pubkey_encrypt_data(pubkey, 0, &hash_data,
					       &out);
		if (ret < 0)
			fail("gnutls_pubkey_encrypt_data\n");


		ret = gnutls_privkey_decrypt_data(privkey, 0, &out, &out2);
		if (ret < 0)
			fail("gnutls_privkey_decrypt_data\n");

		if (out2.size != hash_data.size)
			fail("Decrypted data don't match original (1)\n");

		if (memcmp(out2.data, hash_data.data, hash_data.size) != 0)
			fail("Decrypted data don't match original (2)\n");

		gnutls_free(out.data);
		gnutls_free(out2.data);

		ret =
		    gnutls_pubkey_encrypt_data(pubkey, 0, &raw_data, &out);
		if (ret < 0)
			fail("gnutls_pubkey_encrypt_data\n");

		ret = gnutls_privkey_decrypt_data(privkey, 0, &out, &out2);
		if (ret < 0)
			fail("gnutls_privkey_decrypt_data\n");

		if (out2.size != raw_data.size)
			fail("Decrypted data don't match original (3)\n");

		if (memcmp(out2.data, raw_data.data, raw_data.size) != 0)
			fail("Decrypted data don't match original (4)\n");

		if (debug)
			success("ok\n");

		gnutls_free(out.data);
		gnutls_free(out2.data);
		gnutls_x509_privkey_deinit(key);
		gnutls_x509_crt_deinit(crt);
		gnutls_privkey_deinit(privkey);
		gnutls_pubkey_deinit(pubkey);
	}

	gnutls_global_deinit();
}
Ejemplo n.º 12
0
int main(int argc, char*argv[])
{
    int choice = atoi(argv[1]);

    
    printf("Choice: %d\n", choice);
    
    if(choice == 1){
        //1.  Normal SLInserts (@ beginning, middle, end of list)
        //a. integers
        SortedListPtr s = SLCreate(compareInts);
        int iarr[6] = {7,5,155,42,-1,6};
        if(populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,NULL,NULL) == 0){
            failure();
            return 1;
        }
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,INT); //prints 155 42 7 6 5 -1
        
        
    }else if(choice == 2){
        //b. doubles
        SortedListPtr s = SLCreate(compareDoubles);
        
        double darr[6] = {7.43,5.55,155.26,42.1,-1.5,6.7};
        if(populate_list(s,DOUBLE,sizeof(darr)/sizeof(double),NULL,darr,NULL) == 0){
            failure();
            return 1;
        }

        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,DOUBLE); //prints 155.26 42.1 7.43 6.7 5.55 -1.5
        
        
    }else if(choice == 3){
        //c. strings
        SortedListPtr s = SLCreate(compareStrings);
        
        char *carr[6] = {"cat","dog","catamaran","apple","cormorant","zebra"};
        if(populate_list(s,STRING,6,0,0,carr) == 0){
            failure();
            return 1;
        }

        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all(s,iter,STRING); //prints apple cat catamaran cormorant dog zebra
        
        
        
    }else if(choice == 4){
        //SLInsert on null list;
        int x = 5;
        if(SLInsert(NULL, &x) == 0){
            success();
        }else{
            failure();
        }
    }else if(choice == 5){
        //SLInsert null object
        SortedListPtr s = SLCreate(compareDoubles);

        if (SLInsert(s,NULL) == 0){
            success();
        }else{
            failure();
        }
    
    }else if(choice == 6){
        //SLRemove nonexistent element
        SortedListPtr s = SLCreate(compareInts);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);

        int toremove = 54;
        if (SLRemove(s,&toremove) != 0) {
            failure();
        }else{
            success();
        }
    }else if(choice == 7){
        //SLRemove existing element (no duplicates; didn't handle them anyway)
        SortedListPtr s = SLCreate(compareInts);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);


        int toremove = 5;
        
        if (SLRemove(s,&toremove) != 0) {
            SortedListIteratorPtr iter = SLCreateIterator(s);
            iterprint_all_int(s,iter); //prints 155 42 7 6 -1
        }else{
            failure();
        }
        
    }else if(choice == 8){
        //Iterate on empty list
        SortedListPtr s = SLCreate(compareInts);
        SortedListIteratorPtr iter = SLCreateIterator(s);
        iterprint_all_int(s,iter);
        //TODO: Separate into a) create iterator b) print empty list
    }else if(choice == 9){
        //Create new iterator on list, destroy old one mid-iteration
        SortedListPtr s = SLCreate(compareInts);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        
        
        SortedListIteratorPtr olditer = SLCreateIterator(s);
        void *olditem = SLNextItem(olditer);
        olditem = SLNextItem(olditer);
        SortedListIteratorPtr iter = SLCreateIterator(s);
        SLDestroyIterator(olditer);
        
        iterprint_all_int(s,iter); //prints 155 42 7 6 5 -1
    }else if(choice == 10){ //TODO
        //Create multiple iterators on same list, interleave iterations.
        
        SortedListPtr s = SLCreate(compareInts);
        int iarr[6] = {7,5,155,42,-1,6};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        SortedListIteratorPtr olditer = SLCreateIterator(s);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);

        
        void *item;
        
        item = SLNextItem(olditer);
        printf("%d ", *((int*)item));
        item = SLNextItem(olditer);
        printf("%d ", *((int*)item));  //prints 155 42
        
        item = SLNextItem(iter);
        printf("%d ", *((int*)item));
        item = SLNextItem(iter);
        printf("%d ", *((int*)item));
        item = SLNextItem(iter);
        printf("%d ", *((int*)item)); //prints 155 42 7
        
        
        item = SLNextItem(iter);  //prints 6
        printf("%d ", *((int*)item));
        item = SLNextItem(olditer);
        printf("%d ", *((int*)item)); //prints 7
        
        
        iterprint_all_int(s,iter); //prints 5 -1
        
        iterprint_all_int(s,olditer); //prints 6 5 -1
        
    }else if(choice == 11){
        //SLRemove end element, iterator positioned on it
        
        SortedListPtr s = SLCreate(compareInts);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);

        
        SortedListIteratorPtr iter = SLCreateIterator(s);

        int x3 = 3;
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);
        if(SLRemove(s,&x3) && SLNextItem(iter) == NULL){
            success();
        }else{
            failure();
        }
        
    }else if(choice == 12){ //TODO
        //SLRemove beginning element, iterator positioned on it
        
        SortedListPtr s = SLCreate(compareInts);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        
        int x1 = 7;
        if(SLRemove(s,&x1) && *((int*)SLNextItem(iter)) == 5 &&
           *((int*)SLNextItem(iter)) == 3 &&
           ((int*)SLNextItem(iter)) == NULL){
            success();
        }else{
            failure();
        }
    }else if(choice == 13){ //TODO
        //SLRemove element in middle, iterator positioned on it
        SortedListPtr s = SLCreate(compareInts);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        
        if (*((int*)item) != 7) {
            failure();
            return 1;
        }
        
        int x1 = 5;
        if(SLRemove(s,&x1) && *((int*)SLNextItem(iter)) == 3 &&
           ((int*)SLNextItem(iter)) == NULL){
            success();
        }else{
            failure();
        }
    }else if(choice == 14){
        //Add element after iterator
        SortedListPtr s = SLCreate(compareInts);
        int iarr[3] = {7,5,3};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);
        int x4 = 4;
        SLInsert(s,&x4); //prints 4 3
        
        iterprint_all_int(s,iter);
        
        
    }else if(choice == 15){
        //Remove element after iterator
        SortedListPtr s = SLCreate(compareInts);
        int iarr[4] = {7,5,3,4};
        populate_list(s,INT,sizeof(iarr)/sizeof(int),iarr,0,0);
        
        
        SortedListIteratorPtr iter = SLCreateIterator(s);
        void *item = SLNextItem(iter);
        item = SLNextItem(iter);
        int x4 = 4;
        if(SLRemove(s,&x4)){
            iterprint_all_int(s,iter); //prints 3
        }else{
            failure();
        }
    }else{
        printf("Bad input\n");
    }
    
    
    return 0;
    
}
Ejemplo n.º 13
0
int check_for_message(int sock) {
	static char * data=0;
	int message_length, sender;
	if(!data) data = new char[MAXMSGSIZE+1];
	MessageType type = get_message(sock, &data, message_length, &sender);
	if(type==NO_MESSAGE) return 0;
	//printf("organism recvd %i from %i\n", type, sender);
	if(type == SOUND) {
		char * msg = getStringFromData(data, message_length);
		//printf("%i) I hear sound %s length %i\n", myPort, msg, message_length);
		delete [] msg;
		if(sender!=myPort) { /*ignore sounds from myself*/
			myNet.feedInput(data, message_length, "ear");
			usleep(200);
			myNet.addClick();
			usleep(200);
			myGenome.transcribeGene("//encourage_auditory", 2, genome_file, portstr.str().c_str());
		}
	} else if(type == VISION) {
		//printf("start vision\n");
		if(message_length<=0) {
			organism_of_focus=worldPort;
			if(success(30)) {
				char data[2]={60,0};
				send_message(myPort, worldPort, TURN, 1, data);
				usleep(1600);
			}
		} else {
			memcpy(&organism_of_focus, data, sizeof(int));
			myNet.feedInput(data, message_length, "eye");
			char * dx_str = &data[sizeof(int)];
			float dx;
			memcpy(&dx, dx_str, sizeof(float));
			/*if(myPort==49153) {
				printf("%i at %g\n", organism_of_focus, dx);
			}*/
			if(dx<2.0) {
				if(std::find(children.begin(), children.end(), organism_of_focus) == children.end()) {
					stringstream destination_str;  destination_str<<organism_of_focus;
					myGenome.transcribeGene("//eat", 2, portstr.str().c_str(), destination_str.str().c_str());
				}
			}
			//printf("%i focus on %i dx %g\n", myPort, organism_of_focus, dx);
		}
		//printf("end vision\n");
	} else if(type == EAT) {
		int victim;
		memcpy(&victim, data, sizeof(int));
		if(victim==myPort) {
			/*printf("I'm being eaten\n");*/
		} else {
			myNet.reward("eat", 0.5);
		}
	} else if(type == KILL) {
		//printf("%i received kill message\n", myPort);
		exit(0);
	} else if(type == MATE) {
		if(sender == worldPort) { /*mate directive*/
			if(organism_of_focus==worldPort) { /*I can't see anybody, mate with self*/
				stringstream child_file;  child_file<<genome_file<<n_children;
				myGenome.transcribeGene("//asexual_reproduction", 4, portstr.str().c_str(), genome_file, child_file.str().c_str(), worldportstr.str().c_str()) ;
			} else { /*transmit request to potential mate*/
				printf("%i) send mate request to %i\n", myPort, organism_of_focus);
				send_message(myPort, organism_of_focus, MATE, strlen(genome_file), genome_file);
			}
		} else { /*the message came from a potential mate*/
			char * mate_genome = getStringFromData(data, message_length);
			printf("%i) received mate request from %i (%s)\n", myPort, sender, mate_genome);
			stringstream child_file;  child_file<<genome_file<<n_children;
			myGenome.transcribeGene("//sexual_reproduction", 5, portstr.str().c_str(), genome_file, mate_genome, child_file.str().c_str(), worldportstr.str().c_str()) ;
		}
	} else if(type == NEW_ORGANISM) {
		int child_id;
		memcpy(&child_id, data, sizeof(int));
		children.push_back(child_id);
		n_children++;
	} else if(type == DISPLAY) {
		myNet.printStats(1);
	} else if(type == SAVE) {
		char * filename = getStringFromData(data, message_length);
		stringstream cmd;
		cmd<<"cp "<<genome_file<<" "<<filename;
		system(cmd.str().c_str());
	}
	return 1;
}
Ejemplo n.º 14
0
static void
client (int fd, int server_init)
{
  int ret;
  char buffer[MAX_BUF + 1];
  gnutls_anon_client_credentials_t anoncred;
  /* Need to enable anonymous KX specifically. */

  global_init ();

  if (debug)
    {
      gnutls_global_set_log_function (client_log_func);
      gnutls_global_set_log_level (4711);
    }

  gnutls_anon_allocate_client_credentials (&anoncred);

  /* Initialize TLS session
   */
  gnutls_init (&session, GNUTLS_CLIENT|GNUTLS_DATAGRAM);
  gnutls_dtls_set_mtu( session, 1500);

  /* Use default priorities */
  gnutls_priority_set_direct (session, "NONE:+VERS-DTLS1.0:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-ECDH:+CURVE-ALL", NULL);

  /* put the anonymous credentials to the current session
   */
  gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) fd);
  gnutls_transport_set_push_function (session, push);

  /* Perform the TLS handshake
   */
  do 
    {
      ret = gnutls_handshake (session);
    }
  while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

  if (ret < 0)
    {
      fail ("client: Handshake failed\n");
      gnutls_perror (ret);
      exit(1);
    }
  else
    {
      if (debug)
        success ("client: Handshake was completed\n");
    }

  if (debug)
    success ("client: TLS version is: %s\n",
             gnutls_protocol_get_name (gnutls_protocol_get_version
                                       (session)));

  if (!server_init)
    {
      if (debug) success("Initiating client rehandshake\n");
      do 
        {
          ret = gnutls_handshake (session);
        }
      while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

      if (ret < 0)
        {
          fail ("2nd client gnutls_handshake: %s\n", gnutls_strerror(ret));
          terminate();
        }
    }
  else
    {
      do {
        ret = gnutls_record_recv (session, buffer, MAX_BUF);
      } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
    }

  if (ret == 0)
    {
      if (debug)
        success ("client: Peer has closed the TLS connection\n");
      goto end;
    }
  else if (ret < 0)
    {
      if (server_init && ret == GNUTLS_E_REHANDSHAKE)
        {
          if (debug) success("Initiating rehandshake due to server request\n");
          do 
            {
              ret = gnutls_handshake (session);
            }
          while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
        }

      if (ret != 0)
        {
          fail ("client: Error: %s\n", gnutls_strerror (ret));
          exit(1);
        }
    }

  do {
    ret = gnutls_record_send (session, MSG, strlen (MSG));
  } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
  gnutls_bye (session, GNUTLS_SHUT_WR);

end:

  close (fd);

  gnutls_deinit (session);

  gnutls_anon_free_client_credentials (anoncred);

  gnutls_global_deinit ();
}
Ejemplo n.º 15
0
static void client(int fd, const char *prio)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_anon_client_credentials_t anoncred;
	gnutls_certificate_credentials_t x509_cred;
	gnutls_session_t session;
	/* Need to enable anonymous KX specifically. */

	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(7);
	}

	gnutls_anon_allocate_client_credentials(&anoncred);
	gnutls_certificate_allocate_credentials(&x509_cred);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT);

	/* Use default priorities */
	gnutls_priority_set_direct(session, prio, NULL);

	/* put the anonymous credentials to the current session
	 */
	gnutls_credentials_set(session, GNUTLS_CRD_ANON, anoncred);
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("client: Handshake failed\n");
		gnutls_perror(ret);
		exit(1);
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

	if (debug)
		success("client: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));
	do {
		do {
			ret = gnutls_record_recv(session, buffer, MAX_BUF);
		} while (ret == GNUTLS_E_AGAIN
			 || ret == GNUTLS_E_INTERRUPTED);
	} while (ret > 0);

	if (ret == GNUTLS_E_PREMATURE_TERMINATION) {
		if (debug)
			success
			    ("client: Peer has closed the TLS connection\n");
		goto end;
	} else {
		fail("client: Unexpected error: %d (%s)\n", ret,
		     gnutls_strerror(ret));
		exit(1);
	}

      end:
	close(fd);

	gnutls_deinit(session);

	gnutls_anon_free_client_credentials(anoncred);
	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();
}
Ejemplo n.º 16
0
static void start(struct test_st *test)
{
	int ret;
	/* Server stuff. */
	gnutls_priority_t cache;
	gnutls_certificate_credentials_t serverx509cred;
	gnutls_session_t server;
	int sret = GNUTLS_E_AGAIN;
	/* Client stuff. */
	gnutls_certificate_credentials_t clientx509cred;
	gnutls_session_t client;
	const char *ep;
	int cret = GNUTLS_E_AGAIN;

	if (test == NULL)
		success("running gnutls_set_default_priority test\n");
	else
		success("running %s\n", test->name);

	if (test && test->def_prio)
		_gnutls_default_priority_string = test->def_prio;
	else
		_gnutls_default_priority_string = "NORMAL";

	/* General init. */
	global_init();
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(6);

	assert(gnutls_certificate_allocate_credentials(&serverx509cred)>=0);
	assert(gnutls_certificate_set_x509_key_mem(serverx509cred,
					    &server_cert, &server_key,
					    GNUTLS_X509_FMT_PEM)>=0);

	assert(gnutls_init(&server, GNUTLS_SERVER) >= 0);
	gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE,
				serverx509cred);
	if (test == NULL) {
		ret = gnutls_priority_init(&cache, NULL, NULL);
		if (ret < 0)
			fail("error: %s\n", gnutls_strerror(ret));
	} else {
		ret = gnutls_priority_init2(&cache, test->add_prio, &ep, GNUTLS_PRIORITY_INIT_DEF_APPEND);
		if (ret < 0) {
			if (test->exp_err == ret) {
				if (strchr(_gnutls_default_priority_string, '@') != 0) {
					if (ep != test->add_prio) {
						fail("error expected error on start of string[%d]: %s\n",
							test->err_pos, test->add_prio);
					}
				} else {
					if (ep-test->add_prio != test->err_pos) {
						fprintf(stderr, "diff: %d\n", (int)(ep-test->add_prio));
						fail("error expected error on different position[%d]: %s\n",
							test->err_pos, test->add_prio);
					}
				}
				goto cleanup;
			}
			fail("error: %s\n", gnutls_strerror(ret));
		}
	}
	gnutls_priority_set(server, cache);

	gnutls_transport_set_push_function(server, server_push);
	gnutls_transport_set_pull_function(server, server_pull);
	gnutls_transport_set_ptr(server, server);

	/* Init client */
	ret = gnutls_certificate_allocate_credentials(&clientx509cred);
	if (ret < 0)
		exit(1);

	ret = gnutls_certificate_set_x509_trust_mem(clientx509cred, &ca_cert, GNUTLS_X509_FMT_PEM);
	if (ret < 0)
		exit(1);

	ret = gnutls_init(&client, GNUTLS_CLIENT);
	if (ret < 0)
		exit(1);

	ret = gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,
				clientx509cred);
	if (ret < 0)
		exit(1);

	ret = gnutls_set_default_priority(client);
	if (ret < 0)
		exit(1);

	gnutls_transport_set_push_function(client, client_push);
	gnutls_transport_set_pull_function(client, client_pull);
	gnutls_transport_set_ptr(client, client);

	HANDSHAKE(client, server);

	/* check gnutls_certificate_get_ours() - client side */
	{
		const gnutls_datum_t *mcert;

		mcert = gnutls_certificate_get_ours(client);
		if (mcert != NULL) {
			fail("gnutls_certificate_get_ours(): failed\n");
			exit(1);
		}
	}

	if (test && test->exp_vers != 0) {
		if (test->exp_vers != gnutls_protocol_get_version(server)) {
			fail("expected version %s, got %s\n",
			     gnutls_protocol_get_name(test->exp_vers),
			     gnutls_protocol_get_name(gnutls_protocol_get_version(server)));
		}
	}

	/* check the number of certificates received */
	{
		unsigned cert_list_size = 0;
		gnutls_typed_vdata_st data[2];
		unsigned status;

		memset(data, 0, sizeof(data));

		data[0].type = GNUTLS_DT_DNS_HOSTNAME;
		data[0].data = (void*)"localhost1";

		data[1].type = GNUTLS_DT_KEY_PURPOSE_OID;
		data[1].data = (void*)GNUTLS_KP_TLS_WWW_SERVER;

		gnutls_certificate_get_peers(client, &cert_list_size);
		if (cert_list_size < 2) {
			fprintf(stderr, "received a certificate list of %d!\n", cert_list_size);
			exit(1);
		}

		ret = gnutls_certificate_verify_peers(client, data, 2, &status);
		if (ret < 0) {
			fprintf(stderr, "could not verify certificate: %s\n", gnutls_strerror(ret));
			exit(1);
		}

		if (status == 0) {
			fprintf(stderr, "should not have accepted!\n");
			exit(1);
		}

		data[0].type = GNUTLS_DT_DNS_HOSTNAME;
		data[0].data = (void*)"localhost";

		ret = gnutls_certificate_verify_peers(client, data, 2, &status);
		if (ret < 0) {
			fprintf(stderr, "could not verify certificate: %s\n", gnutls_strerror(ret));
			exit(1);
		}

		if (status != 0) {
			fprintf(stderr, "could not verify certificate: %.4x\n", status);
			exit(1);
		}
	}

	if (test && test->exp_etm) {
		ret = gnutls_session_ext_master_secret_status(client);
		if (ret != 1) {
			fprintf(stderr, "Extended master secret wasn't negotiated by default (client ret: %d)\n", ret);
			exit(1);
		}

		ret = gnutls_session_ext_master_secret_status(server);
		if (ret != 1) {
			fprintf(stderr, "Extended master secret wasn't negotiated by default (server ret: %d)\n", ret);
			exit(1);
		}
	}

	gnutls_bye(client, GNUTLS_SHUT_RDWR);
	gnutls_bye(server, GNUTLS_SHUT_RDWR);

	gnutls_deinit(client);
	gnutls_certificate_free_credentials(clientx509cred);
 cleanup:
	gnutls_priority_deinit(cache);
	gnutls_deinit(server);

	gnutls_certificate_free_credentials(serverx509cred);

	gnutls_global_deinit();
	reset_buffers();
}
Ejemplo n.º 17
0
static void client(int fd)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_certificate_credentials_t clientx509cred;
	gnutls_anon_client_credentials_t anoncred;
	gnutls_session_t session;

	global_init();

	if (debug) {
		gnutls_global_set_log_function(client_log_func);
		gnutls_global_set_log_level(4711);
	}

	assert(gnutls_anon_allocate_client_credentials(&anoncred) >= 0);
	assert(gnutls_certificate_allocate_credentials(&clientx509cred) >= 0);

	/* Initialize TLS session
	 */
	gnutls_init(&session, GNUTLS_CLIENT | GNUTLS_DATAGRAM);
	gnutls_dtls_set_mtu(session, MTU);

	assert(gnutls_priority_set_direct(session,
					  "NONE:+VERS-DTLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-ECDH:+CURVE-ALL",
					  NULL) >= 0);

	gnutls_credentials_set(session, GNUTLS_CRD_ANON, anoncred);
	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, clientx509cred);

	gnutls_transport_set_int(session, fd);
	gnutls_transport_set_push_function(session, push);
	gnutls_dtls_set_timeouts(session, 2000, 30 * 1000);

	/* Perform the TLS handshake
	 */
	do {
		ret = gnutls_handshake(session);
	}
	while (ret < 0 && gnutls_error_is_fatal(ret) == 0);

	if (ret < 0) {
		fail("client: Handshake failed\n");
		gnutls_perror(ret);
		exit(1);
	} else {
		if (debug)
			success("client: Handshake was completed\n");
	}

	if (debug)
		success("client: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));

	/* update priorities to allow cert auth */
	assert(gnutls_priority_set_direct(session,
					  "NONE:+VERS-DTLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ECDHE-RSA:+CURVE-ALL",
					  NULL) >= 0);

	do {
		ret = gnutls_record_recv(session, buffer, MAX_BUF);
	} while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);

	if (ret == 0) {
		if (debug)
			success("client: Peer has closed the TLS connection\n");
		goto end;
	} else if (ret < 0) {
		if (ret == GNUTLS_E_REHANDSHAKE) {
			if (debug)
				success
				    ("Initiating rehandshake due to server request\n");
			do {
				ret = gnutls_handshake(session);
			}
			while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
		}

		if (ret != 0) {
			fail("client: Error: %s\n", gnutls_strerror(ret));
			exit(1);
		}
	}

	do {
		ret = gnutls_record_send(session, MSG, strlen(MSG));
	} while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED);
	gnutls_bye(session, GNUTLS_SHUT_WR);

 end:

	close(fd);

	gnutls_deinit(session);

	gnutls_certificate_free_credentials(clientx509cred);
	gnutls_anon_free_client_credentials(anoncred);

	gnutls_global_deinit();
}
Ejemplo n.º 18
0
void
doit (void)
{
    gnutls_x509_privkey_t key;
    gnutls_x509_crt_t crt;
    gnutls_pubkey_t pubkey;
    gnutls_privkey_t privkey;
    gnutls_digest_algorithm_t hash_algo;
    gnutls_datum_t signature;
    gnutls_datum_t signature2;
    int ret;
    size_t i;

    gnutls_global_init ();

    for (i = 0; i < sizeof (key_dat) / sizeof (key_dat[0]); i++)
    {
        if (debug)
            success ("loop %d\n", (int) i);

        ret = gnutls_x509_privkey_init (&key);
        if (ret < 0)
            fail ("gnutls_x509_privkey_init\n");

        ret =
            gnutls_x509_privkey_import (key, &key_dat[i], GNUTLS_X509_FMT_PEM);
        if (ret < 0)
            fail ("gnutls_x509_privkey_import\n");

        ret = gnutls_pubkey_init (&pubkey);
        if (ret < 0)
            fail ("gnutls_privkey_init\n");

        ret = gnutls_privkey_init (&privkey);
        if (ret < 0)
            fail ("gnutls_pubkey_init\n");

        ret = gnutls_privkey_import_x509 (privkey, key, 0);
        if (ret < 0)
            fail ("gnutls_privkey_import_x509\n");

        ret = gnutls_privkey_sign_hash (privkey, GNUTLS_DIG_SHA1, 0,
                                        &hash_data, &signature2);
        if (ret < 0)
            fail ("gnutls_privkey_sign_hash\n");

        ret = gnutls_privkey_sign_data (privkey, GNUTLS_DIG_SHA1, 0,
                                        &raw_data, &signature);
        if (ret < 0)
            fail ("gnutls_x509_privkey_sign_hash\n");

        ret = gnutls_x509_crt_init (&crt);
        if (ret < 0)
            fail ("gnutls_x509_crt_init\n");

        ret = gnutls_x509_crt_import (crt, &cert_dat[i], GNUTLS_X509_FMT_PEM);
        if (ret < 0)
            fail ("gnutls_x509_crt_import\n");

        ret =
            gnutls_pubkey_import_x509 (pubkey, crt, 0);
        if (ret < 0)
            fail ("gnutls_x509_pubkey_import\n");

        ret =
            gnutls_pubkey_get_verify_algorithm (pubkey, &signature, &hash_algo);
        if (ret < 0 || hash_algo != GNUTLS_DIG_SHA1)
            fail ("gnutls_x509_crt_get_verify_algorithm\n");

        ret = gnutls_pubkey_verify_hash (pubkey, 0, &hash_data, &signature);
        if (ret < 0)
            fail ("gnutls_x509_privkey_verify_hash\n");

        ret =
            gnutls_pubkey_get_verify_algorithm (pubkey, &signature2, &hash_algo);
        if (ret < 0 || hash_algo != GNUTLS_DIG_SHA1)
            fail ("gnutls_x509_crt_get_verify_algorithm (hashed data)\n");

        ret = gnutls_pubkey_verify_hash (pubkey, 0, &hash_data, &signature2);
        if (ret < 0)
            fail ("gnutls_x509_privkey_verify_hash (hashed data)\n");

        /* should fail */
        ret = gnutls_pubkey_verify_hash (pubkey, 0, &invalid_hash_data, &signature2);
        if (ret != GNUTLS_E_PK_SIG_VERIFY_FAILED)
            fail ("gnutls_x509_privkey_verify_hash (hashed data)\n");


        gnutls_free(signature.data);
        gnutls_free(signature2.data);
        gnutls_x509_privkey_deinit (key);
        gnutls_x509_crt_deinit (crt);
        gnutls_privkey_deinit (privkey);
        gnutls_pubkey_deinit (pubkey);
    }

    gnutls_global_deinit ();
}
Ejemplo n.º 19
0
void
doit (void)
{
  gnutls_certificate_credentials_t x509cred;
  const char *file, *password;
  int ret;

  ret = gnutls_global_init ();
  if (ret < 0)
    fail ("gnutls_global_init failed %d\n", ret);

  ret = gnutls_certificate_allocate_credentials (&x509cred);
  if (ret < 0)
    fail ("gnutls_certificate_allocate_credentials failed %d\n", ret);

  file = getenv ("PKCS12FILE");
  password = getenv ("PKCS12PASSWORD");

  if (!file)
    file = "pkcs12-decode/client.p12";
  if (!password)
    password = "foobar";

  success ("Reading PKCS#12 blob from `%s' using password `%s'.\n",
	   file, password);
  ret = gnutls_certificate_set_x509_simple_pkcs12_file (x509cred,
							file,
							GNUTLS_X509_FMT_DER,
							password);
  if (ret < 0)
    fail ("x509_pkcs12 failed %d: %s\n", ret, gnutls_strerror (ret));

  success ("Read file OK\n");

  gnutls_certificate_free_credentials (x509cred);

  /* try now if we can read correctly from a pkcs12 file that
   * contains two certificates (one unrelated with key)
   */
  ret = gnutls_certificate_allocate_credentials (&x509cred);
  if (ret < 0)
    fail ("gnutls_certificate_allocate_credentials failed %d\n", ret);

  file = getenv ("PKCS12FILE_2");
  password = getenv ("PKCS12PASSWORD_2");

  if (!file)
    file = "pkcs12-decode/pkcs12_2certs.p12";
  if (!password)
    password = "";

  success ("Reading PKCS#12 blob from `%s' using password `%s'.\n",
	   file, password);
  ret = gnutls_certificate_set_x509_simple_pkcs12_file (x509cred,
							file,
							GNUTLS_X509_FMT_DER,
							password);
  if (ret < 0)
    fail ("x509_pkcs12 failed %d: %s\n", ret, gnutls_strerror (ret));

  success ("Read file OK\n");

  gnutls_certificate_free_credentials (x509cred);

  gnutls_global_deinit ();
}
Ejemplo n.º 20
0
static void dtls_mtu_try(const char *name, const char *client_prio,
		unsigned link_mtu, unsigned tunnel_mtu)
{
	int ret;
	/* Server stuff. */
	gnutls_certificate_credentials_t serverx509cred;
	gnutls_session_t server;
	int sret = GNUTLS_E_AGAIN;
	/* Client stuff. */
	gnutls_certificate_credentials_t clientx509cred;
	gnutls_session_t client;
	int cret = GNUTLS_E_AGAIN;
	unsigned dmtu;
	unsigned i;

	/* General init. */
	gnutls_global_set_log_function(tls_log_func);
	if (debug)
		gnutls_global_set_log_level(6);

	reset_buffers();
	/* Init server */
	assert(gnutls_certificate_allocate_credentials(&serverx509cred)>=0);

	assert(gnutls_certificate_set_x509_key_mem(serverx509cred,
					    &server_cert, &server_key,
					    GNUTLS_X509_FMT_PEM) >= 0);

	assert(gnutls_init(&server, GNUTLS_SERVER|GNUTLS_DATAGRAM|GNUTLS_NONBLOCK) >= 0);
	gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE,
				serverx509cred);

	assert(gnutls_priority_set_direct(server,
				   "NORMAL:+ANON-ECDH:+ANON-DH:+ECDHE-RSA:+DHE-RSA:+RSA:+ECDHE-ECDSA:+CURVE-X25519",
				   NULL) >= 0);
	gnutls_transport_set_push_function(server, server_push);
	gnutls_transport_set_pull_function(server, server_pull);
	gnutls_transport_set_pull_timeout_function(server, server_pull_timeout_func);
	gnutls_transport_set_ptr(server, server);

	/* Init client */

	ret = gnutls_init(&client, GNUTLS_CLIENT|GNUTLS_DATAGRAM|GNUTLS_NONBLOCK);
	if (ret < 0)
		exit(1);

	assert(gnutls_certificate_allocate_credentials(&clientx509cred) >= 0);
	assert(gnutls_certificate_set_x509_trust_mem(clientx509cred, &ca_cert, GNUTLS_X509_FMT_PEM)>=0);

	assert(gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE,
				clientx509cred) >= 0);

	gnutls_transport_set_push_function(client, client_push);
	gnutls_transport_set_pull_function(client, client_pull);
	gnutls_transport_set_pull_timeout_function(client, client_pull_timeout_func);
	
	gnutls_transport_set_ptr(client, client);

	ret = gnutls_priority_set_direct(client, client_prio, NULL);
	if (ret < 0) {
		fail("%s: error in priority setting\n", name);
		exit(1);
	}
	success("negotiating %s\n", name);
	HANDSHAKE_DTLS(client, server);

	gnutls_dtls_set_mtu(client, link_mtu);
	dmtu = gnutls_dtls_get_data_mtu(client);
	if (dmtu != tunnel_mtu) {
		fail("%s: Calculated MTU (%d) does not match expected (%d)\n", name, dmtu, tunnel_mtu);
	}

	{
		char msg[dmtu+1];
		memset(msg, 1, sizeof(msg));
		ret = gnutls_record_send(client, msg, dmtu+1);
		if (ret != (int)GNUTLS_E_LARGE_PACKET) {
			myfail("could send larger packet than MTU (%d), ret: %d\n", dmtu, ret);
		}

		ret = gnutls_record_send(client, msg, dmtu);
		if (ret != (int)dmtu) {
			myfail("could not send %d bytes (sent %d)\n", dmtu, ret);
		}

		memset(msg, 2, dmtu);
		ret = gnutls_record_recv(server, msg, dmtu);
		if (ret != (int)dmtu) {
			myfail("could not receive %d bytes (received %d)\n", dmtu, ret);
		}

		for (i=0;i<dmtu;i++)
			assert(msg[i]==1);
	}

	gnutls_bye(client, GNUTLS_SHUT_RDWR);
	gnutls_bye(server, GNUTLS_SHUT_RDWR);

	gnutls_deinit(client);
	gnutls_deinit(server);

	gnutls_certificate_free_credentials(serverx509cred);
	gnutls_certificate_free_credentials(clientx509cred);
}
Ejemplo n.º 21
0
static void server(int fd)
{
	int ret;
	char buffer[MAX_BUF + 1];
	gnutls_session_t session;
	gnutls_certificate_credentials_t x509_cred;

	/* this must be called once in the program
	 */
	global_init();
	memset(buffer, 0, sizeof(buffer));

	if (debug) {
		gnutls_global_set_log_function(server_log_func);
		gnutls_global_set_log_level(4711);
	}

	gnutls_certificate_allocate_credentials(&x509_cred);
	gnutls_certificate_set_x509_key_mem(x509_cred, &server_cert,
					    &server_key,
					    GNUTLS_X509_FMT_PEM);

	gnutls_init(&session, GNUTLS_SERVER);

	/* avoid calling all the priority functions, since the defaults
	 * are adequate.
	 */
	gnutls_priority_set_direct(session, "NORMAL", NULL);

	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);

	gnutls_transport_set_int(session, fd);

	do {
		ret = gnutls_handshake(session);
	} while (ret < 0 && gnutls_error_is_fatal(ret) == 0);
	if (ret < 0) {
		/* failure is expected here */
		goto end;
	}

	if (debug) {
		success("server: Handshake was completed\n");
	}

	if (debug)
		success("server: TLS version is: %s\n",
			gnutls_protocol_get_name
			(gnutls_protocol_get_version(session)));

	/* do not wait for the peer to close the connection.
	 */
	gnutls_bye(session, GNUTLS_SHUT_WR);

 end:
	close(fd);
	gnutls_deinit(session);

	gnutls_certificate_free_credentials(x509_cred);

	gnutls_global_deinit();

	if (debug)
		success("server: finished\n");
}
Ejemplo n.º 22
0
static int
cert_callback (gnutls_session_t session,
	       const gnutls_datum_t * req_ca_rdn, int nreqs,
	       const gnutls_pk_algorithm_t * sign_algos,
	       int sign_algos_length, gnutls_retr_st * st)
{
  int result;
  gnutls_x509_dn_t dn;

  if (nreqs != 1)
    {
      fail ("client: invoked to provide client cert, %d CA .\n", nreqs);
      return -1;
    }

  if (debug)
    success ("client: invoked to provide client cert.\n");

  result = gnutls_x509_dn_init (&dn);
  if (result < 0)
    {
      fail ("client: could not initialize DN.\n");
      return -1;
    }

  result = gnutls_x509_dn_import (dn, req_ca_rdn);
  if (result == 0)
    {
      gnutls_x509_ava_st val;

      if (debug)
	success ("client: imported DN.\n");

      if (gnutls_x509_dn_get_rdn_ava (dn, 0, 0, &val) == 0)
	{
	  if (debug)
	    success ("client: got RDN 0.\n");

	  if (val.value.size == strlen (EXPECT_RDN0)
	      && strncmp (val.value.data, EXPECT_RDN0, val.value.size) == 0)
	    {
	      if (debug)
		success ("client: RND 0 correct.\n");
	    }
	  else
	    {
	      fail ("client: RND 0 bad: %.*s\n",
		    val.value.size, val.value.data);
	      return -1;
	    }
	}
      else
	{
	  fail ("client: could not retrieve RDN 0.\n");
	  return -1;
	}

      gnutls_x509_dn_deinit (dn);
    }
  else
    {
      fail ("client: failed to parse RDN: %s\n", gnutls_strerror (result));
    }

  return 0;
}
Ejemplo n.º 23
0
static int do_test_open(int exist, int flags, const char *flags_str, int mode)
{
    char buf[4096];
    const char *data = testdata;
    int datalen = testdatalen;
    unsigned currlen = 0;
    int err = 0;
    int res;
    int fd;
    off_t off;

    start_test("open(%s, %s, 0%03o)", exist ? "+" : "-", flags_str, mode);
    unlink(testfile);
    if (exist) {
        res = create_file(testfile_r, testdata2, testdata2len);
        if (res == -1)
            return -1;

        currlen = testdata2len;
    }

    fd = open(testfile, flags, mode);
    if ((flags & O_CREAT) && (flags & O_EXCL) && exist) {
        if (fd != -1) {
            ERROR("open should have failed");
            close(fd);
            return -1;
        } else if (errno == EEXIST)
            goto succ;
    }
    if (!(flags & O_CREAT) && !exist) {
        if (fd != -1) {
            ERROR("open should have failed");
            close(fd);
            return -1;
        } else if (errno == ENOENT)
            goto succ;
    }
    if (fd == -1) {
        PERROR("open");
        return -1;
    }

    if (flags & O_TRUNC)
        currlen = 0;

    err += check_type(testfile, S_IFREG);
    if (exist)
        err += check_mode(testfile, 0644);
    else
        err += check_mode(testfile, mode);
    err += check_nlink(testfile, 1);
    err += check_size(testfile, currlen);
    if (exist && !(flags & O_TRUNC) && (mode & 0400))
        err += check_data(testfile, testdata2, 0, testdata2len);

    res = write(fd, data, datalen);
    if ((flags & O_ACCMODE) != O_RDONLY) {
        if (res == -1) {
            PERROR("write");
            err --;
        } else if (res != datalen) {
            ERROR("write is short: %u instead of %u", res, datalen);
            err --;
        } else {
            if (datalen > (int) currlen)
                currlen = datalen;

            err += check_size(testfile, currlen);

            if (mode & 0400) {
                err += check_data(testfile, data, 0, datalen);
                if (exist && !(flags & O_TRUNC) &&
                        testdata2len > datalen)
                    err += check_data(testfile,
                                      testdata2 + datalen,
                                      datalen,
                                      testdata2len - datalen);
            }
        }
    } else {
        if (res != -1) {
            ERROR("write should have failed");
            err --;
        } else if (errno != EBADF) {
            PERROR("write");
            err --;
        }
    }
    off = lseek(fd, SEEK_SET, 0);
    if (off == (off_t) -1) {
        PERROR("lseek");
        err--;
    } else if (off != 0) {
        ERROR("offset should have returned 0");
        err --;
    }
    res = read(fd, buf, sizeof(buf));
    if ((flags & O_ACCMODE) != O_WRONLY) {
        if (res == -1) {
            PERROR("read");
            err--;
        } else {
            int readsize =
                currlen < sizeof(buf) ? currlen : sizeof(buf);
            if (res != readsize) {
                ERROR("read is short: %i instead of %u",
                      res, readsize);
                err--;
            } else {
                if ((flags & O_ACCMODE) != O_RDONLY) {
                    err += check_buffer(buf, data, datalen);
                    if (exist && !(flags & O_TRUNC) &&
                            testdata2len > datalen)
                        err += check_buffer(buf + datalen,
                                            testdata2 + datalen,
                                            testdata2len - datalen);
                } else if (exist)
                    err += check_buffer(buf, testdata2,
                                        testdata2len);
            }
        }
    } else {
        if (res != -1) {
            ERROR("read should have failed");
            err --;
        } else if (errno != EBADF) {
            PERROR("read");
            err --;
        }
    }

    res = close(fd);
    if (res == -1) {
        PERROR("close");
        return -1;
    }
    res = unlink(testfile);
    if (res == -1) {
        PERROR("unlink");
        return -1;
    }
    res = check_nonexist(testfile);
    if (res == -1)
        return -1;
    res = check_nonexist(testfile_r);
    if (res == -1)
        return -1;
    if (err)
        return -1;

succ:
    success();
    return 0;
}
Ejemplo n.º 24
0
static void
client (void)
{
  int ret, sd, ii;
  gnutls_session_t session;
  char buffer[MAX_BUF + 1];
  gnutls_certificate_credentials_t xcred;

  gnutls_global_init ();

  gnutls_global_set_log_function (tls_log_func);
  if (debug)
    gnutls_global_set_log_level (4711);

  gnutls_certificate_allocate_credentials (&xcred);

  /* sets the trusted cas file
   */
  gnutls_certificate_set_x509_trust_mem (xcred, &ca, GNUTLS_X509_FMT_PEM);

  gnutls_certificate_client_set_retrieve_function (xcred, cert_callback);

  /* Initialize TLS session
   */
  gnutls_init (&session, GNUTLS_CLIENT);

  /* Use default priorities */
  gnutls_set_default_priority (session);

  /* put the x509 credentials to the current session
   */
  gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);

  /* connect to the peer
   */
  sd = tcp_connect ();

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);

  /* Perform the TLS handshake
   */
  ret = gnutls_handshake (session);

  if (ret < 0)
    {
      fail ("client: Handshake failed\n");
      gnutls_perror (ret);
      goto end;
    }
  else
    {
      if (debug)
	success ("client: Handshake was completed\n");
    }

  if (debug)
    success ("client: TLS version is: %s\n",
	     gnutls_protocol_get_name (gnutls_protocol_get_version
				       (session)));

  /* see the Getting peer's information example */
  if (debug)
    print_info (session);

  gnutls_record_send (session, MSG, strlen (MSG));

  ret = gnutls_record_recv (session, buffer, MAX_BUF);
  if (ret == 0)
    {
      if (debug)
	success ("client: Peer has closed the TLS connection\n");
      goto end;
    }
  else if (ret < 0)
    {
      fail ("client: Error: %s\n", gnutls_strerror (ret));
      goto end;
    }

  if (debug)
    {
      printf ("- Received %d bytes: ", ret);
      for (ii = 0; ii < ret; ii++)
	{
	  fputc (buffer[ii], stdout);
	}
      fputs ("\n", stdout);
    }

  gnutls_bye (session, GNUTLS_SHUT_RDWR);

end:

  tcp_close (sd);

  gnutls_deinit (session);

  gnutls_certificate_free_credentials (xcred);

  gnutls_global_deinit ();
}
Ejemplo n.º 25
0
void
doit (void)
{
  /* Server stuff. */
  gnutls_anon_server_credentials_t s_anoncred;
  const gnutls_datum_t p3 = { (char*) pkcs3, strlen (pkcs3) };
  static gnutls_dh_params_t dh_params;
  gnutls_session_t server;
  int sret = GNUTLS_E_AGAIN;
  /* Client stuff. */
  gnutls_anon_client_credentials_t c_anoncred;
  gnutls_session_t client;
  int n, cret = GNUTLS_E_AGAIN;
  /* Need to enable anonymous KX specifically. */
  const int kx_prio[] = { GNUTLS_KX_ANON_DH, 0 };
  char buffer[MAX_BUF + 1];
  ssize_t ns;
  int ret;

  /* General init. */
  gnutls_global_init ();
  gnutls_global_set_log_function (tls_log_func);
  if (debug)
    gnutls_global_set_log_level (4711);

  /* Init server */
  gnutls_anon_allocate_server_credentials (&s_anoncred);
  gnutls_dh_params_init (&dh_params);
  gnutls_dh_params_import_pkcs3 (dh_params, &p3, GNUTLS_X509_FMT_PEM);
  gnutls_anon_set_server_dh_params (s_anoncred, dh_params);
  gnutls_init (&server, GNUTLS_SERVER);
  gnutls_set_default_priority (server);
  gnutls_kx_set_priority (server, kx_prio);
  gnutls_credentials_set (server, GNUTLS_CRD_ANON, s_anoncred);
  gnutls_dh_set_prime_bits (server, 1024);
  gnutls_transport_set_push_function (server, server_push);
  gnutls_transport_set_pull_function (server, server_pull);

  /* Init client */
  gnutls_anon_allocate_client_credentials (&c_anoncred);
  gnutls_init (&client, GNUTLS_CLIENT);
  gnutls_set_default_priority (client);
  gnutls_kx_set_priority (client, kx_prio);
  gnutls_credentials_set (client, GNUTLS_CRD_ANON, c_anoncred);
  gnutls_transport_set_push_function (client, client_push);
  gnutls_transport_set_pull_function (client, client_pull);

  do
    {
      if (cret == GNUTLS_E_AGAIN)
	{
	  success ("loop invoking client:\n");
	  cret = gnutls_handshake (client);
	  success ("client %d: %s\n", cret, gnutls_strerror (cret));
	}

      if (sret == GNUTLS_E_AGAIN)
	{
	  success ("loop invoking server:\n");
	  sret = gnutls_handshake (server);
	  success ("server %d: %s\n", sret, gnutls_strerror (sret));
	}
    }
  while (cret == GNUTLS_E_AGAIN || sret == GNUTLS_E_AGAIN);

  success ("Handshake established\n");

  ns = gnutls_record_send (client, MSG, strlen (MSG));
  success ("client: sent %d\n", ns);

  ret = gnutls_record_recv (server, buffer, MAX_BUF);
  if (ret == 0)
    fail ("server: didn't receive any data\n");
  else if (ret < 0)
    fail ("server: error: %s\n", gnutls_strerror (ret));
  else
    {
      printf ("server: received %d: ", ret);
      for (n = 0; n < ret; n++)
	fputc (buffer[n], stdout);
      fputs ("\n", stdout);
    }

  ns = gnutls_record_send (server, MSG, strlen (MSG));
  success ("server: sent %d\n", ns);

  ret = gnutls_record_recv (client, buffer, MAX_BUF);
  if (ret == 0)
    {
      fail ("client: Peer has closed the TLS connection\n");
    }
  else if (ret < 0)
    {
      fail ("client: Error: %s\n", gnutls_strerror (ret));
    }
  else
    {
      printf ("client: received %d: ", ret);
      for (n = 0; n < ret; n++)
	fputc (buffer[n], stdout);
      fputs ("\n", stdout);
    }

  gnutls_bye (client, GNUTLS_SHUT_RDWR);
  gnutls_bye (server, GNUTLS_SHUT_RDWR);

  gnutls_deinit (client);
  gnutls_deinit (server);

  free (to_server);
  free (to_client);

  gnutls_anon_free_client_credentials (c_anoncred);
  gnutls_anon_free_server_credentials (s_anoncred);

  gnutls_dh_params_deinit (dh_params);

  gnutls_global_deinit ();
}
Ejemplo n.º 26
0
static void
server (void)
{
  /* this must be called once in the program
   */
  gnutls_global_init ();

  gnutls_global_set_log_function (tls_log_func);
  if (debug)
    gnutls_global_set_log_level (4711);

  gnutls_certificate_allocate_credentials (&x509_cred);
  gnutls_certificate_set_x509_trust_mem (x509_cred, &ca, GNUTLS_X509_FMT_PEM);

  gnutls_certificate_set_x509_key_mem (x509_cred, &server_cert, &server_key,
				       GNUTLS_X509_FMT_PEM);

  if (debug)
    success ("Launched, generating DH parameters...\n");

  generate_dh_params ();

  gnutls_certificate_set_dh_params (x509_cred, dh_params);

  client_len = sizeof (sa_cli);

  session = initialize_tls_session ();

  sd = accept (listen_sd, (SA *) & sa_cli, &client_len);

  if (debug)
    success ("server: connection from %s, port %d\n",
	     inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf,
			sizeof (topbuf)), ntohs (sa_cli.sin_port));

  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
  ret = gnutls_handshake (session);
  if (ret < 0)
    {
      close (sd);
      gnutls_deinit (session);
      fail ("server: Handshake has failed (%s)\n\n", gnutls_strerror (ret));
      return;
    }
  if (debug)
    success ("server: Handshake was completed\n");

  if (debug)
    success ("server: TLS version is: %s\n",
	     gnutls_protocol_get_name (gnutls_protocol_get_version
				       (session)));

  /* see the Getting peer's information example */
  if (debug)
    print_info (session);

  i = 0;
  for (;;)
    {
      memset (buffer, 0, MAX_BUF + 1);
      ret = gnutls_record_recv (session, buffer, MAX_BUF);

      if (ret == 0)
	{
	  if (debug)
	    success ("server: Peer has closed the GnuTLS connection\n");
	  break;
	}
      else if (ret < 0)
	{
	  fail ("server: Received corrupted data(%d). Closing...\n", ret);
	  break;
	}
      else if (ret > 0)
	{
	  /* echo data back to the client
	   */
	  gnutls_record_send (session, buffer, strlen (buffer));
	}
    }
  /* do not wait for the peer to close the connection.
   */
  gnutls_bye (session, GNUTLS_SHUT_WR);

  close (sd);
  gnutls_deinit (session);

  close (listen_sd);

  gnutls_certificate_free_credentials (x509_cred);

  gnutls_dh_params_deinit (dh_params);

  gnutls_global_deinit ();

  if (debug)
    success ("server: finished\n");
}
Ejemplo n.º 27
0
void
doit (void)
{
  gnutls_x509_privkey_t pkey;
  gnutls_privkey_t abs_pkey;
  gnutls_x509_crq_t crq;

  size_t pkey_key_id_len;
  unsigned char *pkey_key_id = NULL;

  size_t crq_key_id_len;
  unsigned char *crq_key_id = NULL;

  gnutls_pk_algorithm_t algorithm;

  int ret;

  ret = gnutls_global_init ();
  if (ret < 0)
    fail ("gnutls_global_init: %d\n", ret);

  gnutls_global_set_log_function (tls_log_func);
  if (debug)
    gnutls_global_set_log_level (4711);

  for (algorithm = GNUTLS_PK_RSA; algorithm <= GNUTLS_PK_DSA; algorithm++)
    {
      ret = gnutls_x509_crq_init (&crq);
      if (ret < 0)
        fail ("gnutls_x509_crq_init: %d\n", ret);

      ret = gnutls_x509_privkey_init (&pkey);
      if (ret < 0)
        {
          fail ("gnutls_x509_privkey_init: %d\n", ret);
        }

      ret = gnutls_privkey_init (&abs_pkey);
      if (ret < 0)
        {
          fail ("gnutls_privkey_init: %d\n", ret);
        }

      ret = gnutls_x509_privkey_generate (pkey, algorithm, 1024, 0);
      if (ret < 0)
        {
          fail ("gnutls_x509_privkey_generate (rsa): %d\n", ret);
        }
      else if (debug)
        {
          success ("Key[%s] generation ok: %d\n",
                   gnutls_pk_algorithm_get_name (algorithm), ret);
        }

      pkey_key_id_len = 0;
      ret = gnutls_x509_privkey_get_key_id (pkey, 0, pkey_key_id,
                                            &pkey_key_id_len);
      if (ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
        {
          fail ("gnutls_x509_privkey_get_key_id incorrectly returns %d\n",
                ret);
        }

      pkey_key_id = malloc (sizeof (unsigned char) * pkey_key_id_len);
      ret = gnutls_x509_privkey_get_key_id (pkey, 0, pkey_key_id,
                                            &pkey_key_id_len);
      if (ret != GNUTLS_E_SUCCESS)
        {
          fail ("gnutls_x509_privkey_get_key_id incorrectly returns %d\n",
                ret);
        }

      ret = gnutls_x509_crq_set_version (crq, 1);
      if (ret < 0)
        {
          fail ("gnutls_x509_crq_set_version: %d\n", ret);
        }

      ret = gnutls_x509_crq_set_key (crq, pkey);
      if (ret < 0)
        {
          fail ("gnutls_x509_crq_set_key: %d\n", ret);
        }

      ret = gnutls_x509_crq_set_dn_by_oid (crq, GNUTLS_OID_X520_COMMON_NAME,
                                           0, "CN-Test", 7);
      if (ret < 0)
        {
          fail ("gnutls_x509_crq_set_dn_by_oid: %d\n", ret);
        }

      ret = gnutls_privkey_import_x509( abs_pkey, pkey, 0);
      if (ret < 0)
        {
          fail ("gnutls_privkey_import_x509: %d\n", ret);
        }

      ret = gnutls_x509_crq_privkey_sign (crq, abs_pkey, GNUTLS_DIG_SHA1, 0);
      if (ret < 0)
        {
          fail ("gnutls_x509_crq_sign: %d\n", ret);
        }

      ret = gnutls_x509_crq_verify (crq, 0);
      if (ret < 0)
        {
          fail ("gnutls_x509_crq_verify: %d\n", ret);
        }

      crq_key_id_len = 0;
      ret = gnutls_x509_crq_get_key_id (crq, 0, crq_key_id, &crq_key_id_len);
      if (ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
        {
          fail ("gnutls_x509_crq_get_key_id incorrectly returns %d\n", ret);
        }

      crq_key_id = malloc (sizeof (unsigned char) * crq_key_id_len);
      ret = gnutls_x509_crq_get_key_id (crq, 0, crq_key_id, &crq_key_id_len);
      if (ret != GNUTLS_E_SUCCESS)
        {
          fail ("gnutls_x509_crq_get_key_id incorrectly returns %d\n", ret);
        }

      if (crq_key_id_len == pkey_key_id_len)
        {
          ret = memcmp (crq_key_id, pkey_key_id, crq_key_id_len);
          if (ret == 0)
            {
              if (debug)
                success ("Key ids are identical. OK.\n");
            }
          else
            {
              fail ("Key ids differ incorrectly: %d\n", ret);
            }
        }
      else
        {
          fail ("Key_id lengths differ incorrectly: %d - %d\n",
                (int) crq_key_id_len, (int) pkey_key_id_len);
        }


      if (pkey_key_id)
        {
          free (pkey_key_id);
          pkey_key_id = NULL;
        }

      if (crq_key_id)
        {
          free (crq_key_id);
          crq_key_id = NULL;
        }

      gnutls_x509_crq_deinit (crq);
      gnutls_x509_privkey_deinit (pkey);
      gnutls_privkey_deinit (abs_pkey);
    }

  gnutls_global_deinit ();
}
Ejemplo n.º 28
0
static int cipher_test(const char *ocipher, gnutls_cipher_algorithm_t gcipher, unsigned tag_size)
{
	int ret;
	gnutls_aead_cipher_hd_t hd;
	gnutls_datum_t dkey, dnonce;
	unsigned char key[32];
	unsigned char nonce[32];
	size_t enc_data_size, dec_data_size;
	int dec_data_size2;
	EVP_CIPHER_CTX *ctx;
	const EVP_CIPHER *evp_cipher;
	unsigned char tag[64];

	assert(gnutls_rnd(GNUTLS_RND_NONCE, orig_plain_data, sizeof(orig_plain_data)) >= 0);
	assert(gnutls_rnd(GNUTLS_RND_NONCE, buffer_auth, sizeof(buffer_auth)) >= 0);
	assert(gnutls_rnd(GNUTLS_RND_NONCE, key, sizeof(key)) >= 0);
	assert(gnutls_rnd(GNUTLS_RND_NONCE, nonce, sizeof(nonce)) >= 0);

	dkey.data = (void*)key;
	dkey.size = gnutls_cipher_get_key_size(gcipher);
	assert(gnutls_aead_cipher_init(&hd, gcipher, &dkey) >= 0);

	dnonce.data = (void*)nonce;
	dnonce.size = gnutls_cipher_get_iv_size(gcipher);

	enc_data_size = sizeof(enc_data);
	assert(gnutls_aead_cipher_encrypt(hd, dnonce.data, dnonce.size, 
		buffer_auth, sizeof(buffer_auth), tag_size, orig_plain_data, sizeof(orig_plain_data),
		enc_data, &enc_data_size) >= 0);

	if (debug)
		success("encrypted %d bytes, to %d\n", (int)sizeof(orig_plain_data), (int)enc_data_size);

	dec_data_size = sizeof(dec_data);
	ret = gnutls_aead_cipher_decrypt(hd, dnonce.data, dnonce.size, 
		buffer_auth, sizeof(buffer_auth), tag_size, enc_data, enc_data_size,
		dec_data, &dec_data_size);
	if (ret < 0) {
		fail("error in gnutls_aead_cipher_decrypt for %s: %s\n", ocipher, gnutls_strerror(ret));
	}

	if (dec_data_size != sizeof(orig_plain_data) || memcmp(dec_data, orig_plain_data, sizeof(orig_plain_data)) != 0) {
		fail("gnutls encrypt-decrypt failed (got: %d, expected: %d)\n", (int)dec_data_size, (int)sizeof(orig_plain_data));
	}

	gnutls_aead_cipher_deinit(hd);

	/* decrypt with openssl */
	evp_cipher = EVP_get_cipherbyname(ocipher);
	if (!evp_cipher)
		fail("EVP_get_cipherbyname failed for %s\n", ocipher);

	ctx = EVP_CIPHER_CTX_new();
	assert(EVP_CipherInit_ex(ctx, evp_cipher, NULL, key, nonce, 0) > 0);

	EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, tag_size, enc_data+enc_data_size-tag_size);

	dec_data_size2 = sizeof(dec_data);
	assert(EVP_CipherUpdate(ctx, NULL, &dec_data_size2, buffer_auth, sizeof(buffer_auth)) > 0);
	dec_data_size2 = sizeof(dec_data);
	assert(EVP_CipherUpdate(ctx, dec_data, &dec_data_size2, enc_data, enc_data_size-tag_size) > 0);

	dec_data_size = dec_data_size2;
	dec_data_size2 = tag_size;
	assert(EVP_CipherFinal_ex(ctx, tag, &dec_data_size2) > 0);

	if (dec_data_size != sizeof(orig_plain_data) || memcmp(dec_data, orig_plain_data, sizeof(orig_plain_data)) != 0) {
		fail("openssl decrypt failed for %s\n", ocipher);
	}

	EVP_CIPHER_CTX_free(ctx);

	return 0;
}
Ejemplo n.º 29
0
void GenericImage::read_jpg(const char *filename)
{
    unsigned char *p = NULL;
    int w, h, c;

    FILE *fin;

    //fp = fopen(filename, "rb");
    //if(fp == NULL){ fprintf(stderr, "test: fopen() file %s error!\n", filename); exit(0); }
    //else { fprintf(stderr, "test: fopen() file %s ok!\n", filename); fclose(fp); }
    
    if ((fin = fopen(filename, "rb")))
    {
    	//fprintf(stderr, "begin to read in jpg header info.\n");
    	fprintf(stderr, "fopen() file %s ok!\n", filename);
    	
        struct jpeg_decompress_struct cinfo;
        struct jpeg_error_mgr         jerr;

        /* Initialize the JPG decompressor. */

        cinfo.err = jpeg_std_error(&jerr);

        jpeg_create_decompress(&cinfo);
        jpeg_stdio_src(&cinfo, fin);

        /* Grab the JPG header info. */

        jpeg_read_header(&cinfo, TRUE);
        jpeg_start_decompress(&cinfo);

        w = cinfo.output_width;
        h = cinfo.output_height;
        c = cinfo.output_components;

        /* Allocate the pixel buffer and copy pixels there. */

        if ((p = (unsigned char *) malloc ((w) * (h) * (c))))
        {
            int i = h - 1;

            while (cinfo.output_scanline < cinfo.output_height)
            {
                unsigned char *s = p + i * (w) * (c);
                i -= jpeg_read_scanlines(&cinfo, &s, 1);
            }
        }

        /* Finalize the decompression. */

        jpeg_finish_decompress (&cinfo);
        jpeg_destroy_decompress(&cinfo);

        fclose(fin);
  
        //set the generic iimage object
        width = w;
        height = h;
        pixels = p;
        components = c;
        pix_depth = 1;
	    
        print();
        success("file opened\n");
    }
    else
    {
        fail("can't open file\n");
    }
}
// ---------------------------------------------------------------------------
// 
// ---------------------------------------------------------------------------
//
void WlanTxRateAdaptation::OnTxCompleted( 
    WHA::TRate aRate, 
    TBool aSuccess,
    WHA::TQueueId aQueueId,
    WHA::TRate aRequestedRate )
    {
    OsTracePrint( KTxRateAdapt, (TUint8*)
        ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): aRate: 0x%08x"), 
        aRate);
    OsTracePrint( KTxRateAdapt, (TUint8*)
        ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): aSuccess: %d"), 
        aSuccess);
    OsTracePrint( KTxRateAdapt, (TUint8*)
        ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): aQueueId: %d"), 
        aQueueId);
    OsTracePrint( KTxRateAdapt, (TUint8*)
        ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): aRequestedRate: 0x%08x"), 
        aRequestedRate);

    TBool success( aSuccess );

    TUint8 policyId = iQueue2Policy[aQueueId];
    OsTracePrint( KTxRateAdapt, 
        (TUint8*)("UMAC: WlanTxRateAdaptation::OnTxCompleted(): policyId: %d"), 
        policyId);    

    if ( iPolicy[policyId - 1].iCurrentTxRate )
        {
        // as Current Tx Rate is defined for this policy, it means that
        // this rate adaptation object is configured and we can handle this 
        // event
           
        if ( aSuccess )
            {
            // the frame was successfully delivered to nw
            
            // from rate adaptation point of view we are interested in the 
            // actual Tx rate of the frame only if the current rate for the Tx
            // policy in question is still the same as the originally requested Tx
            // rate for this frame.
            // (After we have switched the curent rate to something else, we may
            // still receive Tx completions for frames which we have requested to 
            // be sent with the previous rate. We are not interested in their 
            // actual Tx rate any more.)
            if ( aRequestedRate == iPolicy[policyId - 1].iCurrentTxRate->iBitRate )
                {
                if ( aRate != aRequestedRate )
                    {
                    // actual Tx rate was different than the originally requested
                    // rate. This is a Tx "failure" from Tx rate adaptation point
                    // of view
                    OsTracePrint( KTxRateAdapt, (TUint8*)
                        ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): succeeded with a different rate than requested"));
                    success = EFalse;
                    }
                }
            else
                {
                // curent rate of the Tx policy in question not the same any more
                // as the originally requested rate for this frame. The frame is
                // ignored from Tx rate adaptation considerations            
                OsTracePrint( KTxRateAdapt, (TUint8*)
                    ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): current rate for this Tx policy not same any more as originally requested rate for this frame"));
                OsTracePrint( KTxRateAdapt, (TUint8*)
                    ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): frame ignored from Tx rate adaptation considerations"));
                return;
                }
            }
                
        TRateStep rateStep = OnTxCompleted( success, iPolicy[policyId - 1] );
        
        switch ( rateStep )
            {
            case EStepUp:
                if ( RateStepUp( iPolicy[policyId - 1] ) )
                    {
                    // step up succeeded (i.e. there was a higher rate to switch to)

                    // if probe frame handling hasn't been disabled, the next 
                    // transmitted frame will be handled as a probe frame
                    if ( !iAlgorithmParam.iDisableProbeHandling )
                        {
                        iPolicy[policyId - 1].iProbe = ETrue;                    
                        }                
                    }                
                break;
            case EStepDown:
                RateStepDown( iPolicy[policyId - 1] );
                break;
            case EKeepCurrent:
                // nothing to do here
                break;
            default:
                OsTracePrint( KErrorLevel, 
                    (TUint8*)("UMAC: unkown rate step: %d"), 
                    rateStep );        
                OsAssert( (TUint8*)("UMAC: panic"), (TUint8*)(WLAN_FILE), __LINE__ );                        
            }    
        }
    else
        {
        // Current Tx Rate is not defined for this policy, which means that
        // this rate adaptation object is not configured (it has been
        // reset) and cannot handle the event. So we just discard it
        OsTracePrint( KTxRateAdapt, (TUint8*)
            ("UMAC: WlanTxRateAdaptation::OnTxCompleted(): Rate adaptation not configured. Tx complete event discarded"));
        }
    }