// Open an archive. // If the user has asked for compression, // then we popen(2) a pipe to gzip or zip. // This does 'in place' compression. // void open_archive(const char* filename_prefix, FILE*& f){ char path[MAXPATHLEN]; char command[MAXPATHLEN+512]; if (daily_dir) { time_t time_time = time_int; char dirname[32]; strftime(dirname, sizeof(dirname), "%Y_%m_%d", gmtime(&time_time)); safe_strcpy(path, config.project_path("archives/%s",dirname)); if (mkdir(path,0775)) { if(errno!=EEXIST) { char errstr[256]; sprintf(errstr, "could not create directory '%s': %s\n", path, strerror(errno)); fail(errstr); } } safe_strcpy(path, config.project_path( "archives/%s/%s_%d.xml", dirname, filename_prefix, time_int ) ); } else { safe_strcpy(path, config.project_path("archives/%s_%d.xml", filename_prefix, time_int) ); } // append appropriate suffix for file type safe_strcat(path, suffix[compression_type]); // and construct appropriate command if needed if (compression_type == COMPRESSION_GZIP) { snprintf(command, sizeof(command), "gzip - > %s", path); } if (compression_type == COMPRESSION_ZIP) { snprintf(command, sizeof(command), "zip - - > %s", path); } log_messages.printf(MSG_NORMAL, "Opening archive %s\n", path ); if (compression_type == COMPRESSION_NONE) { if (!(f = fopen(path,"w"))) { char buf[256]; sprintf(buf, "Can't open archive file %s %s\n", path, errno?strerror(errno):"" ); fail(buf); } } else { f = popen(command,"w"); if (!f) { log_messages.printf(MSG_CRITICAL, "Can't open pipe %s %s\n", command, errno?strerror(errno):"" ); exit(4); } } // set buffering to line buffered, since we are outputing XML on a // line-by-line basis. // setlinebuf(f); return; }
/* Test all data types update operation. */ void BasicUpdateTests::full_update () { int iRow = 0; FdoPtr<FdoPropertyValueCollection> values; FdoPtr<FdoISelect> selectCmd; FdoPtr<FdoIFeatureReader> reader; if (CreateSchemaOnly()) return; try { mConnection = ArcSDETests::GetConnection (); mConnection->SetConnectionString (ArcSDETestConfig::ConnStringMetadcovSingleDb()); mConnection->Open (); // Clean up previous tests: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); // Insert 2 rows of data: while (iRow<=1) { FdoPtr<FdoIInsert> insert = (FdoIInsert*)mConnection->CreateCommand (FdoCommandType_Insert); insert->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); // misnomer, it's not a feature class values = insert->GetPropertyValues (); for (int i = 0; i < PropertyCount; i++) { FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (); value->SetName (Data[i]->mPropertyName); FdoPtr<FdoValueExpression> expression = (FdoValueExpression*)ArcSDETests::ParseByDataType (Data[i]->mPropertyData[iRow], Data[i]->mPropertyType); value->SetValue (expression); values->Add (value); } reader = insert->Execute (); // none returned: reader->Close (); iRow++; } // check by doing a select selectCmd = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); selectCmd->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); reader = selectCmd->Execute (); FdoInt32 iSelectedRow = 0; while (reader->ReadNext ()) { // NOTE: we're assuming we receive the rows in the same order we inserted them for (int i = 0; i < PropertyCount; i++) checkEqual(reader, Data[i]->mPropertyName, Data[i]->mPropertyType, Data[i]->mPropertyData[iSelectedRow]); iSelectedRow++; } reader->Close (); // Update both rows, providing several values in the *reverse* order as class properties appear: FdoPtr<FdoIUpdate> update = (FdoIUpdate*)mConnection->CreateCommand (FdoCommandType_Update); update->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); // misnomer, it's not a feature class wchar_t filter[1024]; wcscpy (filter, Data[3]->mPropertyName); wcscat (filter, L" = "); wcscat (filter, Data[3]->mPropertyData[0]); update->SetFilter (FdoPtr<FdoFilter>(FdoFilter::Parse (filter))); values = update->GetPropertyValues (); for (int iPropertyIndex = 0; iPropertyIndex < PropertyCount; iPropertyIndex++) { int iDataIndex = (PropertyCount - 1) - iPropertyIndex; FdoPtr<FdoValueExpression> expression; expression = (FdoValueExpression*)ArcSDETests::ParseByDataType (Data[iDataIndex]->mPropertyData[iRow], Data[iDataIndex]->mPropertyType); FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (Data[iDataIndex]->mPropertyName, expression); values->Add (value); } FdoInt32 iUpdatedRows = update->Execute (); //NOTE: iUpdatedRows is currently always 1, regardless of the # of rows actually affected. // check by doing a select selectCmd = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); selectCmd->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); reader = selectCmd->Execute (); while (reader->ReadNext ()) for (int i = 0; i < PropertyCount; i++) checkEqual(reader, Data[i]->mPropertyName, Data[i]->mPropertyType, Data[i]->mPropertyData[iRow]); reader->Close (); iRow++; // Update both rows, providing *mostly NULL value* in the *same* order as class properties appear: update = (FdoIUpdate*)mConnection->CreateCommand (FdoCommandType_Update); update->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); // misnomer, it's not a feature class wcscpy (filter, Data[3]->mPropertyName); wcscat (filter, L" = "); wcscat (filter, Data[3]->mPropertyData[iRow-1]); update->SetFilter (FdoPtr<FdoFilter>(FdoFilter::Parse (filter))); values = update->GetPropertyValues (); for (int i = 0; i < PropertyCount; i++) { FdoPtr<FdoValueExpression> expression; expression = (FdoValueExpression*)ArcSDETests::ParseByDataType (Data[i]->mPropertyData[iRow], Data[i]->mPropertyType); FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (Data[i]->mPropertyName, expression); value->SetValue (expression); values->Add (value); } iUpdatedRows = update->Execute (); //NOTE: iUpdatedRows is currently always 1, regardless of the # of rows actually affected. // check by doing a select selectCmd = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); selectCmd->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); reader = selectCmd->Execute (); while (reader->ReadNext ()) for (int i = 0; i < PropertyCount; i++) checkEqual(reader, Data[i]->mPropertyName, Data[i]->mPropertyType, Data[i]->mPropertyData[iRow]); reader->Close (); // Clean up after test: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); } catch (FdoException* ge) { fail (ge); } }
/* Test spatial filter. */ void BasicUpdateTests::spatial_filter () { if (CreateSchemaOnly()) return; try { mConnection = ArcSDETests::GetConnection (); mConnection->SetConnectionString (ArcSDETestConfig::ConnStringMetadcovSingleDb()); mConnection->Open (); // Clean up previous tests: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); FdoPtr<FdoIInsert> insert = (FdoIInsert*)mConnection->CreateCommand (FdoCommandType_Insert); insert->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); FdoPtr<FdoPropertyValueCollection> values = insert->GetPropertyValues (); FdoPtr<FdoValueExpression> expression = (FdoValueExpression*)FdoExpression::Parse (Data[0]->mPropertyData[0]); FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (Data[0]->mPropertyName, expression); values->Add (value); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5010.282 5011.717, 5010.4 5011.7, 5010.4 5011.3, 5010.282 5011.717))')"); value = FdoPropertyValue::Create ((FdoString*)GetGeomPropName(), expression); values->Add (value); FdoPtr<FdoIFeatureReader> reader = insert->Execute (); int id1; while (reader->ReadNext ()) id1 = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); value = values->GetItem (Data[0]->mPropertyName); expression = (FdoValueExpression*)FdoExpression::Parse (L"'John Smith'"); value->SetValue (expression); value = values->GetItem ((FdoString*)GetGeomPropName()); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5000.919 5000.277, 5000.5 5000.2, 5000.5 5000.7, 5000.919 5000.277))')"); value->SetValue (expression); reader = insert->Execute (); int id2; while (reader->ReadNext ()) id2 = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); value = values->GetItem (Data[0]->mPropertyName); expression = (FdoValueExpression*)FdoExpression::Parse (L"'Mott the Hoople'"); value->SetValue (expression); value = values->GetItem ((FdoString*)GetGeomPropName()); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5014.262 5015.018, 5014.3 5015.9, 5014.9 5015.9, 5014.262 5015.018))')"); value->SetValue (expression); reader = insert->Execute (); int id3; while (reader->ReadNext ()) id3 = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); // do a spatial filtered update FdoPtr<FdoIUpdate> update = (FdoIUpdate*)mConnection->CreateCommand (FdoCommandType_Update); update->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); update->SetFilter (FdoPtr<FdoFilter>(FdoFilter::Parse (L"SHAPE INTERSECTS GEOMFROMTEXT ('POLYGON XY (( 5012 5012, 5020 5012, 5020 5016, 5012 5016, 5012 5012 ))')"))); values = update->GetPropertyValues (); expression = (FdoValueExpression*)FdoExpression::Parse (L"'Alice in Wonderland'"); value = FdoPropertyValue::Create (Data[0]->mPropertyName, expression); values->Add (value); if (1 != update->Execute ()) CPPUNIT_FAIL ("update execute failed"); // check by doing a select FdoPtr<FdoISelect> select = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); select->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); reader = select->Execute (); int id; while (reader->ReadNext ()) { id = reader->GetInt32 ((FdoString*)GetIdPropName()); FdoString* item = reader->GetString (Data[0]->mPropertyName); if (id == id3) CPPUNIT_ASSERT_MESSAGE ("value not changed", 0 == wcscmp (item, L"Alice in Wonderland")); else CPPUNIT_ASSERT_MESSAGE ("value mistakenly changed", 0 != wcscmp (item, L"Alice in Wonderland")); } reader->Close(); // Clean up after test: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); } catch (FdoException* ge) { fail (ge); } }
/* * Test iterative X25519 computation through lower layer MPI routines. * * Input: K (as hex string), ITER, R (as hex string) * * where R is expected result of iterating X25519 by ITER times. * */ static void test_it (int testno, const char *k_str, int iter, const char *result_str) { gcry_ctx_t ctx; gpg_error_t err; void *buffer = NULL; size_t buflen; gcry_mpi_t mpi_k = NULL; gcry_mpi_t mpi_x = NULL; gcry_mpi_point_t P = NULL; gcry_mpi_point_t Q; int i; gcry_mpi_t mpi_kk = NULL; if (verbose > 1) info ("Running test %d: iteration=%d\n", testno, iter); gcry_mpi_ec_new (&ctx, NULL, "Curve25519"); Q = gcry_mpi_point_new (0); if (!(buffer = hex2buffer (k_str, &buflen)) || buflen != 32) { fail ("error scanning MPI for test %d, %s: %s", testno, "k", "invalid hex string"); goto leave; } reverse_buffer (buffer, buflen); if ((err = gcry_mpi_scan (&mpi_x, GCRYMPI_FMT_USG, buffer, buflen, NULL))) { fail ("error scanning MPI for test %d, %s: %s", testno, "x", gpg_strerror (err)); goto leave; } xfree (buffer); buffer = NULL; P = gcry_mpi_point_set (NULL, mpi_x, NULL, GCRYMPI_CONST_ONE); mpi_k = gcry_mpi_copy (mpi_x); if (debug) print_mpi ("k", mpi_k); for (i = 0; i < iter; i++) { /* * Another variant of decodeScalar25519 thing. */ mpi_kk = gcry_mpi_set (mpi_kk, mpi_k); gcry_mpi_set_bit (mpi_kk, 254); gcry_mpi_clear_bit (mpi_kk, 255); gcry_mpi_clear_bit (mpi_kk, 0); gcry_mpi_clear_bit (mpi_kk, 1); gcry_mpi_clear_bit (mpi_kk, 2); gcry_mpi_ec_mul (Q, mpi_kk, P, ctx); P = gcry_mpi_point_set (P, mpi_k, NULL, GCRYMPI_CONST_ONE); gcry_mpi_ec_get_affine (mpi_k, NULL, Q, ctx); if (debug) print_mpi ("k", mpi_k); } { unsigned char res[32]; char *r, *r0; gcry_mpi_print (GCRYMPI_FMT_USG, res, 32, NULL, mpi_k); reverse_buffer (res, 32); r0 = r = xmalloc (65); if (!r0) { fail ("memory allocation for test %d", testno); goto leave; } for (i=0; i < 32; i++, r += 2) snprintf (r, 3, "%02x", res[i]); if (strcmp (result_str, r0)) { fail ("curv25519 failed for test %d: %s", testno, "wrong value returned"); info (" expected: '%s'", result_str); info (" got: '%s'", r0); } xfree (r0); } leave: gcry_mpi_release (mpi_kk); gcry_mpi_release (mpi_k); gcry_mpi_point_release (P); gcry_mpi_release (mpi_x); xfree (buffer); gcry_mpi_point_release (Q); gcry_ctx_release (ctx); }
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; }
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 (); }
void DataExporter::historyError(const QString &errorText) { fail(QString("Fail to get data from db: %1").arg(errorText)); }
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 (); }
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); }
void kmeans( int dim, // dimension of data double *X, // pointer to data int n, // number of elements int k, // number of clusters double *cluster_centroid, // initial cluster centroids int *cluster_assignment_final // output ) { double *dist = (double *)malloc(sizeof(double) * n * k); int *cluster_assignment_cur = (int *)malloc(sizeof(int) * n); int *cluster_assignment_prev = (int *)malloc(sizeof(int) * n); double *point_move_score = (double *)malloc(sizeof(double) * n * k); if (!dist || !cluster_assignment_cur || !cluster_assignment_prev || !point_move_score) fail("Error allocating dist arrays"); // initial setup calc_all_distances(dim, n, k, X, cluster_centroid, dist); choose_all_clusters_from_distances(dim, n, k, dist, cluster_assignment_cur); copy_assignment_array(n, cluster_assignment_cur, cluster_assignment_prev); // BATCH UPDATE double prev_totD = BIG_double; int batch_iteration = 0; while (batch_iteration < MAX_ITERATIONS) { // printf("batch iteration %d \n", batch_iteration); // cluster_diag(dim, n, k, X, cluster_assignment_cur, cluster_centroid); // update cluster centroids calc_cluster_centroids(dim, n, k, X, cluster_assignment_cur, cluster_centroid); // deal with empty clusters // XXXXXXXXXXXXXX // see if we've failed to improve double totD = calc_total_distance(dim, n, k, X, cluster_centroid, cluster_assignment_cur); if (totD > prev_totD) // failed to improve - currently solution worse than previous { // restore old assignments copy_assignment_array(n, cluster_assignment_prev, cluster_assignment_cur); // recalc centroids calc_cluster_centroids(dim, n, k, X, cluster_assignment_cur, cluster_centroid); printf(" negative progress made on this step - iteration completed (%.2f) \n", totD - prev_totD); // done with this phase break; } // save previous step copy_assignment_array(n, cluster_assignment_cur, cluster_assignment_prev); // move all points to nearest cluster calc_all_distances(dim, n, k, X, cluster_centroid, dist); choose_all_clusters_from_distances(dim, n, k, dist, cluster_assignment_cur); int change_count = assignment_change_count(n, cluster_assignment_cur, cluster_assignment_prev); printf("%3d %u %9d %16.2f %17.2f\n", batch_iteration, 1, change_count, totD, totD - prev_totD); fflush(stdout); // done with this phase if nothing has changed if (change_count == 0) { printf(" no change made on this step - iteration completed \n"); break; } prev_totD = totD; batch_iteration++; } cluster_diag(dim, n, k, X, cluster_assignment_cur, cluster_centroid); /* THe online update prtion of this code has never worked properly, but batch update has been adequate for our projects so far // ONLINE UPDATE int online_iteration = 0; int last_point_moved = 0; int cluster_changed[MAX_CLUSTERS]; for (int ii = 0; ii < k; ii++) cluster_changed[ii] = 1; int cluster_member_count[MAX_CLUSTERS]; get_cluster_member_count(n, k, cluster_assignment_cur, cluster_member_count); while (online_iteration < MAX_ITERATIONS) { // printf("online iteration %d \n", online_iteration); // for each cluster for (int ii = 0; ii < k; ii++) if (cluster_changed[ii]) update_delta_score_table(dim, n, k, X, cluster_assignment_cur, cluster_centroid, cluster_member_count, point_move_score, ii); // pick a point to move // look at points in sequence starting at one after previously moved point int make_move = 0; int point_to_move = -1; int target_cluster = -1; for (int ii = 0; ii < n; ii++) { int point_to_consider = (last_point_moved + 1 + ii) % n; // find the best target for it int best_target_cluster = -1; int best_match_count = 0; double best_delta = BIG_double; // for each possible target for (int jj = 0; jj < k; jj++) { double cur_delta = point_move_score[point_to_consider*k + jj]; // is this the best move so far? if (cur_delta < best_delta) // yes - record it { best_target_cluster = jj; best_delta = cur_delta; best_match_count = 1; } else if (cur_delta == best_delta) // no, but it's tied with the best one best_match_count++; } // is the best cluster for this point its current cluster? if (best_target_cluster == cluster_assignment_cur[point_to_consider]) // yes - don't move this point continue; // do we have a unique best move? if (best_match_count > 1) // no - don't move this point (ignore ties) continue; else // yes - we've found a good point to move { point_to_move = point_to_consider; target_cluster = best_target_cluster; make_move = 1; break; } } if (make_move) { // where should we move it to? printf(" %10d: moved %d to %d \n", point_to_move, cluster_assignment_cur[point_to_move], target_cluster); // mark which clusters have been modified for (int ii = 0; ii < k; ii++) cluster_changed[ii] = 0; cluster_changed[cluster_assignment_cur[point_to_move]] = 1; cluster_changed[target_cluster] = 1; // perform move perform_move(dim, n, k, X, cluster_assignment_cur, cluster_centroid, cluster_member_count, point_to_move, target_cluster); // count an iteration every time we've cycled through all the points if (point_to_move < last_point_moved) online_iteration++; last_point_moved = point_to_move; } } */ // printf("iterations: %3d %3d \n", batch_iteration, online_iteration); // write to output array copy_assignment_array(n, cluster_assignment_cur, cluster_assignment_final); free(dist); free(cluster_assignment_cur); free(cluster_assignment_prev); free(point_move_score); }
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(); }
MAIN_ENV #endif #include "specific.h" int main( int argc, /* arg count */ char * argv[] /* arg vector */ ){ static char * context = "main(winnow)"; int2D matrix; /* matrix of values */ bool2D mask; /* mask on values */ int nr, nc, nrM, ncM; /* sizes */ pt1D pt; /* resulting point vector */ int npt; /* number of points to keep */ char * infnMat = NULL; /* input matrix file name */ char * infnMask = NULL; /* input mask file name */ char * outfn = NULL; /* output file name */ int argd = 1; /* argument index */ /* arguments */ #if NUMA MAIN_INITENV(,32000000) #endif while (argd < argc){ CHECK(argv[argd][0] == '-', fail(context, "bad argument", "index", "%d", argd, NULL)); switch(argv[argd][1]){ case 'N' : npt = arg_int(context, argc, argv, argd+1, argv[argd]); argd += 2; break; #if GRAPHICS case 'g' : gfx_open(app_winnow, arg_gfxCtrl(context, argc, argv, argd+1, argv[argd])); argd += 2; break; #endif #if MIMD case 'p' : DataDist = arg_dataDist(context, argc, argv, argd+1, argv[argd]); ParWidth = arg_int(context, argc, argv, argd+2, argv[argd]); argd += 3; break; #endif case 'i' : infnMat = arg_str(context, argc, argv, argd+1, argv[argd]); infnMask = arg_str(context, argc, argv, argd+2, argv[argd]); argd += 3; break; case 'o' : outfn = arg_str(context, argc, argv, argd+1, argv[argd]); argd += 2; break; case 'u' : io_init(FALSE); argd += 1; break; default : fail(context, "unknown flag", "flag", "%s", argv[argd], NULL); break; } } /* setup */ #if MIMD sch_init(DataDist); #endif CHECK(npt > 0, fail(context, "non-positive number of points requested", "number of points", "%d", npt, NULL)); io_rdInt2D(context, infnMat, matrix, &nr, &nc); io_rdBool2D(context, infnMask, mask, &nrM, &ncM); CHECK((nr == nrM) && (nc == ncM), fail(context, "matrix/mask size mismatch", "matrix file", "%s", infnMat, "mask file", "%s", infnMask, NULL)); /* run */ winnow(matrix, mask, nr, nc, pt, npt); /* takedown */ io_wrPt1D(context, outfn, pt, npt); #if GRAPHICS gfx_close(); #endif #if IEEE ieee_retrospective(stderr); #endif #if NUMA MAIN_END; #endif return 0; }
int archive_wu(DB_WORKUNIT& wu) { int n; n = fprintf(wu_stream, "<workunit_archive>\n" " <id>%lu</id>\n", wu.id ); if (n >= 0) n = fprintf(wu_stream, " <create_time>%d</create_time>\n" " <appid>%lu</appid>\n" " <name>%s</name>\n" " <xml_doc>%s</xml_doc>\n" " <batch>%d</batch>\n" " <rsc_fpops_est>%.15e</rsc_fpops_est>\n" " <rsc_fpops_bound>%.15e</rsc_fpops_bound>\n" " <rsc_memory_bound>%.15e</rsc_memory_bound>\n" " <rsc_disk_bound>%.15e</rsc_disk_bound>\n" " <need_validate>%d</need_validate>\n" " <canonical_resultid>%lu</canonical_resultid>\n" " <canonical_credit>%.15e</canonical_credit>\n" " <transition_time>%d</transition_time>\n" " <delay_bound>%d</delay_bound>\n" " <error_mask>%d</error_mask>\n" " <file_delete_state>%d</file_delete_state>\n" " <assimilate_state>%d</assimilate_state>\n" " <hr_class>%d</hr_class>\n" " <opaque>%f</opaque>\n" " <min_quorum>%d</min_quorum>\n" " <target_nresults>%d</target_nresults>\n" " <max_error_results>%d</max_error_results>\n" " <max_total_results>%d</max_total_results>\n" " <max_success_results>%d</max_success_results>\n" " <result_template_file>%s</result_template_file>\n" " <priority>%d</priority>\n" " <mod_time>%s</mod_time>\n", wu.create_time, wu.appid, wu.name, wu.xml_doc, wu.batch, wu.rsc_fpops_est, wu.rsc_fpops_bound, wu.rsc_memory_bound, wu.rsc_disk_bound, wu.need_validate, wu.canonical_resultid, wu.canonical_credit, wu.transition_time, wu.delay_bound, wu.error_mask, wu.file_delete_state, wu.assimilate_state, wu.hr_class, wu.opaque, wu.min_quorum, wu.target_nresults, wu.max_error_results, wu.max_total_results, wu.max_success_results, wu.result_template_file, wu.priority, wu.mod_time ); if (n >= 0) n = fprintf(wu_stream, "</workunit_archive>\n" ); if (n >= 0) { n = fprintf(wu_index_stream, "%lu %d %s\n", wu.id, time_int, wu.name ); } if (n < 0) fail("fprintf() failed\n"); return 0; }
int archive_result(DB_RESULT& result) { int n; n = fprintf(re_stream, "<result_archive>\n" " <id>%lu</id>\n", result.id ); // xml_escape can increase size by factor of 6, e.g. x -> &#NNN; // char buf[BLOB_SIZE*6]; xml_escape(result.stderr_out, buf, sizeof(buf)); if (n >= 0) n = fprintf( re_stream, " <create_time>%d</create_time>\n" " <workunitid>%lu</workunitid>\n" " <server_state>%d</server_state>\n" " <outcome>%d</outcome>\n" " <client_state>%d</client_state>\n" " <hostid>%lu</hostid>\n" " <userid>%lu</userid>\n" " <report_deadline>%d</report_deadline>\n" " <sent_time>%d</sent_time>\n" " <received_time>%d</received_time>\n" " <name>%s</name>\n" " <cpu_time>%.15e</cpu_time>\n" " <xml_doc_in>%s</xml_doc_in>\n" " <xml_doc_out>%s</xml_doc_out>\n" " <stderr_out>%s</stderr_out>\n" " <batch>%d</batch>\n" " <file_delete_state>%d</file_delete_state>\n" " <validate_state>%d</validate_state>\n" " <claimed_credit>%.15e</claimed_credit>\n" " <granted_credit>%.15e</granted_credit>\n" " <opaque>%f</opaque>\n" " <random>%d</random>\n" " <app_version_num>%d</app_version_num>\n" " <app_version_id>%ld</app_version_id>\n" " <appid>%lu</appid>\n" " <exit_status>%d</exit_status>\n" " <teamid>%lu</teamid>\n" " <priority>%d</priority>\n" " <mod_time>%s</mod_time>\n", result.create_time, result.workunitid, result.server_state, result.outcome, result.client_state, result.hostid, result.userid, result.report_deadline, result.sent_time, result.received_time, result.name, result.cpu_time, result.xml_doc_in, result.xml_doc_out, buf, result.batch, result.file_delete_state, result.validate_state, result.claimed_credit, result.granted_credit, result.opaque, result.random, result.app_version_num, result.app_version_id, result.appid, result.exit_status, result.teamid, result.priority, result.mod_time ); if (n >= 0) n = fprintf(re_stream, "</result_archive>\n" ); if (n >= 0) { n = fprintf(re_index_stream, "%lu %d %s\n", result.id, time_int, result.name ); } if (n < 0) fail("fprintf() failed\n"); return 0; }
static void test_cmp (void) { gpg_error_t rc; gcry_mpi_t zero, zero2; gcry_mpi_t one; gcry_mpi_t two; gcry_mpi_t all_ones; gcry_mpi_t opa1, opa2; gcry_mpi_t opa1s, opa2s; gcry_mpi_t opa0, opa02; zero = gcry_mpi_new (0); zero2= gcry_mpi_set_ui (NULL, 0); one = gcry_mpi_set_ui (NULL, 1); two = gcry_mpi_set_ui (NULL, 2); rc = gcry_mpi_scan (&all_ones, GCRYMPI_FMT_USG, ones, sizeof(ones), NULL); if (rc) die ("scanning number failed at line %d", __LINE__); opa0 = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("a"), 0); opa02 = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("b"), 0); opa1 = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("aaaaaaaaaaaaaaaa"), 16*8); opa1s = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("a"), 1*8); opa2 = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("bbbbbbbbbbbbbbbb"), 16*8); opa2s = gcry_mpi_set_opaque (NULL, gcry_xstrdup ("b"), 1*8); /* Single limb test with cmp_ui */ if (gcry_mpi_cmp_ui (zero, 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (!(gcry_mpi_cmp_ui (zero, 1) < 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (!(gcry_mpi_cmp_ui (zero, (-1)) < 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (gcry_mpi_cmp_ui (two, 2)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (!(gcry_mpi_cmp_ui (two, 3) < 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (!(gcry_mpi_cmp_ui (two, 1) > 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); /* Multi limb tests with cmp_ui. */ if (!(gcry_mpi_cmp_ui (all_ones, 0) > 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); if (!(gcry_mpi_cmp_ui (all_ones, (-1)) > 0)) fail ("mpi_cmp_ui failed at line %d", __LINE__); /* Single limb test with cmp */ if (gcry_mpi_cmp (zero, zero2)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (zero, one) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (one, zero) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); gcry_mpi_neg (one, one); if (!(gcry_mpi_cmp (zero, one) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (one, zero) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (one, two) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); gcry_mpi_neg (one, one); if (!(gcry_mpi_cmp (one, two) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (two, one) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (one, all_ones) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); /* Tests with opaque values. */ if (!(gcry_mpi_cmp (opa1, one) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (one, opa1) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa0, opa02) == 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa1s, opa1) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa2, opa1s) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa1, opa2) < 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa2, opa1) > 0)) fail ("mpi_cmp failed at line %d", __LINE__); if (!(gcry_mpi_cmp (opa1, opa1) == 0)) fail ("mpi_cmp failed at line %d", __LINE__); gcry_mpi_release(opa2s); gcry_mpi_release(opa2); gcry_mpi_release(opa1s); gcry_mpi_release(opa1); gcry_mpi_release(opa02); gcry_mpi_release(opa0); gcry_mpi_release(all_ones); gcry_mpi_release(two); gcry_mpi_release(one); gcry_mpi_release(zero2); gcry_mpi_release(zero); }
static void test_equals_int(char *what, int a, int b) { test_count++; if (a != b) fail(what); }
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; }
static void test_equals_str(char *what, const char *a, const char *b) { test_count++; if (strcmp(a, b)) fail(what); }
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"); }
static void test_equals_ull(char *what, uint64_t a, uint64_t b) { test_count++; if (a != b) fail(what); }
/* * Test X25519 functionality through higher layer crypto routines. * * Input: K (as hex string), U (as hex string), R (as hex string) * * where R is expected result of X25519 (K, U). * * It calls gcry_pk_decrypt with Curve25519 private key and let * it compute X25519. */ static void test_cv (int testno, const char *k_str, const char *u_str, const char *result_str) { gpg_error_t err; void *buffer = NULL; size_t buflen; gcry_sexp_t s_pk = NULL; gcry_mpi_t mpi_k = NULL; gcry_sexp_t s_data = NULL; gcry_sexp_t s_result = NULL; gcry_sexp_t s_tmp = NULL; unsigned char *res = NULL; size_t res_len; if (verbose > 1) info ("Running test %d\n", testno); if (!(buffer = hex2buffer (k_str, &buflen)) || buflen != 32) { fail ("error building s-exp for test %d, %s: %s", testno, "k", "invalid hex string"); goto leave; } reverse_buffer (buffer, buflen); if ((err = gcry_mpi_scan (&mpi_k, GCRYMPI_FMT_USG, buffer, buflen, NULL))) { fail ("error converting MPI for test %d: %s", testno, gpg_strerror (err)); goto leave; } if ((err = gcry_sexp_build (&s_data, NULL, "%m", mpi_k))) { fail ("error building s-exp for test %d, %s: %s", testno, "data", gpg_strerror (err)); goto leave; } xfree (buffer); if (!(buffer = hex2buffer (u_str, &buflen)) || buflen != 32) { fail ("error building s-exp for test %d, %s: %s", testno, "u", "invalid hex string"); goto leave; } /* * The procedure of decodeUCoordinate will be done internally * by _gcry_ecc_mont_decodepoint. So, we just put the little-endian * binary to build S-exp. * * We could add the prefix 0x40, but libgcrypt also supports * format with no prefix. So, it is OK not to put the prefix. */ if ((err = gcry_sexp_build (&s_pk, NULL, "(public-key" " (ecc" " (curve \"Curve25519\")" " (flags djb-tweak)" " (q%b)))", (int)buflen, buffer))) { fail ("error building s-exp for test %d, %s: %s", testno, "pk", gpg_strerror (err)); goto leave; } xfree (buffer); buffer = NULL; if ((err = gcry_pk_encrypt (&s_result, s_data, s_pk))) fail ("gcry_pk_encrypt failed for test %d: %s", testno, gpg_strerror (err)); s_tmp = gcry_sexp_find_token (s_result, "s", 0); if (!s_tmp || !(res = gcry_sexp_nth_buffer (s_tmp, 1, &res_len))) fail ("gcry_pk_encrypt failed for test %d: %s", testno, "missing value"); else { char *r, *r0; int i; /* To skip the prefix 0x40, for-loop start with i=1 */ r0 = r = xmalloc (2*(res_len)+1); if (!r0) { fail ("memory allocation for test %d", testno); goto leave; } for (i=1; i < res_len; i++, r += 2) snprintf (r, 3, "%02x", res[i]); if (strcmp (result_str, r0)) { fail ("gcry_pk_encrypt failed for test %d: %s", testno, "wrong value returned"); info (" expected: '%s'", result_str); info (" got: '%s'", r0); } xfree (r0); } leave: xfree (res); gcry_mpi_release (mpi_k); gcry_sexp_release (s_tmp); gcry_sexp_release (s_result); gcry_sexp_release (s_data); gcry_sexp_release (s_pk); xfree (buffer); }
static void test_notequals_ptr(char *what, void *a, void *b) { test_count++; if (a == b) fail(what); }
static void check_cv25519 (void) { int ntests; info ("Checking Curve25519.\n"); ntests = 0; /* * Values are cited from RFC-7748: 5.2. Test Vectors. * Following two tests are for the first type test. */ test_cv (1, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c", "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"); ntests++; test_cv (2, "4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d", "e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493", "95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957"); ntests++; /* * Additional test. Value is from second type test. */ test_cv (3, G_X, G_X, "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079"); ntests++; /* * Following two tests are for the second type test, * with one iteration and 1,000 iterations. (1,000,000 iterations * takes too long.) */ test_it (4, G_X, 1, "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079"); ntests++; test_it (5, G_X, 1000, "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51"); ntests++; /* * Last test is from: 6. Diffie-Hellman, 6.1. Curve25519 */ test_dh (6, /* Alice's private key, a */ "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", /* Alice's public key, X25519(a, 9) */ "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a", /* Bob's private key, b */ "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", /* Bob's public key, X25519(b, 9) */ "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", /* Their shared secret, K */ "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"); ntests++; /* Seven tests which results 0. */ test_cv (7, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (8, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "0100000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (9, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (10, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (11, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (12, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; test_cv (13, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", "0000000000000000000000000000000000000000000000000000000000000000"); ntests++; /* Five tests which resulted 0 if decodeUCoordinate didn't change MSB. */ test_cv (14, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880", "7ce548bc4919008436244d2da7a9906528fe3a6d278047654bd32d8acde9707b"); ntests++; test_cv (15, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7", "e17902e989a034acdf7248260e2c94cdaf2fe1e72aaac7024a128058b6189939"); ntests++; test_cv (16, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "ea6e6ddf0685c31e152d5818441ac9ac8db1a01f3d6cb5041b07443a901e7145"); ntests++; test_cv (17, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "845ddce7b3a9b3ee01a2f1fd4282ad293310f7a232cbc5459fb35d94bccc9d05"); ntests++; test_cv (18, "a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4", "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "6989e2cb1cea159acf121b0af6bf77493189c9bd32c2dac71669b540f9488247"); ntests++; if (ntests != N_TESTS) fail ("did %d tests but expected %d", ntests, N_TESTS); else if ((ntests % 256)) show_note ("%d tests done\n", ntests); }
static void test_notnull_ptr(char *what, void *a) { test_count++; if (NULL == a) fail(what); }
int main(int argc, char *argv[]) { if (argc != 3) fail(argv[0], "%s: wrong number of argument", 0); if (symlink(argv[1], argv[2]) < 0) fail(argv[1], "", 1); return 0; }
/* * unreg * * This routine unregisters a component (either as supplied or it will * find the component based upon supplied criteria). If requested, * the routine will unregister recursively. * * pws The component to unregister. This parameter can be NULL. * criteria If pws is NULL, use criteria to determine a component * to unregister. * recursive If non zero, unregister recursively. * * Return: Nothing. * Side effects: Could unregister one or more components. */ static void unreg(Wsreg_component *pws, Criteria criteria, int recursive) { Wsreg_query *pq = NULL; int found_here = 0; /* * This ugly special case exists because of webstart 2 cli * legacy scripts. There are several possibilities. * * 1 mnemonic (FIND_UNAME) only (! FIND_LOCN) * We have to unregister all instances when * a mnemonic (name) is given, without a location. * * The algorithm loops on finding and removing the first * instance, till there are no more instances. When * instance #1 is removed, the instance #s of all instances * change so there is always an instance #1. * * 2 mnemonic (FIND_UNAME) and "-" for location (FIND_LOCN) * The same as 1. * * 3 mnemonic (FIND_UNAME) and 7*10DIGIT (FIND_LOCN) * the attribute 'id' == the location #. * * 4 mnemonic (FIND_UNAME) and location (FIND_LOCN) */ if (criteria.mask & FIND_UNAME) { int x = 1, y = 0, total = 0; char *pcdata = NULL; Wsreg_component *pwsany = NULL; Wsreg_query *pqany = wsreg_query_create(); pq = wsreg_query_create(); wsreg_query_set_unique_name(pq, criteria.uniquename); wsreg_query_set_unique_name(pqany, criteria.uniquename); /* x == x is always true. '1' doesn't satisfy lint. */ while (x == x) { wsreg_query_set_instance(pq, x); pws = wsreg_get(pq); pwsany = wsreg_get(pqany); /* * We have to step through every instance, but * we do not know how many instances there are. * It is not enough to wait for an instance * which is not in the registry, since some * instances can be deregistered discontiguously. * Continue until either 128 instances tried * AN ARBITRARY MAX #, or no more instances exist. */ if (x > 128 || pwsany == NULL) break; wsreg_free_component(pwsany); /* Count every time through the loop */ x++; if (pws == NULL) { continue; } y = 0; /* Cases 1 and 2 above */ if (!(criteria.mask & FIND_LOCN) || ((criteria.mask & FIND_LOCN) && (criteria.location != NULL) && (strncmp("-", criteria.location, 2) == 0))) { y = 1; } /* Case 3 - check id attribute */ pcdata = wsreg_get_data(pws, "id"); if ((criteria.mask & FIND_LOCN) && (pcdata != NULL) && (strncmp(pcdata, criteria.location, strlen(pcdata)) == 0)) { y = 3; } /* Case 4 - check location */ pcdata = wsreg_get_location(pws); if ((criteria.mask & FIND_LOCN) && (pcdata != NULL) && (strncmp(pcdata, criteria.location, strlen(pcdata)) == 0)) { y = 4; } if (y != 0) { /* Unreg first children then dependents. */ rec_unreg(pws, CHILDREN); rec_unreg(pws, DEPENDENCIES); /* Unreg the component itself. */ if (_private_wsreg_unregister(pws) == 0) { fail(PRODREG_UNREGISTER); } total++; /* If y == 1, unregister all instances. */ if (y != 1) { /* * The desired component instance * was found & deregistered. */ break; } } if (pws != NULL) { wsreg_free_component(pws); pws = NULL; } } if (total == 0) fail(PRODREG_NOT_UNREGABLE); if (pqany) wsreg_query_free(pqany); pqany = NULL; } else { if (NULL == pws) { pq = wsreg_query_create(); wsreg_query_set_id(pq, criteria.uuid); if (criteria.mask & FIND_LOCN) wsreg_query_set_location(pq, criteria.location); pws = wsreg_get(pq); found_here = 1; } if (pws) { if (recursive) { rec_unreg(pws, CHILDREN); rec_unreg(pws, DEPENDENCIES); } if (_private_wsreg_unregister(pws) == 0) { fail(PRODREG_UNREGISTER); } } else { fail(PRODREG_NOT_UNREGABLE); } } if (pq) wsreg_query_free(pq); if (found_here) wsreg_free_component(pws); }
/* Test geometry update operation. */ void BasicUpdateTests::geometry_update () { if (CreateSchemaOnly()) return; try { mConnection = ArcSDETests::GetConnection (); mConnection->SetConnectionString (ArcSDETestConfig::ConnStringMetadcovSingleDb()); mConnection->Open (); // Clean up previous tests: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); FdoPtr<FdoIInsert> insert = (FdoIInsert*)mConnection->CreateCommand (FdoCommandType_Insert); insert->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); // misnomer, it's not a feature class FdoPtr<FdoPropertyValueCollection> values = insert->GetPropertyValues (); FdoPtr<FdoValueExpression> expression = (FdoValueExpression*)FdoExpression::Parse (Data[0]->mPropertyData[0]); FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (Data[0]->mPropertyName, expression); values->Add (value); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5010.282 5011.717, 5011 5012, 5013 5012, 5010.282 5011.717))')"); FdoPtr<FdoPropertyValue> geometry = FdoPropertyValue::Create ((FdoString*)GetGeomPropName(), expression); values->Add (geometry); FdoPtr<FdoIFeatureReader> reader = insert->Execute (); int id; while (reader->ReadNext ()) id = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); value = values->GetItem (Data[0]->mPropertyName); expression = (FdoValueExpression*)FdoExpression::Parse (L"'John Smith'"); value->SetValue (expression); value = values->GetItem ((FdoString*)GetGeomPropName()); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5000.919 5000.277, 5005 5000, 5005 5005, 5000.919 5000.277))')"); value->SetValue (expression); reader = insert->Execute (); int id2; while (reader->ReadNext ()) id2 = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); value = values->GetItem (Data[0]->mPropertyName); expression = (FdoValueExpression*)FdoExpression::Parse (L"'Mott the Hoople'"); value->SetValue (expression); value = values->GetItem ((FdoString*)GetGeomPropName()); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5014.262 5000.018, 5015 5005, 5016 5010, 5014.262 5000.018))')"); value->SetValue (expression); reader = insert->Execute (); int id3; while (reader->ReadNext ()) id3 = reader->GetInt32 ((FdoString*)GetIdPropName()); reader->Close(); // update it FdoPtr<FdoIUpdate> update = (FdoIUpdate*)mConnection->CreateCommand (FdoCommandType_Update); update->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); FdoPtr<FdoPropertyValueCollection> propertyValues = update->GetPropertyValues(); wchar_t filter[1024]; FdoCommonOSUtil::swprintf(filter, ELEMENTS(filter), L"%ls = %d", (FdoString*)GetIdPropName(), id); FdoPtr<FdoFilter> fdoFilter = FdoFilter::Parse (filter); update->SetFilter (fdoFilter); values = update->GetPropertyValues (); expression = (FdoValueExpression*)FdoExpression::Parse (L"GeomFromText('POLYGON XY ((5008.8 5004.7, 5010 5010, 5000 5005, 5008.8 5004.7))')"); value = FdoPropertyValue::Create ((FdoString*)GetGeomPropName(), expression); values->Add (value); if (1 != update->Execute ()) CPPUNIT_FAIL ("update execute failed"); // check by doing a select FdoPtr<FdoISelect> select = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); select->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassComplex()); fdoFilter = FdoFilter::Parse (filter); select->SetFilter (fdoFilter); reader = select->Execute (); while (reader->ReadNext ()) { FdoPtr<FdoGeometryValue> geometry = FDO_SAFE_ADDREF((FdoGeometryValue*)expression.p); FdoPtr<FdoByteArray> fetched = reader->GetGeometry ((FdoString*)GetGeomPropName()); FdoString* referenceText = geometry->ToString(); FdoPtr<FdoGeometryValue> fetchedGeom = FdoGeometryValue::Create (fetched); const wchar_t* fetchedText = fetchedGeom->ToString (); CPPUNIT_ASSERT_MESSAGE ("incorrect geometry value", 0==wcscmp(referenceText, fetchedText)); } reader->Close(); // Clean up after test: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassComplex(), ArcSDETestConfig::ClassNameTestClassComplex(), true); } catch (FdoException* ge) { fail (ge); } }
/* * prodreg_unregister * * This will unregister a component unless (a) the component has * dependencies, in which case the command will fail and an error * will be output UNLESS the 'force' option is set, (b) the * component criteria is ambiguous, in which case the list of * possible matching components is returned. * * pcRoot An alternate root, if non-null. * criteria The component's name, uuid, browse number, etc. * force If this is set, unregister even if the component * has others which depend on it. * recursive Will deregister the component and all children and * nodes which depend upon it. * * Returns: Nothing. * Side effects: Changes the state of the registry, if the user * has permission to do so. */ void prodreg_unregister(const char *pcRoot, Criteria criteria, int force, int recursive) { Wsreg_component **ppws_ambig = NULL; Wsreg_component **ppws_dep = NULL; Wsreg_component *pws = NULL; Wsreg_component **ppws_syspkgs = NULL; int i; int result; if (SPECIALROOT(criteria, ROOT_UUID, ROOT_STR) || SPECIALROOT(criteria, UNCL_UUID, UNCL_STR) || SPECIALROOT(criteria, LOCL_UUID, LOCL_STR) || SPECIALROOT(criteria, ADDL_UUID, ADDL_STR) || SPECIALROOT(criteria, SYSS_UUID, SYSS_STR) || SPECIALROOT(criteria, global_ENTR_UUID, ENTR_STR) || SPECIALROOT(criteria, SYSL_UUID, SYSL_STR)) { fail(PRODREG_UNREGISTER); } if (pcRoot && pcRoot[0] == '\0') pcRoot = NULL; if ((result = wsreg_initialize(WSREG_INIT_NORMAL, pcRoot)) != WSREG_SUCCESS) { debug(DEBUGINFO, "Could not init, reason = %d\n", result); fail(PRODREG_CONVERT_NEEDED_ACCESS); } /* * Check uid is 0, otherwise we may fail later. * This is a work around for the case where sometimes * wsreg_can_access_registry says YES, but the answer is NO. */ if (_private_wsreg_can_access_registry(O_RDWR) == 0) { fail(PRODREG_CANNOT_WRITE); } /* * Handle the simple mnemonic case. */ if (criteria.mask & FIND_UNAME) { unreg(pws, criteria, recursive); return; } pws = prodreg_get_component(pcRoot, criteria, 0, &ppws_ambig, &ppws_syspkgs); if (pws == NULL) fail(PRODREG_NO_SUCH_COMPONENT); db_open(); if (ppws_ambig) { if (force == 0) { (void) printf(PRODREG_AMBIGUOUS_RESULTS); (void) printf("\n"); browse_header(); } for (i = 0; ppws_ambig[i]; i++) { if (force) { unreg(ppws_ambig[i], criteria, 0); } else { Wsreg_component **p = wsreg_get_child_references(ppws_ambig[i]); fill_in_comps(p, ppws_syspkgs); show(NODE, 1, 0, get_bn(ppws_ambig[i]->id), ppws_ambig[i]->id, ppws_ambig[i]->instance, wsreg_get_display_name(ppws_ambig[i], global_lang)); if (p) { wsreg_free_component_array(p); p = NULL; } } } if (ppws_syspkgs) wsreg_free_component_array(ppws_syspkgs); return; } /* This will exit if pws has dependents, unless forced. */ check_dependent(recursive, force, pws, PRODREG_UNREG_WOULD_BREAK); unreg(pws, criteria, recursive); wsreg_free_component(pws); if (ppws_dep) wsreg_free_component_array(ppws_dep); if (ppws_syspkgs) wsreg_free_component_array(ppws_syspkgs); db_close(); }
/* Test insert/update/select on a table that has a UUID column. */ void BasicUpdateTests::update_uuid () { if (CreateSchemaOnly()) return; try { mConnection = ArcSDETests::GetConnection (); mConnection->SetConnectionString (ArcSDETestConfig::ConnStringMetadcov()); mConnection->Open (); // Clean up previous tests: CleanUpClass(mConnection, ArcSDETestConfig::ClassSchemaTestClassUuid(), ArcSDETestConfig::ClassNameTestClassUuid(), true); FdoPtr<FdoIInsert> insert = (FdoIInsert*)mConnection->CreateCommand (FdoCommandType_Insert); insert->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassUuid()); FdoPtr<FdoPropertyValueCollection> values = insert->GetPropertyValues (); FdoPtr<FdoStringValue> expression = FdoStringValue::Create (L"Added"); FdoPtr<FdoPropertyValue> value = FdoPropertyValue::Create (AdjustRdbmsName(L"MYSTRING"), expression); values->Add (value); FdoPtr<FdoIFeatureReader> reader = insert->Execute (); expression->SetString(L"Updated"); reader = insert->Execute (); expression->SetString(L"Deleted"); reader = insert->Execute (); FdoStringP addedUuid1; FdoStringP updatedUuid1; FdoStringP deletedUuid; FdoStringP updatedUuid2 = L"{ABCDEFGH-IJKL-MNOP-QRST-UVWXYZ123456}"; FdoStringP addedUuid3; FdoStringP updatedUuid3; FdoPtr<FdoISelect> select = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); select->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassUuid()); reader = select->Execute (); while (reader->ReadNext ()) { FdoStringP myString = reader->GetString(AdjustRdbmsName(L"MYSTRING")); if ( myString == L"Added" ) addedUuid1 = reader->GetString(AdjustRdbmsName(L"ID")); else if ( myString == L"Updated" ) updatedUuid1 = reader->GetString(AdjustRdbmsName(L"ID")); else if ( myString == L"Deleted" ) deletedUuid = reader->GetString(AdjustRdbmsName(L"ID")); } reader->Close(); FdoPtr<FdoIUpdate> update = (FdoIUpdate*)mConnection->CreateCommand (FdoCommandType_Update); update->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassUuid()); FdoStringP filter = FdoStringP::Format( L"%ls = '%ls'", (FdoString*) AdjustRdbmsName(L"ID"), (FdoString*) updatedUuid1 ); update->SetFilter (FdoPtr<FdoFilter>(FdoFilter::Parse (filter))); values = update->GetPropertyValues (); value = FdoPropertyValue::Create (); value->SetName (AdjustRdbmsName(L"ID")); expression = FdoStringValue::Create (updatedUuid2); value->SetValue (expression); values->Add (value); bool updateFailed = false; // ID is readonly so update should fail. try { update->Execute (); } catch ( FdoException* ex ) { ex->Release(); updateFailed = true; } CPPUNIT_ASSERT ("update failed"); FdoPtr<FdoIDelete> dlte = (FdoIDelete*)mConnection->CreateCommand (FdoCommandType_Delete); dlte->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassUuid()); filter = FdoStringP::Format( L"%ls = '%ls'", (FdoString*) AdjustRdbmsName(L"ID"), (FdoString*) deletedUuid ); dlte->SetFilter (FdoPtr<FdoFilter>(FdoFilter::Parse (filter))); if (1 != dlte->Execute ()) CPPUNIT_FAIL ("delete execute failed"); // check by doing a select select = (FdoISelect*)mConnection->CreateCommand (FdoCommandType_Select); select->SetFeatureClassName (ArcSDETestConfig::QClassNameTestClassUuid()); reader = select->Execute (); int count = 0; while (reader->ReadNext ()) { count++; FdoStringP myString = reader->GetString(AdjustRdbmsName(L"MYSTRING")); if ( myString == L"Added" ) addedUuid3 = reader->GetString(AdjustRdbmsName(L"ID")); else if ( myString == L"Updated" ) updatedUuid3 = reader->GetString(AdjustRdbmsName(L"ID")); } reader->Close(); CPPUNIT_ASSERT( count == 2 ); CPPUNIT_ASSERT( addedUuid3 == addedUuid1 ); CPPUNIT_ASSERT( updatedUuid3 == updatedUuid1 ); CPPUNIT_ASSERT( updatedUuid3 != updatedUuid2 ); mConnection->Close(); } catch (FdoException* ge) { fail (ge); } }
void parse_options (int actual_argc, char *actual_argv[]) { int op; static int n_from_args; argc = actual_argc; argv = actual_argv; while ((op = getopt(argc, argv, sand_optstring)) != -1) { switch (op) { case 'h': display_help_opt = true; break; case 'v': display_version_opt = true; break; case 'u': underground_opt = true; break; case 'g': graphical_opt = true; break; case 'i': printf ("option -i not yet implemented\n"); interactive_opt = true; break; case 'j': if (strcmp(optarg, "time") == 0) { selected_job = TIME_JOB; } else if (strcmp(optarg, "area") == 0) { selected_job = AREA_JOB; } else { cantcontinue ("Option \"-j %s\" not understood.\n", optarg); } break; case 'o': /* expects path for output file */ printf ("option -o not yet implemented\n"); //parse_ofile_arg (optarg); break; case 'f': /* expects path for snapshot file */ snapshot_source_file_arg = optarg; from_snapshot_mode = true; break; case 's': /* expects numerical value for n */ if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/ fprintf (stderr, "ERROR: %s: \"-s %s\" is not an integer argument.\n", __func__, optarg); fail (); } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_SNAPSHOT_DELAY)) { fprintf (stderr, "ERROR: %s: \"-s %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_SNAPSHOT_DELAY); fail (); } set_value_for_snapshot_delay (n_from_args); break; case 't': /* expects numerical value for n */ if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/ fprintf (stderr, "ERROR: %s: \"-t %s\" is not an integer argument.\n", __func__, optarg); fail (); } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_ANIM_LEVEL)) { fprintf (stderr, "ERROR: %s: \"-t %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_ANIM_LEVEL); fail (); } set_value_for_anim_level (n_from_args); break; case 'n': /* expects numerical value for n */ if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/ fprintf (stderr, "ERROR: %s: \"-n %s\" is not an integer argument.\n", __func__, optarg); fail (); } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_HEIGHT)) { fprintf (stderr, "ERROR: %s: \"-n %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_HEIGHT); fail (); } set_value_for_height (n_from_args); break; case 'd': /* expects numerical value for d */ if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/ fprintf (stderr, "ERROR: %s: \"-d %s\" is not an integer argument.\n", __func__, optarg); fail (); } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_DIM)) { fprintf (stderr, "ERROR: %s: \"-d %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_DIM); fail (); } set_value_for_max_dim (n_from_args); break; case '?': default: fprintf (stderr, "ERROR: %s: Cannot parse optional args\n", __func__); display_help (stderr); fail (); } } if (argc > optind) { fprintf (stderr, "ERROR: %s: Does not know about arg \"%s\"\n", __func__, argv[optind]); fail(); } }