static void buildFilenameListFrom(UVector<UString>& vec, const UString& arg) { U_TRACE(5, "Application::buildFilenameListFrom(%p,%.*S)", &vec, U_STRING_TO_TRACE(arg)) uint32_t pos; UTokenizer t(arg); UString dir, filename, filter; while (t.next(filename, ',')) { if (filename.find_first_of("?*", 0, 2) == U_NOT_FOUND) vec.push(filename); else { pos = filename.find_last_of('/'); U_INTERNAL_DUMP("pos = %u", pos) if (pos == U_NOT_FOUND) { UDirWalk dirwalk(0, U_STRING_TO_PARAM(filename)); (void) dirwalk.walk(vec); } else { dir = filename.substr(0U, pos); filter = filename.substr(pos + 1); UDirWalk dirwalk(dir, U_STRING_TO_PARAM(filter)); (void) dirwalk.walk(vec); } } } }
bool UTwilioClient::sendRequest(int method, const char* path, uint32_t path_len, const UString& data) { U_TRACE(0, "UTwilioClient::sendRequest(%d,%.*S,%u,%V)", method, path_len, path, path_len, data.rep) U_INTERNAL_ASSERT_POINTER(client) uri.snprintf(U_CONSTANT_TO_PARAM(TWILIO_API_URL "/" TWILIO_API_VERSION "/Accounts/%.*s/%.*s"), U_STRING_TO_TRACE(client->user), path_len, path); if (method == 4) // DELETE { // send DELETE(4) request to server and get response if (client->sendRequest(4, U_NULLPTR, 0, U_NULLPTR, 0, U_STRING_TO_PARAM(uri))) U_RETURN(true); } else if (method == 3) // PUT { UFile file(data); // upload file to server and get response if (client->upload(uri, file, U_NULLPTR, 0, 3)) U_RETURN(true); } else { UVector<UString> name_value; if (name_value.split(data)) { if (method == 0) // GET { Url url(uri); if (url.setQuery(name_value)) { UString x = url.get(); // send GET(0) request to server and get response if (client->sendRequest(0, U_NULLPTR, 0, U_NULLPTR, 0, U_STRING_TO_PARAM(x))) U_RETURN(true); } } else if (method == 2) // POST { UString body = Url::getQueryBody(name_value); // send POST(2) request to server and get response if (client->sendRequest(2, U_CONSTANT_TO_PARAM("application/x-www-form-urlencoded"), U_STRING_TO_PARAM(body), U_STRING_TO_PARAM(uri))) U_RETURN(true); } } } U_RETURN(false); }
X509_REQ* UPKCS10::readPKCS10(const UString& x, const char* format) { U_TRACE(1, "UPKCS10::readPKCS10(%.*S,%S)", U_STRING_TO_TRACE(x), format) BIO* in; UString tmp = x; X509_REQ* _request = 0; if (format == 0) format = (x.isBinary() ? "DER" : "PEM"); if (U_STREQ(format, "PEM") && U_STRNCMP(x.data(), "-----BEGIN CERTIFICATE REQUEST-----")) { unsigned length = x.size(); UString buffer(length); if (UBase64::decode(x.data(), length, buffer) == false) goto next; tmp = buffer; format = "DER"; } next: in = (BIO*) U_SYSCALL(BIO_new_mem_buf, "%p,%d", U_STRING_TO_PARAM(tmp)); _request = (X509_REQ*) (U_STREQ(format, "PEM") ? U_SYSCALL(PEM_read_bio_X509_REQ, "%p,%p,%p,%p", in, 0, 0, 0) : U_SYSCALL(d2i_X509_REQ_bio, "%p,%p", in, 0)); (void) U_SYSCALL(BIO_free, "%p", in); U_RETURN_POINTER(_request, X509_REQ); }
UXML2Document::UXML2Document(const UString& _data) : data(_data) { U_TRACE_REGISTER_OBJECT(0, UXML2Document, "%V", _data.rep) if (binit == false) init(); // impl_ = (xmlDocPtr) U_SYSCALL(xmlParseMemory, "%p,%d", U_STRING_TO_PARAM(_data)); /* Enum xmlParserOption { XML_PARSE_RECOVER = 1 : recover on errors XML_PARSE_NOENT = 2 : substitute entities XML_PARSE_DTDLOAD = 4 : load the external subset XML_PARSE_DTDATTR = 8 : default DTD attributes XML_PARSE_DTDVALID = 16 : validate with the DTD XML_PARSE_NOERROR = 32 : suppress error reports XML_PARSE_NOWARNING = 64 : suppress warning reports XML_PARSE_PEDANTIC = 128 : pedantic error reporting XML_PARSE_NOBLANKS = 256 : remove blank nodes XML_PARSE_SAX1 = 512 : use the SAX1 interface internally XML_PARSE_XINCLUDE = 1024 : Implement XInclude substitition XML_PARSE_NONET = 2048 : Forbid network access XML_PARSE_NODICT = 4096 : Do not reuse the context dictionnary XML_PARSE_NSCLEAN = 8192 : remove redundant namespaces declarations XML_PARSE_NOCDATA = 16384 : merge CDATA as text nodes XML_PARSE_NOXINCNODE = 32768 : do not generate XINCLUDE START/END nodes XML_PARSE_COMPACT = 65536 : compact small text nodes; no modification of the tree allowed afterwards (will possibly crash if you try to modify tree) XML_PARSE_OLD10 = 131072 : parse using XML-1.0 before update 5 XML_PARSE_NOBASEFIX = 262144 : do not fixup XINCLUDE xml:base uris XML_PARSE_HUGE = 524288 : relax any hardcoded limit from the parser XML_PARSE_OLDSAX = 1048576 : parse using SAX2 interface from before 2.7.0 } */ impl_ = (xmlDocPtr) U_SYSCALL(xmlReadMemory, "%p,%d,%S,%S,%d", U_STRING_TO_PARAM(_data), 0, 0, XML_PARSE_COMPACT); if (impl_ == NULL) { U_ERROR("unable to parse xml document"); } /* * Check the document is of the right kind */ if (getRootNode() == NULL) U_ERROR("empty xml document"); }
UMimePKCS7::UMimePKCS7(const UString& _data) { U_TRACE_REGISTER_OBJECT(0, UMimePKCS7, "%V", _data.rep) // OpenSSL_add_all_algorithms(); // called in ULib::init() BIO* indata; // indata is the signed data if the content is not present in pkcs7 (that is it is detached) BIO* in = (BIO*) BIO_new_mem_buf(U_STRING_TO_PARAM(_data)); // SMIME reader: handle multipart/signed and opaque signing. In multipart case the content is placed // in a memory BIO pointed to by "indata". In opaque this is set to NULL PKCS7* p7 = (PKCS7*) SMIME_read_PKCS7(in, &indata); (void) BIO_free(in); pkcs7.set(p7, indata); content = pkcs7.getContent(&valid_content); }
U_EXPORT ostream& operator<<(ostream& os, const UXMLElement& e) { U_TRACE(0+256, "UXMLElement::operator<<(%p,%p)", &os, &e) // encode the element name os.put('<'); if (e.namespaceName) { os << e.namespaceName; os.put(':'); } os << e.accessorName; os.put(' '); // encode the element's attributes os << e.attributeContainer; // terminate the element declaration os.put(' '); os.put('>'); if (e.value) { (void) os.write(U_CONSTANT_TO_PARAM(" VALUE = ")); char buffer[4096]; uint32_t len = u_escape_encode((const unsigned char*)U_STRING_TO_PARAM(e.value), buffer, sizeof(buffer), false); (void) os.write(buffer, len); } return os; }
void UEscape::encode(const UString& s, UString& buffer, char before, char after) { U_TRACE(0, "UEscape::encode(%.*S,%.*S,%C,%C)", U_STRING_TO_TRACE(s), U_STRING_TO_TRACE(buffer), before, after) U_INTERNAL_ASSERT_DIFFERS(after, '\0') U_ASSERT(buffer.capacity() >= s.size()) uint32_t sz = buffer.size(); char* ptr = buffer.c_pointer(sz); if (before) { ++sz; *ptr++ = before; } uint32_t pos = u_escape_encode((const unsigned char*)U_STRING_TO_PARAM(s), ptr, buffer.space(), true); ptr[pos] = after; buffer.size_adjust(sz + 1 + pos); }
X509* UCertificate::readX509(const UString& x, const char* format) { U_TRACE(1, "UCertificate::readX509(%V,%S)", x.rep, format) BIO* in; X509* _x509 = 0; UString tmp = x; if (format == 0) format = (x.isBinary() ? "DER" : "PEM"); if (strncmp(format, U_CONSTANT_TO_PARAM("PEM")) == 0 && strncmp(x.data(), U_CONSTANT_TO_PARAM("-----BEGIN CERTIFICATE-----")) != 0) { unsigned length = x.size(); UString buffer(length); UBase64::decode(x.data(), length, buffer); if (buffer && u_base64_errors == 0) { tmp = buffer; format = "DER"; } } in = (BIO*) U_SYSCALL(BIO_new_mem_buf, "%p,%d", U_STRING_TO_PARAM(tmp)); _x509 = (X509*) (strncmp(format, U_CONSTANT_TO_PARAM("PEM")) == 0 ? U_SYSCALL(PEM_read_bio_X509, "%p,%p,%p,%p", in, 0, 0, 0) : U_SYSCALL(d2i_X509_bio, "%p,%p", in, 0)); (void) U_SYSCALL(BIO_free, "%p", in); U_RETURN_POINTER(_x509, X509); }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); U_SYSCALL_VOID_NO_PARAM(xmlInitParser); // init libxml LIBXML_TEST_VERSION // manage options num_args = (argc - optind); U_INTERNAL_DUMP("optind = %d num_args = %d", optind, num_args) if (UApplication::isOptions()) cfg_str = opt['c']; // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("XAdES.ini"); // ---------------------------------------------------------------------------------------------------------------------------------- // XAdES - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // DigestAlgorithm md2 | md5 | sha | sha1 | sha224 | sha256 | sha384 | sha512 | mdc2 | ripmed160 // // SigningTime this property contains the time at which the signer claims to have performed the signing process (yes/no) // ClaimedRole this property contains claimed or certified roles assumed by the signer in creating the signature // // this property contains the indication of the purported place where the signer claims to have produced the signature // ------------------------------------------------------------------------------------------------------------------- // ProductionPlaceCity // ProductionPlaceStateOrProvince // ProductionPlacePostalCode // ProductionPlaceCountryName // ------------------------------------------------------------------------------------------------------------------- // // DataObjectFormatMimeType this property identifies the format of a signed data object (when electronic signatures // are not exchanged in a restricted context) to enable the presentation to the verifier or // use by the verifier (text, sound or video) in exactly the same way as intended by the signer // // CAStore // ArchiveTimeStamp the time-stamp token within this property covers the archive validation data // // SignatureTimeStamp the time-stamp token within this property covers the digital signature value element // Schema the pathname XML Schema of XAdES // ---------------------------------------------------------------------------------------------------------------------------------- (void) cfg.open(cfg_str); UString x(U_CAPACITY); UServices::readEOF(STDIN_FILENO, x); if (x.empty()) U_ERROR("cannot read data from <stdin>..."); (void) content.reserve(x.size()); if (UBase64::decode(x, content) == false) U_ERROR("decoding data read failed..."); // manage arguments... schema = ( U_SCHEMA == 0 || *U_SCHEMA == '\0' ? cfg[U_STRING_FROM_CONSTANT("XAdES-L.Schema")] : UString(U_SCHEMA)); if (schema.empty()) U_ERROR("error on XAdES schema: empty"); /* UString str_CApath = cfg[U_STRING_FROM_CONSTANT("XAdES-C.CAStore")], digest_algorithm = cfg[U_STRING_FROM_CONSTANT("XAdES-C.DigestAlgorithm")]; if (str_CApath.empty() || UServices::setupOpenSSLStore(0, str_CApath.c_str()) == false) { U_ERROR("error on setting CA Store: %S", str_CApath.data()); } */ UXML2Schema XAdES_schema(UFile::contentOf(schema)); // --------------------------------------------------------------------------------------------------------------- // check for OOffice or MS-Word document... // --------------------------------------------------------------------------------------------------------------- utility.handlerConfig(cfg); if (utility.checkDocument(content, "XAdES", false)) content = utility.getSigned(); // --------------------------------------------------------------------------------------------------------------- UApplication::exit_value = 1; UXML2Document document(content); if (XAdES_schema.validate(document) == false) { UString content1; if (document.getElement(content1, 0, U_CONSTANT_TO_PARAM(U_TAG_SIGNED_INFO)) && content1.empty() == false) { UXML2Document document1(content1); if (XAdES_schema.validate(document1) == false) { U_ERROR("fail to validate data input based on XAdES schema"); } } } UDSIGContext dsigCtx; UString data, signature; const char* digest_algorithm; if (dsigCtx.verify(document, digest_algorithm, data, signature)) { UString element = document.getElementData(128, U_CONSTANT_TO_PARAM(U_TAG_X509_CERTIFICATE)); if (element.empty() == false) { UString certificate(element.size()); if (UBase64::decode(element, certificate)) { alg = u_dgst_get_algoritm(digest_algorithm); if (alg == -1) U_ERROR("I can't find the digest algorithm for: %s", digest_algorithm); X509* x509 = UCertificate::readX509(certificate, "DER"); u_pkey = UCertificate::getSubjectPublicKey(x509); U_SYSCALL_VOID(X509_free, "%p", x509); if (UServices::verifySignature(alg, data, signature, UString::getStringNull(), 0)) { UApplication::exit_value = 0; # ifdef __MINGW32__ (void) setmode(1, O_BINARY); # endif // std::cout.write(U_STRING_TO_PARAM(certificate)); std::cout.write(U_STRING_TO_PARAM(content)); } U_SYSCALL_VOID(EVP_PKEY_free, "%p", u_pkey); u_pkey = 0; } } } utility.clean(); }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); U_SYSCALL_VOID_NO_PARAM(xmlInitParser); // init libxml LIBXML_TEST_VERSION // manage options num_args = (argc - optind); U_INTERNAL_DUMP("optind = %d num_args = %d", optind, num_args) if (UApplication::isOptions()) cfg_str = opt['c']; // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("XAdES.ini"); // ---------------------------------------------------------------------------------------------------------------------------------- // XAdES signature - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // DigestAlgorithm md2 | md5 | sha | sha1 | sha224 | sha256 | sha384 | sha512 | mdc2 | ripmed160 // // SigningTime this property contains the time at which the signer claims to have performed the signing process (yes/no) // ClaimedRole this property contains claimed or certified roles assumed by the signer in creating the signature // // this property contains the indication of the purported place where the signer claims to have produced the signature // ------------------------------------------------------------------------------------------------------------------- // ProductionPlaceCity // ProductionPlaceStateOrProvince // ProductionPlacePostalCode // ProductionPlaceCountryName // ------------------------------------------------------------------------------------------------------------------- // // DataObjectFormatMimeType this property identifies the format of a signed data object (when electronic signatures // are not exchanged in a restricted context) to enable the presentation to the verifier or // use by the verifier (text, sound or video) in exactly the same way as intended by the signer // // CAStore // ArchiveTimeStamp the time-stamp token within this property covers the archive validation data // // SignatureTimeStamp the time-stamp token within this property covers the digital signature value element // Schema the pathname XML Schema of XAdES // ---------------------------------------------------------------------------------------------------------------------------------- cfg.UFile::setPath(cfg_str); UString x(U_CAPACITY); UServices::readEOF(STDIN_FILENO, x); if (x.empty()) U_ERROR("cannot read data from <stdin>"); content.setBuffer(x.size()); UBase64::decode(x, content); if (content.empty()) U_ERROR("decoding data read failed"); // manage arguments... archive_timestamp = ( U_ARCHIVE_TIMESTAMP == 0 || *U_ARCHIVE_TIMESTAMP == '\0' ? cfg[U_STRING_FROM_CONSTANT("XAdES-L.ArchiveTimeStamp")] : UString(U_ARCHIVE_TIMESTAMP)); if (archive_timestamp.empty()) U_ERROR("error on archive timestamp: empty"); schema = ( U_SCHEMA == 0 || *U_SCHEMA == '\0' ? cfg[U_STRING_FROM_CONSTANT("XAdES-L.Schema")] : UString(U_SCHEMA)); if (schema.empty()) U_ERROR("error on XAdES schema: empty"); UXML2Schema XAdES_schema(UFile::contentOf(schema)); // --------------------------------------------------------------------------------------------------------------- // check for OOffice or MS-Word document... // --------------------------------------------------------------------------------------------------------------- utility.handlerConfig(cfg); if (utility.checkDocument(content, "XAdES-C", false)) content = utility.getSigned(); // --------------------------------------------------------------------------------------------------------------- UXML2Document document(content); if (XAdES_schema.validate(document) == false) U_ERROR("error on input data: not XAdES"); // manage arguments... /* The input to the computation of the digest value MUST be built as follows: 1) Initialize the final octet stream as an empty octet stream. 2) Take all the ds:Reference elements in their order of appearance within ds:SignedInfo referencing whatever the signer wants to sign including the SignedProperties element. Process each one as indicated below: - Process the retrieved ds:Reference element according to the reference processing model of XMLDSIG. - If the result is a XML node set, canonicalize it. If ds:Canonicalization is present, the algorithm indicated by this element is used. If not, the standard canonicalization method specified by XMLDSIG is used. - Concatenate the resulting octets to the final octet stream. */ uint32_t i, n = document.getElement(vec, U_CONSTANT_TO_PARAM("ds:Reference")); for (i = 0; i < n; ++i) { x = vec[i]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); /* 3) Take the following XMLDSIG elements in the order they are listed below, canonicalize each one and concatenate each resulting octet stream to the final octet stream: - The ds:SignedInfo element. - The ds:SignatureValue element. - The ds:KeyInfo element, if present. */ if (document.getElement(vec, U_CONSTANT_TO_PARAM("ds:SignedInfo"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("ds:SignatureValue"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("ds:KeyInfo"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); /* 4) Take the unsigned signature properties that appear before the current xadesv141:ArchiveTimeStamp in the order they appear within the xades:UnsignedSignatureProperties, canonicalize each one and concatenate each resulting octet stream to the final octet stream. While concatenating the following rules apply: - The xades:CertificateValues property MUST be added if it is not already present and the ds:KeyInfo element does not contain the full set of certificates used to validate the electronic signature. - The xades:RevocationValues property MUST be added if it is not already present and the ds:KeyInfo element does not contain the revocation information that has to be shipped with the electronic signature. - The xades:AttrAuthoritiesCertValues property MUST be added if not already present and the following conditions are true: there exist an attribute certificate in the signature AND a number of certificates that have been used in its validation do not appear in CertificateValues. Its content will satisfy with the rules specified in clause 7.6.3. - The xades:AttributeRevocationValues property MUST be added if not already present and there the following conditions are true: there exist an attribute certificate AND some revocation data that have been used in its validation do not appear in RevocationValues. Its content will satisfy with the rules specified in clause 7.6.4. */ if (document.getElement(vec, U_CONSTANT_TO_PARAM("xades:CompleteCertificateRefs"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("xades:CertificateValues"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("xades:CompleteRevocationRefs"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("xades:RevocationValues"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); if (document.getElement(vec, U_CONSTANT_TO_PARAM("xades:SignatureTimeStamp"))) { x = vec[0]; to_digest += UXML2Document::xmlC14N(x); } vec.clear(); /* 5) Take all the ds:Object elements except the one containing xades:QualifyingProperties element. Canonicalize each one and concatenate each resulting octet stream to the final octet stream. If ds:Canonicalization is present, the algorithm indicated by this element is used. If not, the standard canonicalization method specified by XMLDSIG is used. */ n = document.getElement(vec, U_CONSTANT_TO_PARAM("ds:Object")); for (i = 0; i < n; ++i) { x = vec[i]; if (x.find("xades:QualifyingProperties") == U_NOT_FOUND) to_digest += UXML2Document::xmlC14N(x); } u_base64_max_columns = U_OPENSSL_BASE64_MAX_COLUMN; U_line_terminator_len = 2; UString archiveTimeStamp(U_CAPACITY), token = getTimeStampToken(to_digest, archive_timestamp); archiveTimeStamp.snprintf(U_XADES_ARCHIVE_TIMESTAMP_TEMPLATE, U_STRING_TO_TRACE(token)); UString _output = UStringExt::substitute(content, U_CONSTANT_TO_PARAM(" </xades:UnsignedSignatureProperties>"), U_STRING_TO_PARAM(archiveTimeStamp)); // --------------------------------------------------------------------------------------------------------------- // check for OOffice or MS-Word document... // --------------------------------------------------------------------------------------------------------------- utility.outputDocument(_output); // --------------------------------------------------------------------------------------------------------------- }
void USOAPParser::startElement(const XML_Char* name, const XML_Char** attrs) { U_TRACE(0, "USOAPParser::startElement(%S,%p)", name, attrs) U_DUMP_ATTRS(attrs) UXMLAttribute* attribute; UString str((void*)name), namespaceName, accessorName, value; UXMLElement::splitNamespaceAndName(str, namespaceName, accessorName); if (flag_state == 0) { U_INTERNAL_ASSERT(u_rmatch(U_STRING_TO_PARAM(str), U_CONSTANT_TO_PARAM(":Envelope"))) flag_state = 1; } U_DUMP("flag_state = %d ptree = %p ptree->parent() = %p ptree->numChild() = %u ptree->depth() = %u", flag_state, ptree, ptree->parent(), ptree->numChild(), ptree->depth()) current = U_NEW(UXMLElement(str, accessorName, namespaceName)); ptree = ptree->push(current); if (flag_state <= 2) { if (flag_state == 1 && u_rmatch(U_STRING_TO_PARAM(str), U_CONSTANT_TO_PARAM(":Header"))) { header = ptree; flag_state = 2; } else if (u_rmatch(U_STRING_TO_PARAM(str), U_CONSTANT_TO_PARAM(":Body"))) { body = ptree; flag_state = 3; } } U_INTERNAL_DUMP("flag_state = %d", flag_state) while (*attrs) { str.replace(*attrs++); value.replace(*attrs++); UXMLElement::splitNamespaceAndName(str, namespaceName, accessorName); attribute = U_NEW(UXMLAttribute(str, accessorName, namespaceName, value)); current->addAttribute(attribute); // check if anybody has mustUnderstand set to true if (flag_state == 2 && accessorName.equal(U_CONSTANT_TO_PARAM("mustUnderstand"))) { envelope.mustUnderstand = value.equal(U_CONSTANT_TO_PARAM("true")); U_INTERNAL_DUMP("envelope.mustUnderstand = %b", envelope.mustUnderstand) } // set the name of namespace qualified element information (gSOAP) if (flag_state == 1 && namespaceName.equal(U_CONSTANT_TO_PARAM("xmlns")) && accessorName == *UString::str_ns) { envelope.nsName = value; U_INTERNAL_DUMP("envelope.nsName = %V", envelope.nsName.rep) }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); const char* p = argv[optind++]; UString path_of_db_file(p, strlen(p)); if (path_of_db_file.empty()) U_ERROR("missing <path_of_db_file> argument"); URDB x(path_of_db_file, false); if (x.UFile::getSuffix().equal(U_CONSTANT_TO_PARAM("jnl"))) { U_ERROR("you must avoid the jnl suffix, exiting"); } const char* method = argv[optind++]; if (method == 0) U_ERROR("<number_of_command> argument is missing"); if (u__isdigit(*method) == false) U_ERROR("<number_of_command> argument is not numeric"); int op = method[0] - '0'; if (x.open(10 * 1024 * 1024, false, op == 6, true)) // bool open(uint32_t log_size, bool btruncate, bool cdb_brdonly, bool breference) { if (method[1] == 's') x.setShared(0,0); // POSIX shared memory object (interprocess - can be used by unrelated processes) else x.resetReference(); switch (op) { case 1: // get { UString key(argv[optind]), value = x[key]; (void) UFile::writeToTmp(U_STRING_TO_PARAM(value), O_RDWR | O_TRUNC, U_CONSTANT_TO_PARAM(U_FILE_OUTPUT), 0); } break; case 2: // del { # if defined(U_STDCPP_ENABLE) && !defined(HAVE_OLD_IOSTREAM) string input = ""; cout << "Are you sure to want <DELETE> ?\n>"; getline(cin, input); cout << "You entered: " << input << endl << endl; UString key(argv[optind]); UApplication::exit_value = x.remove(key); # endif } break; case 3: // store { UString key(argv[optind]); p = argv[optind++]; UString value(p, strlen(p)); if (value.equal(U_CONSTANT_TO_PARAM(U_DIR_OUTPUT U_FILE_OUTPUT))) { p = U_DIR_OUTPUT U_FILE_OUTPUT; value = UStringExt::trim(UFile::contentOf(UString(p, strlen(p)))); } UApplication::exit_value = x.store(key, value, RDB_REPLACE); } break; case 4: // size, capacity { char buffer[64]; uint32_t sz = x.getCapacity(), n = u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("%u record(s) - capacity: %.2fM (%u bytes)\n"), x.size(), (double)sz / (1024.0 * 1024.0), sz); (void) write(1, buffer, n); } break; case 5: // dump { UString value = x.print(); if (value.empty()) (void) UFile::_unlink(U_DIR_OUTPUT U_FILE_OUTPUT); else (void) UFile::writeToTmp(U_STRING_TO_PARAM(value), O_RDWR | O_TRUNC, U_CONSTANT_TO_PARAM(U_FILE_OUTPUT), 0); } break; case 6: // compact { # if defined(U_STDCPP_ENABLE) && !defined(HAVE_OLD_IOSTREAM) string input = ""; cout << "Are you sure to want <JOURNAL COMPACTION> ?\n>"; getline(cin, input); cout << "You entered: " << input << endl << endl; UApplication::exit_value = (x.compactionJournal() == false); # endif } break; case 7: // reorganize { # if defined(U_STDCPP_ENABLE) && !defined(HAVE_OLD_IOSTREAM) string input = ""; cout << "Are you sure to want <REORGANIZE> ?\n>"; getline(cin, input); cout << "You entered: " << input << endl << endl; UApplication::exit_value = (x.closeReorganize() == false); # endif return; } default: U_ERROR("<number_of_command> argument is not valid"); break; } x.close(false); } }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); UString riga; const char* p = argv[optind++]; UString content1 = UFile::contentOf(UString(p, strlen(p))), content2 = UFile::contentOf(UString(argv[optind])); UVector<UString> vec_entry(10), vec_ap_name(content1), // '\n'), vec_events_log(content2, '\n'); /* vec_ap_name.sort(); riga = vec_ap_name.join('\n'); (void) write(1, U_STRING_TO_PARAM(riga)); U_EXIT(1); */ // ........ // 2013/09/15 03:49:58 op: MAC_AUTH_all, uid: 60:fa:cd:7d:14:06, // ap: [email protected]:5280/wimoMichelangelo-r29587_rspro, // ip: 172.16.69.111, mac: 60:fa:cd:7d:14:06, timeout: 93, traffic: 295, policy: DAILY // ........ UString ap_entry, ap_name, ap_address1, ap_address2; for (uint32_t i = 0, n = vec_events_log.size(); i < n; ++i) { (void) vec_entry.split(vec_events_log[i], ','); ap_entry = vec_entry[2]; uint32_t pos1 = ap_entry.find_first_of('@'), pos2 = ap_entry.find_first_of('/', pos1), pos3 = pos1+1, len3 = pos2-pos1-6; ap_name = ap_entry.substr(pos2+1); ap_address1 = ap_entry.substr(pos3, len3); uint32_t pos = vec_ap_name.findSorted(ap_name, false, true); if (pos == U_NOT_FOUND) { char buffer[4096]; (void) write(2, buffer, u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("NOT FOUND: %.*s %.*s %.*s\n"), U_STRING_TO_TRACE(ap_name), U_STRING_TO_TRACE(ap_address1), U_STRING_TO_TRACE(ap_address2))); } else { ap_address2 = vec_ap_name[pos+1]; if (ap_address1 != ap_address2) { char buffer[4096]; (void) write(2, buffer, u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("ERROR: %.*s %.*s %.*s\n"), U_STRING_TO_TRACE(ap_name), U_STRING_TO_TRACE(ap_address1), U_STRING_TO_TRACE(ap_address2))); } vec_entry.replace(2, ap_entry.replace(pos3, len3, ap_address2)); } riga = vec_entry.join(','); (void) write(1, U_STRING_TO_PARAM(riga)); (void) write(1, U_CONSTANT_TO_PARAM("\n")); vec_entry.clear(); } }
OtpAuthToken::OtpAuthToken(CryptEngine* eng_, const UString& buf) { U_TRACE_REGISTER_OBJECT(5, OtpAuthToken, "%p,%.*S", eng_, U_STRING_TO_TRACE(buf)) eng = eng_; U_STR_RESERVE(buffer, 1000); long pos; unsigned char ptr[1000]; #ifdef U_PROXY_UNIT Base64engine eng1; pos = eng1.decode((unsigned char*)buf.data(), (long)buf.size(), ptr); pos = eng->decrypt(ptr, pos, (unsigned char*)buffer.data()); #else pos = u_base64_decode(U_STRING_TO_PARAM(buf), ptr); # ifdef USE_LIBSSL pos = u_des3_decode(ptr, pos, (unsigned char*)buffer.data()); # endif #endif U_STR_SIZE_ADJUST_FORCE(buffer, pos); migrate = false; valid = (memcmp(buffer.data(), U_CONSTANT_TO_PARAM("TID=")) == 0); timestamp = 0; if (valid) { unsigned n = U_VEC_SPLIT(vec, buffer, "=; \r\n"), i = 10; if (n < i) { valid = false; return; } U_INTERNAL_ASSERT(vec[0] == U_STRING_FROM_CONSTANT("TID")) tid = vec[1]; U_INTERNAL_ASSERT(vec[2] == U_STRING_FROM_CONSTANT("UID")) uid = vec[3]; U_INTERNAL_ASSERT(vec[4] == U_STRING_FROM_CONSTANT("SID")) sid = vec[5]; U_INTERNAL_ASSERT(vec[6] == U_STRING_FROM_CONSTANT("TS")) ts = vec[7]; U_INTERNAL_ASSERT(vec[8] == U_STRING_FROM_CONSTANT("CF")) cf = vec[9]; while (i < n) { if (vec[i] == U_STRING_FROM_CONSTANT("MIGRATE")) { migrate = true; ++i; } else { hp.push_back(vec[i]); ++i; if (i >= n) { valid = false; return; } hp.push_back(vec[i]); ++i; } } # ifdef U_STD_STRING char* _ptr = (char*) ts.c_str(); # else char* _ptr = ts.data(); # endif static struct tm tm; (void) strptime(_ptr, "%Y%m%d%H%M%S", &tm); timestamp = mktime(&tm); } }
#include <ulib/container/vector.h> #include <ulib/container/hash_map.h> bool UHashMap<void*>::stop_call_for_all_entry; uPFpcu UHashMap<void*>::gperf; void UHashMap<void*>::lookup(UStringRep* keyr) { U_TRACE(0, "UHashMap<void*>::lookup(%.*S)", U_STRING_TO_TRACE(*keyr)) U_CHECK_MEMORY U_INTERNAL_ASSERT_MAJOR(_capacity,0) if (gperf) index = gperf(U_STRING_TO_PARAM(*keyr)); else { hash = keyr->hash(ignore_case); index = hash % _capacity; } U_INTERNAL_DUMP("index = %u", index) U_INTERNAL_ASSERT_MINOR(index,_capacity) for (node = table[index]; node; node = node->next) { if (node->key->equal(keyr, ignore_case)) break; }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); // manage options time_t queue_time = 0; UString outpath, result; bool include = false, bstdin = false; if (UApplication::isOptions()) { cfg_str = opt['c']; upload = opt['u']; bstdin = (opt['s'] == U_STRING_FROM_CONSTANT("1")); include = (opt['i'] == U_STRING_FROM_CONSTANT("1")); outpath = opt['o']; queue_time = opt['q'].strtol(); } // manage arg operation UString url(argv[optind++]); // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT(U_SYSCONFDIR "/uclient.cfg"); cfg.UFile::setPath(cfg_str); // ---------------------------------------------------------------------------------------------------------------------------------- // uclient - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // ENABLE_IPV6 flag to indicate use of ipv6 // SERVER host name or ip address for server // PORT port number for the server // // PID_FILE write pid on file indicated // RES_TIMEOUT timeout for response from server // // LOG_FILE locations for file log // // CERT_FILE certificate of client // KEY_FILE private key of client // PASSWORD password for private key of client // CA_FILE locations of trusted CA certificates used in the verification // CA_PATH locations of trusted CA certificates used in the verification // VERIFY_MODE mode of verification (SSL_VERIFY_NONE=0, SSL_VERIFY_PEER=1, SSL_VERIFY_FAIL_IF_NO_PEER_CERT=2, SSL_VERIFY_CLIENT_ONCE=4) // CIPHER_SUITE cipher suite model (Intermediate=0, Modern=1, Old=2) // // FOLLOW_REDIRECTS if yes manage to automatically follow redirects from server // USER if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: user // PASSWORD_AUTH if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: password // ---------------------------------------------------------------------------------------------------------------------------------- client = new UHttpClient<USSLSocket>(&cfg); user = cfg[*UString::str_USER]; password = cfg[U_STRING_FROM_CONSTANT("PASSWORD_AUTH")]; follow_redirects = cfg.readBoolean(U_STRING_FROM_CONSTANT("FOLLOW_REDIRECTS")); client->setFollowRedirects(follow_redirects); client->getResponseHeader()->setIgnoreCase(true); client->setRequestPasswordAuthentication(user, password); UApplication::exit_value = 1; loop: if (upload) { UFile file(upload); if (client->upload(url, file)) UApplication::exit_value = 0; } else if (client->connectServer(url)) { bool ok; if (bstdin == false) ok = client->sendRequest(); else { UString req(U_CAPACITY); UServices::readEOF(STDIN_FILENO, req); if (req.empty()) U_ERROR("cannot read data from <stdin>"); ok = client->sendRequest(req); } if (ok) UApplication::exit_value = 0; } result = (include ? client->getResponse() : client->getContent()); if (result) { # ifdef USE_LIBZ if (UStringExt::isGzip(result)) result = UStringExt::gunzip(result); # endif if (outpath) UFile::writeTo(outpath, result); else (void) write(1, U_STRING_TO_PARAM(result)); } if (queue_time) { UTimeVal to_sleep(queue_time / 10L); U_INTERNAL_ASSERT_EQUALS(UClient_Base::queue_dir, 0) if (result.empty() && UApplication::exit_value == 1) { to_sleep.nanosleep(); goto loop; } UFile file; char mask[100U]; uint32_t i, n, pos; UVector<UString> vec(64); UString req, name, location(U_CAPACITY); uint32_t mask_len = u__snprintf(mask, sizeof(mask), "%.*s.*", U_STRING_TO_TRACE(client->UClient_Base::host_port)); to_sleep.setSecond(to_sleep.getSecond() * 10L); U_MESSAGE("monitoring directory %.*S every %u sec - file mask: %.*S", U_STRING_TO_TRACE(*UString::str_CLIENT_QUEUE_DIR), to_sleep.getSecond(), mask_len, mask); # ifdef USE_LIBSSL client->UClient_Base::setActive(false); # endif UServer_Base::timeoutMS = client->UClient_Base::timeoutMS; UDirWalk dirwalk(*UString::str_CLIENT_QUEUE_DIR, mask, mask_len); while (true) { for (i = 0, n = dirwalk.walk(vec, U_ALPHABETIC_SORT); i < n; ++i) // NB: vec is sorted by string compare... { file.setPath(vec[i]); // ----------------------------------------------------------------------------- // NB: sometime there is a strange behaviour on openWRT (overlayfs) after unlink // ----------------------------------------------------------------------------- // wifi-aaa.comune.fi.it.090513_132007_139 -> (overlay-whiteout) // ----------------------------------------------------------------------------- req = file.getContent(); if (req) { name = file.getName(); pos = name.find_last_of('.'); U_INTERNAL_ASSERT_DIFFERS(pos, U_NOT_FOUND) location.snprintf("http://%.*s", pos, name.data()); (void) location.shrink(); if (client->connectServer(location) == false || client->sendRequest(req) == false) { break; } } (void) file._unlink(); } vec.clear(); if (client->isOpen()) client->close(); to_sleep.nanosleep(); } } client->closeLog(); }
void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); // manage options bool include = false; if (UApplication::isOptions()) { cfg_str = opt['c']; upload = opt['u']; include = (opt['i'] == U_STRING_FROM_CONSTANT("1")); } // manage arg operation UString url(argv[optind++]); // manage file configuration if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT(U_SYSCONFDIR "/uclient.cfg"); // ---------------------------------------------------------------------------------------------------------------------------------- // uclient - configuration parameters // ---------------------------------------------------------------------------------------------------------------------------------- // ENABLE_IPV6 flag to indicate use of ipv6 // SERVER host name or ip address for server // PORT port number for the server // // RES_TIMEOUT timeout for response from server // // LOG_FILE locations for file log // LOG_FILE_SZ memory size for file log // // CERT_FILE certificate of client // KEY_FILE private key of client // PASSWORD password for private key of client // CA_FILE locations of trusted CA certificates used in the verification // CA_PATH locations of trusted CA certificates used in the verification // VERIFY_MODE mode of verification (SSL_VERIFY_NONE=0, SSL_VERIFY_PEER=1, // SSL_VERIFY_FAIL_IF_NO_PEER_CERT=2, // SSL_VERIFY_CLIENT_ONCE=4) // // FOLLOW_REDIRECTS if yes manage to automatically follow redirects from server // USER if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: user // PASSWORD_AUTH if manage to follow redirects, in response to a HTTP_UNAUTHORISED response from the HTTP server: password // ---------------------------------------------------------------------------------------------------------------------------------- (void) cfg.open(cfg_str); client = new UHttpClient<USSLSocket>(&cfg); user = cfg[*UServer_Base::str_USER]; password = cfg[U_STRING_FROM_CONSTANT("PASSWORD_AUTH")]; follow_redirects = cfg.readBoolean(U_STRING_FROM_CONSTANT("FOLLOW_REDIRECTS")); client->setFollowRedirects(follow_redirects); client->setRequestPasswordAuthentication(user, password); client->getResponseHeader()->setIgnoreCase(true); UApplication::exit_value = 1; if (upload.empty() == false) { UFile file(upload); if (client->upload(url, file)) UApplication::exit_value = 0; } else if (client->connectServer(url) && client->sendRequest(result)) { UApplication::exit_value = 0; } result = (include ? client->getResponse() : client->getContent()); if (result.empty() == false) std::cout.write(U_STRING_TO_PARAM(result)); }
*/ } } } } if (country_code) U_RETURN(true); U_RETURN(false); } bool UGeoIPPlugIn::checkCountryForbidden() { U_TRACE_NO_PARAM(0, "UGeoIPPlugIn::checkCountryForbidden()") if (UServices::dosMatchWithOR(country_code, 2, U_STRING_TO_PARAM(*country_forbidden_mask), 0)) { U_SRV_LOG("COUNTRY_FORBIDDEN: request from %s denied by access list", country_name); UHTTP::setForbidden(); U_RETURN(false); } U_RETURN(true); } UGeoIPPlugIn::UGeoIPPlugIn() { U_TRACE_REGISTER_OBJECT(0, UGeoIPPlugIn, "") }