void printans(int c) { fprintf(out,"[%d]",latree[c].l); pkey(c); pkey(latree[c].p); fprintf(out,"\n"); }
void TrustListInserter::CheckForNeededInsert() { Poco::DateTime date; int currentday=date.day(); date-=Poco::Timespan(0,6,0,0,0); // insert trust lists every 6 hours - if 6 hours ago was different day then set to midnight of current day to insert list today ASAP if(currentday!=date.day()) { date.assign(date.year(),date.month(),currentday,0,0,0); } SQLite3DB::Statement st=m_db->Prepare("SELECT LocalIdentityID, PrivateKey FROM tblLocalIdentity WHERE tblLocalIdentity.Active='true' AND PrivateKey IS NOT NULL AND PrivateKey <> '' AND PublishTrustList='true' AND InsertingTrustList='false' AND (LastInsertedTrustList<=? OR LastInsertedTrustList IS NULL);"); st.Bind(0,Poco::DateTimeFormatter::format(date,"%Y-%m-%d %H:%M:%S")); st.Step(); if(st.RowReturned()) { int lid=0; std::string pkey(""); st.ResultInt(0,lid); st.ResultText(1,pkey); StartInsert(lid,pkey); } }
void MoonlightInstance::MakeCert(int32_t callbackId, pp::VarArray args) { pp::VarDictionary ret; ret.Set("callbackId", pp::Var(callbackId)); ret.Set("type", pp::Var("resolve")); pp::VarDictionary retData; CERT_KEY_PAIR certKeyPair = mkcert_generate(); BIO* bio = BIO_new(BIO_s_mem()); PEM_write_bio_X509(bio, certKeyPair.x509); BUF_MEM *mem = NULL; BIO_get_mem_ptr(bio, &mem); std::string cert(mem->data, mem->length); BIO_free(bio); BIO* biokey = BIO_new(BIO_s_mem()); PEM_write_bio_PrivateKey(biokey, certKeyPair.pkey, NULL, NULL, 0, NULL, NULL); BIO_get_mem_ptr(biokey, &mem); std::string pkey(mem->data, mem->length); BIO_free(biokey); retData.Set("privateKey", pkey.c_str()); retData.Set("cert", cert.c_str()); ret.Set("ret", retData); PostMessage(ret); }
static PyObject * Cursor_next(KyotoCursor *self) { std::string key; std::string value; bool succeed = self->m_cursor->get(&key, &value, true); if (succeed) { switch (self->m_type) { case KYOTO_VALUE: { return KyotoDB_load(value, self->m_db->use_pickle); } case KYOTO_ITEMS:{ APR pkey(KyotoDB_load(key, self->m_db->use_pickle)); APR pvalue(KyotoDB_load(value, self->m_db->use_pickle)); return PyTuple_Pack(2, (PyObject *)pkey, (PyObject *)pvalue); } case KYOTO_KEY: default: return KyotoDB_load(key, self->m_db->use_pickle); } } PyErr_SetString(PyExc_StopIteration, ""); return NULL; }
static void dump_bset(struct btree *b, struct bset *i) { struct bkey *k; unsigned j; for (k = i->start; k < end(i); k = bkey_next(k)) { printk(KERN_ERR "block %zu key %zi/%u: %s", index(i, b), (uint64_t *) k - i->d, i->keys, pkey(k)); for (j = 0; j < KEY_PTRS(k); j++) { size_t n = PTR_BUCKET_NR(b->c, k, j); printk(" bucket %zu", n); if (n >= b->c->sb.first_bucket && n < b->c->sb.nbuckets) printk(" prio %i", PTR_BUCKET(b->c, k, j)->prio); } printk(" %s\n", bch_ptr_status(b->c, k)); if (bkey_next(k) < end(i) && skipped_backwards(b, k)) printk(KERN_ERR "Key skipped backwards\n"); } }
__attribute__((visibility("default"))) int openssl_import_keypair(const keymaster0_device_t*, const uint8_t* key, const size_t key_length, uint8_t** key_blob, size_t* key_blob_length) { if (key == NULL) { ALOGW("input key == NULL"); return -1; } else if (key_blob == NULL || key_blob_length == NULL) { ALOGW("output key blob or length == NULL"); return -1; } Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length)); if (pkcs8.get() == NULL) { logOpenSSLError("openssl_import_keypair"); return -1; } /* assign to EVP */ Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get())); if (pkey.get() == NULL) { logOpenSSLError("openssl_import_keypair"); return -1; } if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), key_blob, key_blob_length)) { return -1; } return 0; }
__attribute__((visibility("default"))) int openssl_verify_data( const keymaster0_device_t*, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (signedData == NULL || signature == NULL) { ALOGW("data or signature buffers == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); if (pkey.get() == NULL) { return -1; } int type = EVP_PKEY_type(pkey->type); if (type == EVP_PKEY_DSA) { const keymaster_dsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_dsa_sign_params_t*>(params); return verify_dsa(pkey.get(), const_cast<keymaster_dsa_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else if (type == EVP_PKEY_RSA) { const keymaster_rsa_sign_params_t* sign_params = reinterpret_cast<const keymaster_rsa_sign_params_t*>(params); return verify_rsa(pkey.get(), const_cast<keymaster_rsa_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else if (type == EVP_PKEY_EC) { const keymaster_ec_sign_params_t* sign_params = reinterpret_cast<const keymaster_ec_sign_params_t*>(params); return verify_ec(pkey.get(), const_cast<keymaster_ec_sign_params_t*>(sign_params), signedData, signedDataLength, signature, signatureLength); } else { ALOGW("Unsupported key type %d", type); return -1; } }
TEST_F(avl_tree, DISABLED_check_first_next) { write(); bin_index_t ind(index_dir,4); data_t key; data_t val; unsigned i=0; const char* pi=(const char*)(&i); ASSERT_TRUE(ind.first(key,val)); do { SCOPED_TRACE(i); data_t pkey(pi,pi+4); std::reverse(pkey.begin(),pkey.begin()+2); ASSERT_EQ(key,val); ASSERT_EQ(key,pkey); ++i; } while(ind.next(key,val)); ASSERT_EQ(i,65536); }
static int openssl_import_keypair(const keymaster_device_t* dev, const uint8_t* key, const size_t key_length, uint8_t** key_blob, size_t* key_blob_length) { int response = -1; if (key == NULL) { ALOGW("input key == NULL"); return -1; } else if (key_blob == NULL || key_blob_length == NULL) { ALOGW("output key blob or length == NULL"); return -1; } Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length)); if (pkcs8.get() == NULL) { logOpenSSLError("openssl_import_keypair"); return -1; } /* assign to EVP */ Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get())); if (pkey.get() == NULL) { logOpenSSLError("openssl_import_keypair"); return -1; } OWNERSHIP_TRANSFERRED(pkcs8); if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), key_blob, key_blob_length)) { return -1; } return 0; }
__attribute__((visibility("default"))) int openssl_generate_keypair( const keymaster0_device_t*, const keymaster_keypair_t key_type, const void* key_params, uint8_t** keyBlob, size_t* keyBlobLength) { Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { logOpenSSLError("openssl_generate_keypair"); return -1; } if (key_params == NULL) { ALOGW("key_params == null"); return -1; } else if (key_type == TYPE_DSA) { const keymaster_dsa_keygen_params_t* dsa_params = (const keymaster_dsa_keygen_params_t*)key_params; generate_dsa_keypair(pkey.get(), dsa_params); } else if (key_type == TYPE_EC) { const keymaster_ec_keygen_params_t* ec_params = (const keymaster_ec_keygen_params_t*)key_params; generate_ec_keypair(pkey.get(), ec_params); } else if (key_type == TYPE_RSA) { const keymaster_rsa_keygen_params_t* rsa_params = (const keymaster_rsa_keygen_params_t*)key_params; generate_rsa_keypair(pkey.get(), rsa_params); } else { ALOGW("Unsupported key type %d", key_type); return -1; } if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), keyBlob, keyBlobLength)) { return -1; } return 0; }
static int openssl_sign_data(const keymaster_device_t* dev, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* data, const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) { int result = -1; EVP_MD_CTX ctx; size_t maxSize; if (data == NULL) { ALOGW("input data to sign == NULL"); return -1; } else if (signedData == NULL || signedDataLength == NULL) { ALOGW("output signature buffer == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); if (pkey.get() == NULL) { return -1; } if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) { ALOGW("Cannot handle non-RSA keys yet"); return -1; } keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGW("Cannot handle padding type %d", sign_params->padding_type); return -1; } Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); if (rsa.get() == NULL) { logOpenSSLError("openssl_sign_data"); return -1; } UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength))); if (signedDataPtr.get() == NULL) { logOpenSSLError("openssl_sign_data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get()); if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) { logOpenSSLError("openssl_sign_data"); return -1; } *signedDataLength = dataLength; *signedData = signedDataPtr.release(); return 0; }
static int openssl_verify_data(const keymaster_device_t* dev, const void* params, const uint8_t* keyBlob, const size_t keyBlobLength, const uint8_t* signedData, const size_t signedDataLength, const uint8_t* signature, const size_t signatureLength) { if (signedData == NULL || signature == NULL) { ALOGW("data or signature buffers == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength)); if (pkey.get() == NULL) { return -1; } if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) { ALOGW("Cannot handle non-RSA keys yet"); return -1; } keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params; if (sign_params->digest_type != DIGEST_NONE) { ALOGW("Cannot handle digest type %d", sign_params->digest_type); return -1; } else if (sign_params->padding_type != PADDING_NONE) { ALOGW("Cannot handle padding type %d", sign_params->padding_type); return -1; } else if (signatureLength != signedDataLength) { ALOGW("signed data length must be signature length"); return -1; } Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); if (rsa.get() == NULL) { logOpenSSLError("openssl_verify_data"); return -1; } UniquePtr<uint8_t> dataPtr(reinterpret_cast<uint8_t*>(malloc(signedDataLength))); if (dataPtr.get() == NULL) { logOpenSSLError("openssl_verify_data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get()); if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) { logOpenSSLError("openssl_verify_data"); return -1; } int result = 0; for (size_t i = 0; i < signedDataLength; i++) { result |= tmp[i] ^ signedData[i]; } return result == 0 ? 0 : -1; }
static int openssl_generate_keypair(const keymaster_device_t* dev, const keymaster_keypair_t key_type, const void* key_params, uint8_t** keyBlob, size_t* keyBlobLength) { ssize_t privateLen, publicLen; if (key_type != TYPE_RSA) { ALOGW("Unsupported key type %d", key_type); return -1; } else if (key_params == NULL) { ALOGW("key_params == null"); return -1; } keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params; Unique_BIGNUM bn(BN_new()); if (bn.get() == NULL) { logOpenSSLError("openssl_generate_keypair"); return -1; } if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) { logOpenSSLError("openssl_generate_keypair"); return -1; } /* initialize RSA */ Unique_RSA rsa(RSA_new()); if (rsa.get() == NULL) { logOpenSSLError("openssl_generate_keypair"); return -1; } if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) || RSA_check_key(rsa.get()) < 0) { logOpenSSLError("openssl_generate_keypair"); return -1; } /* assign to EVP */ Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { logOpenSSLError("openssl_generate_keypair"); return -1; } if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) { logOpenSSLError("openssl_generate_keypair"); return -1; } OWNERSHIP_TRANSFERRED(rsa); if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) { return -1; } return 0; }
void pb_num_feature::add_feature( const std::string& key, double value, std::vector<std::pair<std::string, double> >& ret_fv) const { scoped_gil lk; pb_object pkey(pb_unicode_from_string(key)); PB_CHECK(pkey, "cannot convert input key to Python object: " << key); pb_object pval(PyFloat_FromDouble(value)); PB_CHECK(pval, "cannot convert input value to Python object for key: " << key); pb_object ret(PyObject_CallMethodObjArgs( ins_.get(), method_.get(), pkey.get(), pval.get(), NULL)); PB_CHECK(ret, name_ << " method cannot be called"); PB_CHECK(PyList_CheckExact(ret.get()), name_ << " method returned non-list type: " << pb_str(ret.get())); size_t size = PyList_Size(ret.get()); for (size_t i = 0; i < size; ++i) { PyObject* tpl = PyList_GetItem(ret.get(), i); PB_CHECK(tpl, "item " << i << " cannot be accessed: " << pb_str(ret.get())); PB_CHECK(PyTuple_CheckExact(tpl), "list must not contain non-tuple: " << pb_str(tpl)); PB_CHECK(PyTuple_Size(tpl) == 2, "tuple length must be 2: " << pb_str(tpl)); PyObject* f_key = PyTuple_GetItem(tpl, 0); PyObject* f_val = PyTuple_GetItem(tpl, 1); PB_CHECK(PyUnicode_CheckExact(f_key), "feature key must be a unicode string: " << pb_str(tpl)); PB_CHECK(PyNumber_Check(f_val), "feature value must be a number: " << pb_str(tpl)); pb_object f_key_enc(PyUnicode_AsUTF8String(f_key)); PB_CHECK(f_key_enc, "feature key cannot be encoded as UTF-8: " << pb_str(tpl)); pb_object f_val_float(PyNumber_Float(f_val)); PB_CHECK(f_val_float, "value cannot be converted as float: " << pb_str(tpl)); ret_fv.push_back(std::make_pair( std::string(PyBytes_AsString(f_key_enc.get())), PyFloat_AsDouble(f_val_float.get()))); } }
void Info_RemoveKey(VStr& s, const VStr& key) { guard(Info_RemoveKey); if (s.IsEmpty()) { return; } if (s.Length() >= MAX_INFO_STRING) { Host_Error("Info_RemoveKey: oversize infostring"); } if (strchr(*key, '\\')) { GCon->Log("Can't use a key with a \\"); return; } int i = 0; while (1) { int start = i; if (s[i] == '\\') i++; int KeyStart = i; while (s[i] != '\\') { if (!s[i]) return; i++; } VStr pkey(s, KeyStart, i - KeyStart); i++; int ValStart = i; while (s[i] != '\\' && s[i]) { i++; } VStr value(s, ValStart, i - ValStart); if (!key.Cmp(pkey)) { s = VStr(s, 0, start) + VStr(s, i, s.Length() - i); // remove this part return; } if (!s[i]) return; } unguard; }
static PyObject * KyotoDB_array(KyotoDB *self, int type) { PyObject *result = PyList_New(self->m_db->count()); Py_ssize_t i = 0; kyotocabinet::BasicDB::Cursor *cursor = self->m_db->cursor(); cursor->jump(); std::string key; std::string value; while (cursor->get(&key, &value, true)) { switch (type) { case 0: { PyObject *pkey = KyotoDB_load(key, self->use_pickle); if (pkey == NULL) goto onerror; PyList_SetItem(result, i++, pkey); break; } case 1: { PyObject *pvalue = KyotoDB_load(value, self->use_pickle); if (pvalue == NULL) goto onerror; PyList_SetItem(result, i++, pvalue); break; } case 2: { APR pkey(KyotoDB_load(key, self->use_pickle)); if (pkey == NULL) goto onerror; APR pvalue(KyotoDB_load(value, self->use_pickle)); if (pvalue == NULL) goto onerror; PyList_SetItem(result, i++, PyTuple_Pack(2, (PyObject *)pkey, (PyObject *)pvalue)); break; } } } delete cursor; return result; onerror: for (Py_ssize_t j = 0; j < i; j++) { PyObject *obj = PyList_GetItem(result, j); Py_DECREF(obj); } delete cursor; return NULL; }
void registrationKeyDialog::sCheckKey() { XTupleProductKey pkey(_key->text()); if (pkey.valid() && pkey.expiration() > QDate::currentDate()) { _select->setEnabled(true); _status->setHtml(tr("Valid key expiring %1").arg(pkey.expiration().toString(Qt::ISODate))); } else { _select->setEnabled(false); _status->setHtml(pkey.valid() ? tr("Expired key") : tr("Invalid key")); } }
static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD *ui_method, void *callback_data) { ALOGV("keystore_loadkey(%p, \"%s\", %p, %p)", e, key_id, ui_method, callback_data); Keystore_Reply reply; if (keystore_cmd(CommandCodes[GET_PUBKEY], &reply, 1, strlen(key_id), key_id) != NO_ERROR) { ALOGV("Cannot get public key for %s", key_id); return NULL; } const unsigned char* tmp = reinterpret_cast<const unsigned char*>(reply.get()); Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, reply.length())); if (pkey.get() == NULL) { ALOGW("Cannot convert pubkey"); return NULL; } switch (EVP_PKEY_type(pkey->type)) { case EVP_PKEY_RSA: { Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get())); if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { ALOGW("Could not set ex_data for loaded RSA key"); return NULL; } RSA_set_method(rsa.get(), &keystore_rsa_meth); RSA_blinding_off(rsa.get()); /* * This should probably be an OpenSSL API, but EVP_PKEY_free calls * ENGINE_finish(), so we need to call ENGINE_init() here. */ ENGINE_init(e); rsa->engine = e; rsa->flags |= RSA_FLAG_EXT_PKEY; break; } default: ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type)); return NULL; } return pkey.release(); }
void GncSqlVendorBackend::load_all (GncSqlBackend* sql_be) { g_return_if_fail (sql_be != NULL); std::string sql("SELECT * FROM " TABLE_NAME); auto stmt = sql_be->create_statement_from_sql(sql); auto result = sql_be->execute_select_statement(stmt); for (auto row : *result) GncVendor* pVendor = load_single_vendor (sql_be, row); std::string pkey(col_table[0]->name()); sql = "SELECT DISTINCT "; sql += pkey + " FROM " TABLE_NAME; gnc_sql_slots_load_for_sql_subquery (sql_be, sql, (BookLookupFn)gnc_vendor_lookup); }
/* static */ Key* Key::ImportKey(const AuthorizationSet& key_description, keymaster_key_format_t key_format, const uint8_t* key_data, size_t key_data_length, const Logger& logger, keymaster_error_t* error) { *error = KM_ERROR_OK; if (key_data == NULL || key_data_length <= 0) { *error = KM_ERROR_INVALID_KEY_BLOB; return NULL; } if (key_format != KM_KEY_FORMAT_PKCS8) { *error = KM_ERROR_UNSUPPORTED_KEY_FORMAT; return NULL; } UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> pkcs8( d2i_PKCS8_PRIV_KEY_INFO(NULL, &key_data, key_data_length)); if (pkcs8.get() == NULL) { *error = KM_ERROR_MEMORY_ALLOCATION_FAILED; return NULL; } UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKCS82PKEY(pkcs8.get())); if (pkey.get() == NULL) { *error = KM_ERROR_INVALID_KEY_BLOB; return NULL; } UniquePtr<Key> key; switch (EVP_PKEY_type(pkey->type)) { case EVP_PKEY_RSA: return RsaKey::ImportKey(key_description, pkey.get(), logger, error); case EVP_PKEY_DSA: return DsaKey::ImportKey(key_description, pkey.get(), logger, error); case EVP_PKEY_EC: return EcdsaKey::ImportKey(key_description, pkey.get(), logger, error); default: *error = KM_ERROR_UNSUPPORTED_ALGORITHM; return NULL; } *error = KM_ERROR_UNIMPLEMENTED; return NULL; }
VStr Info_ValueForKey(const VStr& s, const VStr& key) { guard(Info_ValueForKey); if (s.IsEmpty() || key.IsEmpty()) { return VStr(); } if (s.Length() >= MAX_INFO_STRING) { Host_Error("Info_ValueForKey: oversize infostring"); } int i = 0; if (s[i] == '\\') i++; while (1) { int Start = i; while (s[i] != '\\') { if (!s[i]) return VStr(); i++; } VStr pkey(s, Start, i - Start); i++; Start = i; while (s[i] != '\\' && s[i]) { i++; } if (!key.ICmp(pkey)) return VStr(s, Start, i - Start); if (!s[i]) return VStr(); i++; } unguard; }
__attribute__((visibility("default"))) int openssl_get_keypair_public(const keymaster0_device_t*, const uint8_t* key_blob, const size_t key_blob_length, uint8_t** x509_data, size_t* x509_data_length) { if (x509_data == NULL || x509_data_length == NULL) { ALOGW("output public key buffer == NULL"); return -1; } Unique_EVP_PKEY pkey(unwrap_key(key_blob, key_blob_length)); if (pkey.get() == NULL) { return -1; } int len = i2d_PUBKEY(pkey.get(), NULL); if (len <= 0) { logOpenSSLError("openssl_get_keypair_public"); return -1; } UniquePtr<uint8_t, Malloc_Free> key(static_cast<uint8_t*>(malloc(len))); if (key.get() == NULL) { ALOGE("Could not allocate memory for public key data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get()); if (i2d_PUBKEY(pkey.get(), &tmp) != len) { logOpenSSLError("openssl_get_keypair_public"); return -1; } ALOGV("Length of x509 data is %d", len); *x509_data_length = len; *x509_data = key.release(); return 0; }
bool createKeyPair( ItalcCore::UserRole role, const QString &destDir ) { QString priv = LocalSystem::Path::privateKeyPath( role, destDir ); QString pub = LocalSystem::Path::publicKeyPath( role, destDir ); LogStream() << "ImcCore: creating new key pair in" << priv << "and" << pub; PrivateDSAKey pkey( 1024 ); if( !pkey.isValid() ) { ilog_failed( "key generation" ); return false; } if( !pkey.save( priv ) ) { ilog_failed( "saving private key" ); return false; } if( !PublicDSAKey( pkey ).save( pub ) ) { ilog_failed( "saving public key" ); return false; } printf( "...done, saved key-pair in\n\n%s\n\nand\n\n%s", priv.toUtf8().constData(), pub.toUtf8().constData() ); printf( "\n\n\nFor now the file is only readable by " "root and members of group root (if you\n" "didn't ran this command as non-root).\n" "I suggest changing the ownership of the " "private key so that the file is\nreadable " "by all members of a special group to which " "all users belong who are\nallowed to use " "iTALC.\n\n\n" ); return true; }
int main(int argc, char *argv[]) { XSqlQuery main; Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; QString passwd; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool haveEnhancedAuth= false; bool _enhancedAuth = false; bool havePasswd = false; bool forceWelcomeStub= false; qInstallMsgHandler(xTupleMessageOutput); QApplication app(argc, argv); app.setOrganizationDomain("xTuple.com"); app.setOrganizationName("xTuple"); app.setApplicationName("xTuple"); app.setApplicationVersion(_Version); #if QT_VERSION >= 0x040400 // This is the correct place for this call but on versions less // than 4.4 it causes a crash for an unknown reason so it is // called later on earlier versions. QCoreApplication::addLibraryPath(QString(".")); #endif #ifndef Q_WS_MACX QApplication::setWindowIcon(QIcon(":/images/icon32x32.png")); #endif app.processEvents(); if (argc > 1) { for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth", Qt::CaseInsensitive)) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive)) { haveEnhancedAuth = true; _enhancedAuth = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _enhancedAuth = false; } else if (argument.contains("-forceWelcomeStub", Qt::CaseInsensitive)) forceWelcomeStub = true; } } // Try and load a default translation file and install it // otherwise if we are non-english inform the user that translation are available bool checkLanguage = false; QLocale sysl = QLocale::system(); QTranslator defaultTranslator(&app); if (defaultTranslator.load(translationFile(sysl.name().toLower(), "default"))) app.installTranslator(&defaultTranslator); else if(!xtsettingsValue("LanguageCheckIgnore", false).toBool() && sysl.language() != QLocale::C && sysl.language() != QLocale::English) checkLanguage = translationFile(sysl.name().toLower(), "xTuple").isNull(); if (forceWelcomeStub || checkLanguage) { QTranslator * translator = new QTranslator(&app); if (translator->load(translationFile(sysl.name().toLower(), "welcome/wmsg"))) app.installTranslator(translator); welcomeStub wsdlg; wsdlg.checkBox->setChecked(xtsettingsValue("LanguageCheckIgnore", false).toBool()); wsdlg.exec(); xtsettingsSetValue("LanguageCheckIgnore", wsdlg.checkBox->isChecked()); } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", _Build.arg(__DATE__).arg(__TIME__)); params.append("setSearchPath", true); if (haveUsername) params.append("username", username); if (havePasswd) params.append("password", passwd); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (haveEnhancedAuth) params.append("enhancedAuth", _enhancedAuth); if (_evaluation) params.append("evaluation"); if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) params.append("login"); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if(newdlg.result() != QDialog::Accepted) { if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); __password = newdlg.password(); } } } // TODO: can/should we compose the splash screen on the fly from parts? QList<editionDesc> edition; edition << editionDesc( "Enterprise", ":/images/splashEnterprise.png", true, "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 4" " FROM pkghead" " WHERE pkghead_name IN ('xtmfg', 'xtprjaccnt', 'asset', 'assetdepn');" ) << editionDesc( "Manufacturing", ":/images/splashMfgEdition.png", true, "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 1" " FROM pkghead" " WHERE pkghead_name IN ('xtmfg');" ) << editionDesc( "Distribution", ":/images/splashDistEdition.png", true, "SELECT fetchMetricText('Application') = 'Standard';" ) << editionDesc( "PostBooks", ":/images/splashPostBooks.png", true, "SELECT fetchMetricText('Application') = 'PostBooks';" ) ; XSqlQuery metric; int editionIdx; // we'll use this after the loop for (editionIdx = 0; editionIdx < edition.size(); editionIdx++) { metric.exec(edition[editionIdx].queryString); if (metric.first() && metric.value(0).toBool()) break; } if (editionIdx >= edition.size()) editionIdx = edition.size(); // default to PostBooks _splash->setPixmap(QPixmap(edition[editionIdx].splashResource)); _Name = _Name.arg(edition[editionIdx].editionName); if (edition[editionIdx].shouldCheckLicense) { _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); // PostgreSQL changed the column "procpid" to just "pid" in 9.2.0+ Incident #21852 XSqlQuery checkVersion(QString("select compareversion('9.2.0');")); if(checkVersion.first()) { if(checkVersion.value("compareversion").toInt() > 0) { metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total" " FROM pg_stat_activity, pg_locks" " WHERE((database=datid)" " AND (classid=datid)" " AND (objsubid=2)" " AND (procpid = pg_backend_pid()));"); } else { metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total" " FROM pg_stat_activity, pg_locks" " WHERE((database=datid)" " AND (classid=datid)" " AND (objsubid=2)" " AND (pg_stat_activity.pid = pg_backend_pid()));"); } } int cnt = 50000; int tot = 50000; if(metric.first()) { cnt = metric.value("registered").toInt(); tot = metric.value("total").toInt(); } metric.exec("SELECT packageIsEnabled('drupaluserinfo') AS result;"); bool xtweb = false; if(metric.first()) xtweb = metric.value("result").toBool(); metric.exec("SELECT fetchMetricBool('ForceLicenseLimit') as metric_value;"); bool forceLimit = false; bool forced = false; if(metric.first()) forceLimit = metric.value("metric_value").toBool(); metric.exec("SELECT metric_value" " FROM metric" " WHERE(metric_name = 'RegistrationKey');"); bool checkPass = true; bool checkLock = false; bool expired = false; QString checkPassReason; QString rkey = ""; if(metric.first()) rkey = metric.value("metric_value").toString(); XTupleProductKey pkey(rkey); QString application; metric.exec("SELECT fetchMetricText('Application') as app;"); if(metric.first()) { application = metric.value("app").toString(); } if(pkey.valid() && (pkey.version() == 1 || pkey.version() == 2 || pkey.version() == 3)) { if(pkey.expiration() < QDate::currentDate()) { checkPass = false; checkPassReason = QObject::tr("<p>Your license has expired."); if(!pkey.perpetual()) { int daysTo = pkey.expiration().daysTo(QDate::currentDate()); if(daysTo > 30) { checkLock = true; expired = true; checkPassReason = QObject::tr("<p>Your xTuple license expired over 30 days ago, and this software will no longer function. Please contact xTuple immediately to reinstate your software."); } else checkPassReason = QObject::tr("<p>Attention: Your xTuple license has expired, and in %1 days this software will cease to function. Please make arrangements for immediate payment").arg(30 - daysTo); } else expired = true; } else if(application == "PostBooks" && pkey.users() == 1) { if(pkey.users() < cnt) { checkPass = false; checkPassReason = QObject::tr("<p>Multiple concurrent users of xTuple PostBooks require a license key. Please contact [email protected] to request a free license key for your local installation, or [email protected] to purchase additional users in the xTuple Cloud Service. <p>Thank you."); checkLock = forced = forceLimit; } } else if(pkey.users() != 0 && (pkey.users() < cnt || (!xtweb && (pkey.users() * 2 < tot)))) { checkPass = false; checkPassReason = QObject::tr("<p>You have exceeded the number of allowed concurrent users for your license."); checkLock = forced = forceLimit; } else { int daysTo = QDate::currentDate().daysTo(pkey.expiration()); if(!pkey.perpetual() && daysTo <= 15) { checkPass = false; checkPassReason = QObject::tr("<p>Please note: your xTuple license will expire in %1 days. You should already have received your renewal invoice; please contact xTuple at your earliest convenience.").arg(daysTo); } } } else { checkPass = false; checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid."); } if(!checkPass) { _splash->hide(); if (expired) { registrationKeyDialog newdlg(0, "", TRUE); if(newdlg.exec() == -1) { QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason); return 0; } } else if(checkLock) { QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason); if(!forced) return 0; } else { if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) return 0; } if(forced) checkPassReason.append(" FORCED!"); metric.exec("SELECT current_database() AS db," " fetchMetricText('DatabaseName') AS dbname," " fetchMetricText('remitto_name') AS name;"); QString db = ""; QString dbname = ""; QString name = ""; if(metric.first()) { db = metric.value("db").toString(); dbname = metric.value("dbname").toString(); name = metric.value("name").toString(); } QHttp *http = new QHttp(); QUrl url; url.setPath("/api/regviolation.php"); url.addQueryItem("key", QUrl::toPercentEncoding(rkey)); url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason)); url.addQueryItem("name", QUrl::toPercentEncoding(name)); url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname)); url.addQueryItem("db", QUrl::toPercentEncoding(db)); url.addQueryItem("cnt", QString::number(cnt)); url.addQueryItem("tot", QString::number(tot)); url.addQueryItem("ver", _Version); http->setHost("www.xtuple.org"); http->get(url.toString()); if(forced) return 0; _splash->show(); } } bool disallowMismatch = false; bool shouldCheckForUpdates = false; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'ServerVersion')"); if (!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { int result = 0; metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'DisallowMismatchClientVersion')"); if (metric.first() && (metric.value("metric_value").toString() == "t")) { disallowMismatch = true; } metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'CheckForUpdates')"); if (metric.first()) { shouldCheckForUpdates = (metric.value("metric_value").toString() == "t" ? true : false); } if (shouldCheckForUpdates) { _splash->hide(); checkForUpdates newdlg(0,"", TRUE); result = newdlg.exec(); if (result == QDialog::Rejected) { return 0; } } else if (!shouldCheckForUpdates && disallowMismatch) { _splash->hide(); result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. The system has been configured to disallow " "access in this case.<p>Please contact your systems " "administrator.").arg(_Version), QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default ); return 0; } else { _splash->hide(); result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. If you continue some or all functionality may " "not work properly or at all. You may also cause other " "problems on the database.<p>Do you want to continue " "anyway?").arg(_Version), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if (result != QMessageBox::Yes) { return 0; } else { _splash->show(); } } } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=getEffectiveXtUser())" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "qt"; files << "xTuple"; files << "openrpt"; files << "reports"; XSqlQuery pkglist("SELECT pkghead_name" " FROM pkghead" " WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) files << pkglist.value("pkghead_name").toString(); } if (files.size() > 0) { QStringList notfound; QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { if (DEBUG) qDebug("looking for %s", (*fit).toAscii().data()); if (translator->load(translationFile(langext, *fit))) { app.installTranslator(translator); qDebug("installed %s", (*fit).toAscii().data()); translator = new QTranslator(&app); } else { notfound << *fit; } } if (! notfound.isEmpty() && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(notfound.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::NoError) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) { keyname = "xTuple.key"; keytogether = keypath + keyname; QFile kn(keytogether); if(!kn.exists()) keyname = "OpenMFG.key"; } keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.trimmed(); } } omfgThis = 0; omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->username(), omfgThis->workspace()); // START code for updating the locale settings if they haven't been already XSqlQuery lc; lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';"); lc.first(); if(lc.value(0).toInt() == 0) { lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');"); lc.exec("SELECT locale_id from locale;"); while(lc.next()) { ParameterList params; params.append("mode","edit"); params.append("locale_id", lc.value(0)); sysLocale lcdlg; lcdlg.set(params); lcdlg.sSave(); } } // END code for updating locale settings QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows())); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->setAttribute(Qt::WA_DeleteOnClose); omfgThis->show(); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { ScriptToolbox sb(0); QWidget* newdlg = sb.openWindow("woTimeClock"); if(newdlg) { XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg); if(mw) { ParameterList params; params.append("captive"); mw->set(params); } newdlg->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); newdlg->show(); } else {
// When a record is read, check if it is a duplicate or // store for future checking. void Dedup_LowMem::checkDups(SamRecord& record, uint32_t recordCount) { // Only inside this method if the record is mapped. // Get the key for this record. static DupKey key; key.initKey(record, getLibraryID(record)); int flag = record.getFlag(); bool recordPaired = SamFlag::isPaired(flag) && SamFlag::isMateMapped(flag); int sumBaseQual = getBaseQuality(record); int32_t chromID = record.getReferenceID(); int32_t mateChromID = record.getMateReferenceID(); // If we are one-chrom and the mate is not on the same chromosome, // mark it as not paired. if(myOneChrom && (chromID != mateChromID)) { recordPaired = false; } // Look in the fragment map to see if an entry for this key exists. FragmentMapInsertReturn ireturn = myFragmentMap.insert(std::make_pair(key, FragData())); FragData* fragData = &(ireturn.first->second); // Enter the new record in the fragData if (any of the below): // 1) there is no previous entry for this key (ireturn.second == true) // or // 2) the previous entry is not paired // AND // a) the new record is paired // or // b) the new record has higher quality if((ireturn.second == true) || ((fragData->paired == false) && (recordPaired || (sumBaseQual > fragData->sumBaseQual)))) { // Check if this is a new key. if(ireturn.second == true) { // New entry, so build the recalibration table now. if(myDoRecab) { myRecab.processReadBuildTable(record); } } else if(fragData->paired == false) { // There was a previous record and it is not paired, // so mark it as a duplicate. // Duplicate checking/marking for pairs is handled below. handleDuplicate(fragData->recordIndex); } // Store this record for later duplicate checking. fragData->sumBaseQual = sumBaseQual; fragData->recordIndex = recordCount; fragData->paired = recordPaired; } else { // Leave the old record in fragData. // If the new record is not paired, handle it as a duplicate. if(recordPaired == false) { // This record is a duplicate, so mark it and release it. handleDuplicate(recordCount); } } // Only paired processing is left, so return if not paired. if(recordPaired == false) { // Not paired, no more operations required, so return. return; } // This is a paired record, so check for its mate. uint64_t readPos = SamHelper::combineChromPos(chromID, record.get0BasedPosition()); uint64_t matePos = SamHelper::combineChromPos(mateChromID, record.get0BasedMatePosition()); int mateIndex = -1; MateData* mateData = NULL; // Check to see if the mate is prior to this record. if(matePos <= readPos) { // The mate map is stored by the mate position, so look for this // record's position. // The mate should be in the mate map, so find it. std::pair<MateMap::iterator,MateMap::iterator> matches = myMateMap.equal_range(readPos); // Loop through the elements that matched the pos looking for the mate. for(MateMap::iterator iter = matches.first; iter != matches.second; iter++) { if(strcmp((*iter).second.readName.c_str(), record.getReadName()) == 0) { // Found the match. mateData = &((*iter).second); // Update the quality and track the mate record and index. sumBaseQual += mateData->sumBaseQual; mateIndex = mateData->recordIndex; // Remove the entry from the map. myMateMap.erase(iter); break; } } } if(mateData == NULL) { if(matePos >= readPos) { // Haven't gotten to the mate yet, so store this record. MateMap::iterator mateIter = myMateMap.insert(std::make_pair(matePos, MateData())); mateIter->second.sumBaseQual = sumBaseQual; mateIter->second.recordIndex = recordCount; mateIter->second.key.copy(key); mateIter->second.readName = record.getReadName(); } else { // Passed the mate, but it was not found. handleMissingMate(record.getReferenceID(), record.getMateReferenceID()); } return; } // Make the paired key. PairedKey pkey(key, mateData->key); // Check to see if this pair is a duplicate. PairedMapInsertReturn pairedReturn = myPairedMap.insert(std::make_pair(pkey,PairedData())); PairedData* storedPair = &(pairedReturn.first->second); // Get the index for "record 1" - the one with the earlier coordinate. int record1Index = getFirstIndex(key, recordCount, mateData->key, mateIndex); // Check if we have already found a duplicate pair. // If there is no duplicate found, there is nothing more to do. if(pairedReturn.second == false) { // Duplicate found. bool keepStored = true; if(pairedReturn.first->second.sumBaseQual < sumBaseQual) { // The new pair has higher quality, so keep that. keepStored = false; } else if(pairedReturn.first->second.sumBaseQual == sumBaseQual) { // Same quality, so keep the one with the earlier record1Index. if(record1Index < storedPair->record1Index) { // The new pair has an earlier lower coordinate read, // so keep that. keepStored = false; } } // Check to see which one should be kept by checking qualities. if(keepStored) { // The old pair had higher quality so mark the new pair as a // duplicate and release them. handleDuplicate(mateIndex); handleDuplicate(recordCount); } else { // The new pair has higher quality, so keep that. // First mark the previous one as duplicates and release them. handleDuplicate(storedPair->record1Index); handleDuplicate(storedPair->record2Index); // Store this pair's information. if(record1Index == mateIndex) { // Mate has a lower coordinate, so make mate // record1. storedPair->sumBaseQual = sumBaseQual; storedPair->record1Index = mateIndex; storedPair->record2Index = recordCount; } else { // This record has a lower coordinate, so make it // record1. storedPair->sumBaseQual = sumBaseQual; storedPair->record1Index = recordCount; storedPair->record2Index = mateIndex; } } } else { // Store this pair's information. storedPair->sumBaseQual = sumBaseQual; if(record1Index == mateIndex) { // Mate has a lower coordinate, so make mate // record1. storedPair->record1Index = mateIndex; storedPair->record2Index = recordCount; } else { // This record has a lower coordinate, so make it // record1. storedPair->record1Index = recordCount; storedPair->record2Index = mateIndex; } } }
// When a record is read, check if it is a duplicate or // store for future checking. void Dedup::checkDups(SamRecord& record, uint32_t recordCount) { // Only inside this method if the record is mapped. // Get the key for this record. static DupKey key; static DupKey mateKey; key.updateKey(record, getLibraryID(record)); int flag = record.getFlag(); bool recordPaired = SamFlag::isPaired(flag) && SamFlag::isMateMapped(flag); int sumBaseQual = getBaseQuality(record); int32_t chromID = record.getReferenceID(); int32_t mateChromID = record.getMateReferenceID(); // If we are one-chrom and the mate is not on the same chromosome, // mark it as not paired. if(myOneChrom && (chromID != mateChromID)) { recordPaired = false; } // Look in the map to see if an entry for this key exists. FragmentMapInsertReturn ireturn = myFragmentMap.insert(std::make_pair(key, ReadData())); ReadData* readData = &(ireturn.first->second); // Mark this record's data in the fragment record if this is the first // entry or if it is a duplicate and the old record is not paired and // the new record is paired or the has a higher quality. if((ireturn.second == true) || ((readData->paired == false) && (recordPaired || (sumBaseQual > readData->sumBaseQual)))) { // If there was a previous record, mark it duplicate and release // the old record if(ireturn.second == false) { // Mark the old record as a DUPLICATE! handleDuplicate(readData->recordIndex, readData->recordPtr); } // Store this record for later duplicate checking. readData->sumBaseQual = sumBaseQual; readData->recordIndex = recordCount; readData->paired = recordPaired; if(recordPaired) { readData->recordPtr = NULL; } else { readData->recordPtr = &record; } } else { // The old record is not a duplicate so the new record is // a duplicate if it is not paired. if(recordPaired == false) { // This record is a duplicate, so mark it and release it. handleDuplicate(recordCount, &record); } } // Only paired processing is left, so return if not paired. if(recordPaired == false) { // Not paired, no more operations required, so return. return; } // This is a paired record, so check for its mate. uint64_t readPos = SamHelper::combineChromPos(chromID, record.get0BasedPosition()); uint64_t matePos = SamHelper::combineChromPos(mateChromID, record.get0BasedMatePosition()); SamRecord* mateRecord = NULL; int mateIndex = 0; // Check to see if the mate is prior to this record. if(matePos <= readPos) { // The mate map is stored by the mate position, so look for this // record's position. // The mate should be in the mate map, so find it. std::pair<MateMap::iterator,MateMap::iterator> matches = myMateMap.equal_range(readPos); // Loop through the elements that matched the pos looking for the mate. for(MateMap::iterator iter = matches.first; iter != matches.second; iter++) { if(strcmp((*iter).second.recordPtr->getReadName(), record.getReadName()) == 0) { // Found the match. ReadData* mateData = &((*iter).second); // Update the quality and track the mate record and index. sumBaseQual += mateData->sumBaseQual; mateIndex = mateData->recordIndex; mateRecord = mateData->recordPtr; // Remove the entry from the map. myMateMap.erase(iter); break; } } } if((mateRecord == NULL) && (matePos >= readPos)) { // Haven't gotten to the mate yet, so store this record. MateMap::iterator mateIter = myMateMap.insert(std::make_pair(matePos, ReadData())); mateIter->second.sumBaseQual = sumBaseQual; mateIter->second.recordPtr = &record; mateIter->second.recordIndex = recordCount; // No more processing for this record is necessary. return; } if(mateRecord == NULL) { // Passed the mate, but it was not found. handleMissingMate(&record); return; } // Make the paired key. mateKey.updateKey(*mateRecord, getLibraryID(*mateRecord)); PairedKey pkey(key, mateKey); // Check to see if this pair is a duplicate. PairedMapInsertReturn pairedReturn = myPairedMap.insert(std::make_pair(pkey,PairedData())); PairedData* storedPair = &(pairedReturn.first->second); // Get the index for "record 1" - the one with the earlier coordinate. int record1Index = getFirstIndex(key, recordCount, mateKey, mateIndex); // Check if we have already found a duplicate pair. // If there is no duplicate found, there is nothing more to do. if(pairedReturn.second == false) { // Duplicate found. bool keepStored = true; if(pairedReturn.first->second.sumBaseQual < sumBaseQual) { // The new pair has higher quality, so keep that. keepStored = false; } else if(pairedReturn.first->second.sumBaseQual == sumBaseQual) { // Same quality, so keep the one with the earlier record1Index. if(record1Index < storedPair->record1Index) { // The new pair has an earlier lower coordinate read, // so keep that. keepStored = false; } } // Check to see which one should be kept by checking qualities. if(keepStored) { // The old pair had higher quality so mark the new pair as a // duplicate and release them. handleDuplicate(mateIndex, mateRecord); handleDuplicate(recordCount, &record); } else { // The new pair has higher quality, so keep that. // First mark the previous one as duplicates and release them. handleDuplicate(storedPair->record1Index, storedPair->record1Ptr); handleDuplicate(storedPair->record2Index, storedPair->record2Ptr); // Store this pair's information. if(record1Index == mateIndex) { // Mate has a lower coordinate, so make mate // record1. storedPair->sumBaseQual = sumBaseQual; storedPair->record1Ptr = mateRecord; storedPair->record2Ptr = &record; storedPair->record1Index = mateIndex; storedPair->record2Index = recordCount; } else { // This record has a lower coordinate, so make it // record1. storedPair->sumBaseQual = sumBaseQual; storedPair->record1Ptr = &record; storedPair->record2Ptr = mateRecord; storedPair->record1Index = recordCount; storedPair->record2Index = mateIndex; } } } else { // Store this pair's information. storedPair->sumBaseQual = sumBaseQual; if(record1Index == mateIndex) { // Mate has a lower coordinate, so make mate // record1. storedPair->record1Ptr = mateRecord; storedPair->record2Ptr = &record; storedPair->record1Index = mateIndex; storedPair->record2Index = recordCount; } else { // This record has a lower coordinate, so make it // record1. storedPair->record1Ptr = &record; storedPair->record2Ptr = mateRecord; storedPair->record1Index = recordCount; storedPair->record2Index = mateIndex; } } }
bool avjackif::async_register_new_user(std::string user_name, boost::asio::yield_context yield_context) { // 先发 client_hello if( m_shared_key.empty()) async_client_hello(yield_context); auto digest = EVP_sha1(); // 先生成 RSA 密钥 _rsa.reset(RSA_generate_key(2048, 65537, 0, 0), RSA_free); // 然后生成 CSR boost::shared_ptr<X509_REQ> csr(X509_REQ_new(), X509_REQ_free); boost::shared_ptr<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free); EVP_PKEY_set1_RSA(pkey.get(), _rsa.get()); // 添加证书申请信息 auto subj =X509_REQ_get_subject_name(csr.get()); /* X509_NAME_add_entry_by_NID(subj, NID_countryName, "CN"); X509_NAME_add_entry_by_NID(subj, NID_stateOrProvinceName, "Shanghai"); X509_NAME_add_entry_by_NID(subj, NID_localityName, "Shanghai"); X509_NAME_add_entry_by_NID(subj, NID_organizationName, "avplayer"); X509_NAME_add_entry_by_NID(subj, NID_organizationalUnitName, "sales"); */ X509_NAME_add_entry_by_NID(subj, NID_commonName, user_name); // X509_NAME_add_entry_by_NID(subj, NID_pkcs9_emailAddress, "test-client"); X509_REQ_set_pubkey(csr.get(), pkey.get()); // 签出 CSR X509_REQ_sign(csr.get(), pkey.get(), digest); unsigned char * out = NULL; auto csr_out_len = i2d_X509_REQ(csr.get(), &out); std::string csrout((char*)out, csr_out_len); OPENSSL_free(out); out = NULL; auto rsa_key_out_len = i2d_RSA_PUBKEY(_rsa.get(), &out); std::string rsa_key((char*)out, rsa_key_out_len); OPENSSL_free(out); PEM_write_X509_REQ(stderr, csr.get()); // 然后发送 注册信息 proto::user_register user_register; user_register.set_user_name(user_name); user_register.set_rsa_pubkey(rsa_key); user_register.set_csr(csrout); boost::asio::async_write(*m_sock, boost::asio::buffer(av_router::encode(user_register)), yield_context); // 读取应答 std::unique_ptr<proto::user_register_result> user_register_result((proto::user_register_result*)async_read_protobuf_message(*m_sock, yield_context)); return user_register_result->result() == proto::user_register_result::REGISTER_SUCCEED; }
static int qcom_km_get_keypair_public(const keymaster_device* dev, const uint8_t* keyBlob, const size_t keyBlobLength, uint8_t** x509_data, size_t* x509_data_length) { struct qcom_km_key_blob * keyblob_ptr = (struct qcom_km_key_blob *)keyBlob; if (x509_data == NULL || x509_data_length == NULL) { ALOGE("Output public key buffer == NULL"); return -1; } if (keyBlob == NULL) { ALOGE("Supplied key blob was NULL"); return -1; } // Should be large enough for keyblob data: if (keyBlobLength < (sizeof(qcom_km_key_blob_t))) { ALOGE("key blob appears to be truncated"); return -1; } if (keyblob_ptr->magic_num != KM_MAGIC_NUM) { ALOGE("Cannot read key; it was not made by this keymaster"); return -1; } if (keyblob_ptr->public_exponent_size == 0 ) { ALOGE("Key blob appears to have incorrect exponent length"); return -1; } if (keyblob_ptr->modulus_size == 0 ) { ALOGE("Key blob appears to have incorrect modulus length"); return -1; } Unique_RSA rsa(RSA_new()); if (rsa.get() == NULL) { ALOGE("Could not allocate RSA structure"); return -1; } rsa->n = BN_bin2bn(reinterpret_cast<const unsigned char*>(keyblob_ptr->modulus), keyblob_ptr->modulus_size, NULL); if (rsa->n == NULL) { ALOGE("Failed to initialize modulus"); return -1; } rsa->e = BN_bin2bn(reinterpret_cast<const unsigned char*>(&keyblob_ptr->public_exponent), keyblob_ptr->public_exponent_size, NULL); if (rsa->e == NULL) { ALOGE("Failed to initialize public exponent"); return -1; } Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { ALOGE("Could not allocate EVP_PKEY structure"); return -1; } if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) { ALOGE("Failed to assign rsa parameters \n"); return -1; } OWNERSHIP_TRANSFERRED(rsa); int len = i2d_PUBKEY(pkey.get(), NULL); if (len <= 0) { ALOGE("Len returned is < 0 len = %d", len); return -1; } UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len))); if (key.get() == NULL) { ALOGE("Could not allocate memory for public key data"); return -1; } unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get()); if (i2d_PUBKEY(pkey.get(), &tmp) != len) { ALOGE("Len 2 returned is < 0 len = %d", len); return -1; } *x509_data_length = len; *x509_data = key.release(); return 0; }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; QString passwd; QString company; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool haveEnhancedAuth= false; bool _enhancedAuth = false; bool haveRequireSSL = false; bool _requireSSL = false; bool havePasswd = false; bool cloudOption = false; bool haveCloud = false; qInstallMsgHandler(xTupleMessageOutput); QApplication app(argc, argv); #if QT_VERSION >= 0x040400 // This is the correct place for this call but on versions less // than 4.4 it causes a crash for an unknown reason so it is // called later on earlier versions. QCoreApplication::addLibraryPath(QString(".")); #endif #ifndef Q_WS_MACX QApplication::setWindowIcon(QIcon(":/images/icon32x32.png")); #endif // Try and load a default translation file and install it QTranslator defaultTranslator(&app); if (defaultTranslator.load("default.qm", app.applicationDirPath())) app.installTranslator(&defaultTranslator); app.processEvents(); if (argc > 1) { for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth", Qt::CaseInsensitive)) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive)) { haveEnhancedAuth = true; _enhancedAuth = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _enhancedAuth = false; } else if (argument.contains("-requireSSL", Qt::CaseInsensitive)) { haveRequireSSL = true; _requireSSL = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _requireSSL = false; } else if (argument.contains("-cloud", Qt::CaseInsensitive)) { haveCloud = true; cloudOption = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) cloudOption = false; } else if (argument.contains("-company=", Qt::CaseInsensitive)) { company = argument.right(argument.length() - 9); } } } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__)); if (haveUsername) params.append("username", username); if (havePasswd) params.append("password", passwd); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (haveEnhancedAuth) params.append("enhancedAuth", _enhancedAuth); if (haveRequireSSL) params.append("requireSSL", _requireSSL); if (_evaluation) params.append("evaluation"); if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) params.append("login"); if (haveCloud) params.append("cloud", cloudOption); if (!company.isEmpty()) params.append("company", company); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if(newdlg.result() != QDialog::Accepted) { if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); __password = newdlg.password(); company = newdlg.company(); cloudOption = newdlg.useCloud(); } } } XSqlQuery metric; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'Application')" ); if(!metric.first() || (metric.value("metric_value").toString() == "Standard")) { // check if the xtmfg package is installed metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'"); if(metric.first()) { _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png")); _Name = _Name.arg("Manufacturing"); } else { _splash->setPixmap(QPixmap(":/images/splashStdEdition.png")); _Name = _Name.arg("Standard"); } _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total" " FROM pg_stat_activity, pg_locks" " WHERE((database=datid)" " AND (classid=datid)" " AND (objsubid=2)" " AND (procpid = pg_backend_pid()));"); int cnt = 50000; int tot = 50000; if(metric.first()) { cnt = metric.value("registered").toInt(); tot = metric.value("total").toInt(); } metric.exec("SELECT metric_value" " FROM metric" " WHERE(metric_name = 'RegistrationKey');"); bool checkPass = true; QString checkPassReason; QString rkey = ""; if(metric.first()) rkey = metric.value("metric_value").toString(); XTupleProductKey pkey(rkey); if(pkey.valid() && pkey.version() == 1) { if(pkey.expiration() < QDate::currentDate()) { checkPass = false; checkPassReason = QObject::tr("Your license has expired."); } else if(pkey.users() != 0 && (pkey.users() < cnt || pkey.users() * 2 < tot)) { checkPass = false; checkPassReason = QObject::tr("You have exceeded the number of allowed concurrent users for your license."); } } else { checkPass = false; checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid."); } if(!checkPass) { _splash->hide(); if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) return 0; metric.exec("SELECT current_database() AS db," " fetchMetricText('DatabaseName') AS dbname," " fetchMetricText('remitto_name') AS name;"); QString db = ""; QString dbname = ""; QString name = ""; if(metric.first()) { db = metric.value("db").toString(); dbname = metric.value("dbname").toString(); name = metric.value("name").toString(); } QHttp *http = new QHttp(); QUrl url; url.setPath("/api/regviolation.php"); url.addQueryItem("key", QUrl::toPercentEncoding(rkey)); url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason)); url.addQueryItem("name", QUrl::toPercentEncoding(name)); url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname)); url.addQueryItem("db", QUrl::toPercentEncoding(db)); url.addQueryItem("cnt", QString::number(cnt)); http->setHost("www.xtuple.org"); http->get(url.toString()); _splash->show(); } } else { _splash->setPixmap(QPixmap(":/images/splashPostBooks.png")); _Name = _Name.arg("PostBooks"); } metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'ServerVersion')" ); if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { bool disallowMismatch = false; metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')"); if(metric.first() && (metric.value("metric_value").toString() == "t")) disallowMismatch = true; _splash->hide(); int result; if(disallowMismatch) result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. The system has been configured to disallow " "access in this case.<p>Please contact your systems " "administrator.").arg(_dbVersion), QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default ); else result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. If you continue some or all functionality may " "not work properly or at all. You may also cause other " "problems on the database.<p>Do you want to continue " "anyway?").arg(_dbVersion), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if(result != QMessageBox::Yes) return 0; _splash->show(); } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=CURRENT_USER)" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "xTuple"; files << "openrpt"; files << "reports"; XSqlQuery pkglist("SELECT pkghead_name" " FROM pkghead" " WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) files << pkglist.value("pkghead_name").toString(); } if (files.size() > 0) { QStringList notfound; QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { if (DEBUG) qDebug("looking for %s", (*fit).toAscii().data()); if (translator->load(translationFile(langext, *fit))) { app.installTranslator(translator); qDebug("installed %s", (*fit).toAscii().data()); translator = new QTranslator(&app); } else notfound << *fit; } if (! notfound.isEmpty() && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(notfound.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::NoError) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) { keyname = "xTuple.key"; keytogether = keypath + keyname; QFile kn(keytogether); if(!kn.exists()) keyname = "OpenMFG.key"; } keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.trimmed(); } } omfgThis = 0; omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; omfgThis->_company = company; omfgThis->_useCloud = cloudOption; // qDebug("Encryption Key: %s", key.toAscii().data() ); if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace()); // START code for updating the locale settings if they haven't been already XSqlQuery lc; lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';"); lc.first(); if(lc.value(0).toInt() == 0) { lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');"); lc.exec("SELECT locale_id from locale;"); while(lc.next()) { ParameterList params; params.append("mode","edit"); params.append("locale_id", lc.value(0)); sysLocale lcdlg; lcdlg.set(params); lcdlg.sSave(); } } // END code for updating locale settings QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows())); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->setAttribute(Qt::WA_DeleteOnClose); omfgThis->show(); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { ScriptToolbox sb(0); QWidget* newdlg = sb.openWindow("woTimeClock"); if(newdlg) { XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg); if(mw) { ParameterList params; params.append("captive"); mw->set(params); } newdlg->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); newdlg->show(); } else {
static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) { long publicLen = 0; long privateLen = 0; const uint8_t* p = keyBlob; const uint8_t *const end = keyBlob + keyBlobLength; if (keyBlob == NULL) { ALOGE("supplied key blob was NULL"); return NULL; } // Should be large enough for: // int32 magic, int32 type, int32 pubLen, char* pub, int32 privLen, char* priv if (keyBlobLength < (get_softkey_header_size() + sizeof(int) + sizeof(int) + 1 + sizeof(int) + 1)) { ALOGE("key blob appears to be truncated"); return NULL; } if (!is_softkey(p, keyBlobLength)) { ALOGE("cannot read key; it was not made by this keymaster"); return NULL; } p += get_softkey_header_size(); int type = 0; for (size_t i = 0; i < sizeof(int); i++) { type = (type << 8) | *p++; } Unique_EVP_PKEY pkey(EVP_PKEY_new()); if (pkey.get() == NULL) { logOpenSSLError("unwrap_key"); return NULL; } for (size_t i = 0; i < sizeof(int); i++) { publicLen = (publicLen << 8) | *p++; } if (p + publicLen > end) { ALOGE("public key length encoding error: size=%ld, end=%d", publicLen, end - p); return NULL; } EVP_PKEY* tmp = pkey.get(); d2i_PublicKey(type, &tmp, &p, publicLen); if (end - p < 2) { ALOGE("private key truncated"); return NULL; } for (size_t i = 0; i < sizeof(int); i++) { privateLen = (privateLen << 8) | *p++; } if (p + privateLen > end) { ALOGE("private key length encoding error: size=%ld, end=%d", privateLen, end - p); return NULL; } d2i_PrivateKey(type, &tmp, &p, privateLen); return pkey.release(); }