Example #1
0
   void run(int argc, char* argv[], char* env[])
      {
      U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env)

      Action::run(argc, argv, env);

      // read stdin and scanf

      Action::processInputData(5);

      // --------------------------------------------------------------------------------------------------------------
      // configuration parameters
      // --------------------------------------------------------------------------------------------------------------
      // ARCHIVE_TEMPLATE                    printf form to output request of archive
      // ELECTRONIC_ARCHIVATION_SERVICE_URL  url to do request of archive
      // --------------------------------------------------------------------------------------------------------------

      UString arch_tmpl = UFile::contentOf(cfg[U_STRING_FROM_CONSTANT("ARCHIVE_TEMPLATE")]),
              url       =                  cfg[U_STRING_FROM_CONSTANT("ELECTRONIC_ARCHIVATION_SERVICE_URL")];

      UString body(arch_tmpl.size() + request_decoded.size() + (u__strlen(uid, __PRETTY_FUNCTION__) * 3) + 100U);

      body.snprintf(arch_tmpl.data(), uid, uid, uid, U_STRING_TO_TRACE(request_decoded));

      bool ok = Action::sendHttpPostRequest(url, body, "multipart/form-data; boundary=4MYWPDUi9kH5-ipE_f6CiZXFFn4SaQQOj", "OK") && Action::sendEmail();

      Action::writeToSTDOUT(ok, true);
      }
Example #2
0
   void run(int argc, char* argv[], char* env[])
      {
      U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env)

      Action::run(argc, argv, env);

      // read stdin and scanf

      Action::processInputData(2);

      // --------------------------------------------------------------------------------------------------------------
      // configuration parameters
      // --------------------------------------------------------------------------------------------------------------
      // SUBJECT_TEMPLATE                 scanf form to extract data from mail header Subject:
      // SEARCH_ENGINE_FOLDER_SEARCH_URL  url to do query to search engine
      // --------------------------------------------------------------------------------------------------------------

      UString subj_tmpl = cfg[U_STRING_FROM_CONSTANT("SUBJECT_TEMPLATE")],
              url       = cfg[U_STRING_FROM_CONSTANT("SEARCH_ENGINE_FOLDER_SEARCH_URL")];

      uint32_t subject = U_STRING_FIND(request, 0, "Subject: ");

      if (subject == U_NOT_FOUND) U_ERROR("cannot find mail header subject on input data...");

      // scanf mail header Subject: from request
      // ----------------------------------------------------------------------------------------------------------------------------
      // "Subject: %*[^"]\"%[^"]\",  %*[^"]\"%[^"]\", %*[^"]\"%[^"]\""
      // ----------------------------------------------------------------------------------------------------------------------------
      // Subject: Re: TUnwired processo di registrazione utente residenziale con CPE:
      //              notifica produzione CPE cliente "workflow test", indirizzo installazione "Via Volturno, 12 50100 Firenze (FI)",
      //              UID "37723e2d-d052-4c13-a1e9-134563eb9666"
      // ----------------------------------------------------------------------------------------------------------------------------

      int n = U_SYSCALL(sscanf, "%S,%S,%p,%p,%p,%p", request.c_pointer(subject), subj_tmpl.data(), customer, installation, uid);

      if (n != 3) U_ERROR("scanf error on mail header subject...");

      U_INTERNAL_DUMP("sscanf() customer = %S installation = %S uid = %S", customer, installation, uid)

      // query to Search Engine

      UString body(10U + u__strlen(uid));

      body.snprintf("query=%s", uid);

      bool ok = Action::sendHttpPostRequest(url, body, "application/x-www-form-urlencoded", "1\n");

      Action::writeToSTDOUT(ok, ok);
      }
Example #3
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   USmtpClient smtp;
   UString tmp(argv[1], strlen(argv[1]));

   if (smtp._connectServer(tmp))
      {
      UString rcpt(argv[2], strlen(argv[2]));
#  ifdef USE_LIBSSL
      bool secure = (argc == 4);
#  else
      bool secure = false;
#  endif

      smtp.setSenderAddress(U_STRING_FROM_CONSTANT("< *****@*****.** >"));
      smtp.setRecipientAddress(rcpt);

      cout << (smtp.sendMessage(secure) ? "mail     send"
                                        : "mail NOT send") << '\n';

   // exit(0);
      }
}
Example #4
0
int
U_EXPORT main (int argc, char* argv[], char* env[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   u_init_ulib_hostname();
   u_init_ulib_username();

   ULog y(U_STRING_FROM_CONSTANT("$PWD/test_log.log"), 1024, "tmp");

   y.setPrefix(U_CONSTANT_TO_PARAM(U_SERVER_LOG_PREFIX));

   uint32_t i, n = (argc > 1 ? u_atoi(argv[1]) : 10);

   for (i = 0; i < n; ++i)
      {
      y.log(U_CONSTANT_TO_PARAM("message %6d - %H %U %w"), i+1);

      y.msync();
      }

   cout << "ok" << '\n';
}
Example #5
0
HttpOtpPostLogin::HttpOtpPostLogin(const char* buf, unsigned len, const UString& user_field,
                                   const UString& pin_field, const UString& token_field, const UString& passwd_field,
                                   const UString& cf_field, HttpHeader& header)
{
   U_TRACE(5, "HttpOtpPostLogin::HttpOtpPostLogin(%.*S,%u,%.*S,%.*S,%.*S,%.*S,%p)", len, buf, len,
                     U_STRING_TO_TRACE(user_field), U_STRING_TO_TRACE(pin_field), U_STRING_TO_TRACE(token_field),
                     U_STRING_TO_TRACE(passwd_field), U_STRING_TO_TRACE(cf_field), &header)

   HttpField* f = header.find(U_STRING_FROM_CONSTANT("Content-Type"));

   U_INTERNAL_ASSERT_POINTER(f)

   U_INTERNAL_ASSERT(f->value.find("application/x-www-form-urlencoded") != unsigned(-1))

   buffer.assign(buf, len);

   (void) U_VEC_SPLIT(vec, buffer, "=&"); // "user=stefano+casazza&pin=12345&token=autorizzativo"

   unsigned i = 0;

   while (i < vec.size())
      {
      if (vec[i] == user_field)
         {
         U_STR_RESERVE(user, 64);

         Url::decode(vec[i+1], user);
         }
      else if (vec[i] == pin_field)
         {
         U_STR_RESERVE(pin, 64);

         Url::decode(vec[i+1], pin);
         }
      else if (vec[i] == token_field)
         {
         U_STR_RESERVE(token, 64);

         Url::decode(vec[i+1], token);
         }
      else if (vec[i] == passwd_field)
         {
         U_STR_RESERVE(passwd, 64);

         Url::decode(vec[i+1], passwd);
         }
      else if (vec[i] == cf_field)
         {
         U_STR_RESERVE(cf, 64);

         Url::decode(vec[i+1], cf);
         }

      i += 2;
      }
}
Example #6
0
int main(int argc, char *argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UTwilioClient tc(U_STRING_FROM_CONSTANT("SID"), U_STRING_FROM_CONSTANT("TOKEN"));

   bool ok = tc.getCompletedCalls();

   U_INTERNAL_ASSERT(ok)

   ok = tc.makeCall(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("http://xxxx"));

   U_INTERNAL_ASSERT(ok)

   ok = tc.sendSMS(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("\"Hello, how are you?\""));

   U_INTERNAL_ASSERT(ok)
}
Example #7
0
int U_EXPORT main(int argc, char* argv[])
{
    U_ULIB_INIT(argv);

    U_TRACE(5,"main(%d)",argc)

    UString x, url(argv[1], strlen(argv[1]));

    UHttpClient<USSLSocket> http(0);
    http.setRequestPasswordAuthentication(U_STRING_FROM_CONSTANT("Aladdin"),
                                          U_STRING_FROM_CONSTANT("open sesame"));

    if (http.connectServer(url) &&
            http.sendRequest(x))
    {
        UString content = http.getContent();

        cout.write(content.data(), content.size());
    }
}
Example #8
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   U_ASSERT_EQUALS( UServices::dosMatchWithOR(U_CONSTANT_TO_PARAM("www.sito1.com"), U_CONSTANT_TO_PARAM("SSI|benchmark|www.sito1.com|www.sito2.com"), FNM_INVERT), false)

   UString buffer(2000);

   u_base64_max_columns = 72;

   UBase64::encode(U_CONSTANT_TO_PARAM(TESTOA), buffer);

   U_INTERNAL_DUMP("buffer = %#.*S", U_STRING_TO_TRACE(buffer))

   U_ASSERT( buffer == U_STRING_FROM_CONSTANT(TESTOB) )

   UBase64::decode( U_CONSTANT_TO_PARAM(TESTOB), buffer);

   U_ASSERT( buffer == U_STRING_FROM_CONSTANT(TESTOA) )

   UString cmd, result1, result2;
   int fd_stderr = U_SYSCALL(open, "%S,%d", "err/services.err", O_WRONLY);

   cmd = U_STRING_FROM_CONSTANT("ls test_services.cpp");
   result1 = UCommand::outputCommand(cmd);

// U_ASSERT( result1 == U_STRING_FROM_CONSTANT("test_services.cpp\n") )

   buffer = UServices::getUUID();
   U_INTERNAL_DUMP("buffer = %#.*S", U_STRING_TO_TRACE(buffer))

   cmd = U_STRING_FROM_CONSTANT("cat test_services.cpp");
   result2 = UCommand::outputCommand(cmd, 0, -1, fd_stderr);

   U_ASSERT( result2.empty() == false )

   cout.write(result2.data(), result2.size());
}
Example #9
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UTimeDate data1(31,12,99), data2("31/12/99");

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )
   U_ASSERT( UTimeDate("31/12/1900").getJulian() == 2415385 )
   U_ASSERT( UTimeDate("01/01/1970").getJulian() == 2440588 )

   U_ASSERT( data1 == data2 )
   U_ASSERT( data1.getDayOfWeek() == 5 )           // Venerdi
   U_ASSERT( data2.getDayOfYear() == 365 )

   U_ASSERT( UTimeDate("1/3/00").getDayOfWeek() == 3 ) // Mercoledi
   U_ASSERT( UTimeDate(31,12,00).getDayOfYear() == 366 )

   UTimeDate data3(60,2000);
   UTimeDate data4("29/02/00");

   U_ASSERT( data3 == data4 )
   U_ASSERT( data3.getDayOfYear() == 60 )

   UTimeDate data5(60,1901);
   UTimeDate data6("1/3/1901");

   U_ASSERT( data5 == data6 )

   U_ASSERT( UTimeDate(17, 5, 2002).isValid() == true )  // TRUE   May 17th 2002 is valid
   U_ASSERT( UTimeDate(30, 2, 2002).isValid() == false ) // FALSE  Feb 30th does not exist
   U_ASSERT( UTimeDate(29, 2, 2004).isValid() == true )  // TRUE   2004 is a leap year

   UTimeDate data7(29, 2, 2004);

   UString x = data7.strftime("%Y-%m-%d");

   U_ASSERT( x == U_STRING_FROM_CONSTANT("2004-02-29") )

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )

   cout << "Date: " << data6.strftime("%d/%m/%y") << '\n';

   while (cin >> data6) cout << data6 << '\n';

   U_ASSERT( UTimeDate::getSecondFromTime("19030314104248Z", true, "%4u%2u%2u%2u%2u%2uZ") < u_now->tv_sec )
}
Example #10
0
static void usp_init_fortunes()
{
    U_TRACE(5, "::usp_init_fortunes()")

    psql_fortune  = U_NEW(UOrmSession(U_CONSTANT_TO_PARAM("fortune")));
    pstmt_fortune = U_NEW(UOrmStatement(*psql_fortune, U_CONSTANT_TO_PARAM("SELECT id, message FROM Fortune")));

    if (pstmt_fortune == 0) U_ERROR("usp_init_fortunes(): we cound't connect to db, exiting...");

    pfortune  = U_NEW(Fortune);
    pvfortune = U_NEW(UVector<Fortune*>);
    pmessage  = U_NEW(U_STRING_FROM_CONSTANT("Additional fortune added at request time."));

    pstmt_fortune->into(*pfortune);
}
Example #11
0
   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

      UString cfg_str;

      if (UApplication::isOptions()) cfg_str = opt['c'];

      // manage arg operation

      // manage file configuration

      if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("signer.cfg");

      cfg.UFile::setPath(cfg_str);

      // --------------------------------------------------------------------------------------------------------------
      // configuration parameters
      // --------------------------------------------------------------------------------------------------------------
      // --------------------------------------------------------------------------------------------------------------

      // form_template = cfg[U_STRING_FROM_CONSTANT("TEMPLATE")];

      hinstance = GetModuleHandle(0);

      Window MainWindow;
      //PropSheet MainWindow;

      // Initialize common controls
      InitCommonControls();

      // Init window class lib
      Window::SetAppInstance(hinstance);

      // Create pages

      // Add pages to sheet

      // Create the PropSheet main window
      MainWindow.Create();

      // Clean exit.. save user options.
      }
Example #12
0
static void check_content(const UString& content, const UString& filename)
{
   U_TRACE(5, "check_content(%p,%p)", content.data(), filename.data())

   UString dati = UFile::contentOf(filename);

   if (dati != content)
      {
      UFile save_file;

      if (save_file.creat(U_STRING_FROM_CONSTANT("tmp/content.different")))
         {
         save_file.write(content);

         save_file.close();
         }
      }

   U_ASSERT( dati == content )
}
Example #13
0
   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();
      }
Example #14
0
static int print(UStringRep* key, UStringRep* data)
{
   U_TRACE(5, "::print(%.*S,%.*S)", U_STRING_TO_TRACE(*key), U_STRING_TO_TRACE(*data))

   cout << UString(key) << "->" << UString(data) << endl;

   return 1;
}

static void transaction(URDB& rdb)
{
   U_TRACE(5, "::transaction(%p)", &rdb)

   if (rdb.beginTransaction())
      {
      UString key0  = U_STRING_FROM_CONSTANT("chiave_di_prova0"),
              data0 = U_STRING_FROM_CONSTANT("valore_di_prova0"),
              key1  = U_STRING_FROM_CONSTANT("chiave_di_prova1"),
              data1 = U_STRING_FROM_CONSTANT("valore_di_prova1"),
              key2  = U_STRING_FROM_CONSTANT("chiave_di_prova2"),
              data2 = U_STRING_FROM_CONSTANT("valore_di_prova2"),
              key3  = U_STRING_FROM_CONSTANT("chiave_di_prova3"),
              data3 = U_STRING_FROM_CONSTANT("valore_di_prova3");

      rdb.store(key0, data0, RDB_INSERT);
      U_ASSERT( rdb[key0] == data0 )
      rdb.store(key0, data1, RDB_REPLACE);
      U_ASSERT( rdb[key0] == data1 )

      U_ASSERT( rdb.remove(key0)  == 0 )
      U_ASSERT( rdb[key0].empty() == true )
Example #15
0
int U_EXPORT main(int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5, "main(%d)", argc)

   UString x, url(argv[1], strlen(argv[1]));

   UHttpClient<UTCPSocket> http(0);

#ifndef JOHN
   http.setRequestPasswordAuthentication(U_STRING_FROM_CONSTANT("Aladdin"),
                                         U_STRING_FROM_CONSTANT("open sesame"));

   if (http.connectServer(url) &&
       http.sendRequest())
      {
      UString content = http.getContent();

      cout.write(content.data(), content.size());
      }
#else
   (void) http.setHostPort(url.getHost(), url.getPort());

#  define AB_REQUEST(ver) "GET /usp/benchmarking.usp?name=stefano HTTP/1."#ver"\r\n" \
                          "Host: stefano\r\n" \
                          "User-Agent: ApacheBench/2.3\r\n" \
                          "Accept: */*\r\n" \
                          "\r\n"

/*
#  define HTTP_VER 1
*/
#  define HTTP_VER 0
   x = U_STRING_FROM_CONSTANT(AB_REQUEST(HTTP_VER));

#  if HTTP_VER == 1
   if (http.connect())
      {
      for (uint32_t i = 0 ; i < 100000 && http.sendRequest(x); ++i)
         {
         }
      }
#  else
   for (uint32_t i = 0 ; i < 100000; ++i)
      {
      if (http.connect())
         {
         if (http.sendRequest(x))
            {
            http.close();

            continue;
            }
         }

      break;
      }
#  endif
#endif
}
Example #16
0
                tipology[U_rilevazione_virus] == false) return;

        /*
        -------------------------------------------------------
        si parte dalla fine record <-> "delimitatore..." ':'

        ERRORE 2 (errore=virus)
        ci sono due possibilita':
        if (rilevazione_virus) (obbligatorio)
        if (non_accettazione) (check valore campo)
        -------------------------------------------------------
        */

        bool input        = true;
        int U_field       = U_ricezione;
        bool errore_virus = PEC_report::checkValueField(U_errore, U_STRING_FROM_CONSTANT("virus"));

        if (tipology[U_rilevazione_virus])
        {
            if (errore_virus == false)
            {
                U_WARNING(U_PARSE_ERROR_MESSAGE_UNEXPECTED_VALUE, U_STRING_TO_TRACE(*identifier));
            }

            // from version > 2.0...

            if (getValueField(U_consegna).empty() == false) U_field = U_consegna;

            input = isDomainField(U_field);
        }
        else if (errore_virus)
Example #17
0
    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));
    }
Example #18
0
   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

      UString cfg_str;

      if (UApplication::isOptions()) cfg_str = opt['c'];

      // The "hash seed" is a feature to perturb the results to avoid "algorithmic complexity attacks"
      // ---------------------------------------------------------------------------------------------
      // http://lwn.net/Articles/474365/

      u_seed_hash = u_random(u_now->tv_usec);

      // manage file configuration

      if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT(U_SYSCONFDIR "/userver.cfg");

      // ---------------------------------------------------------------------------------------------------------------------------------------
      // userver - configuration parameters
      // ---------------------------------------------------------------------------------------------------------------------------------------
      // ENABLE_IPV6    flag to indicate use of ipv6
      // SERVER         host name or ip address for the listening socket
      // PORT           port number for the listening socket
      // SOCKET_NAME    file name   for the listening socket
      // IP_ADDRESS     ip address of host for the interface connected to the Internet (autodetected if not specified)
      // ALLOWED_IP     list of comma separated client address for IP-based access control (IPADDR[/MASK])
      //
      // ENABLE_RFC1918_FILTER reject request from private IP to public server address
      // ALLOWED_IP_PRIVATE    list of comma separated client private address for IP-based access control (IPADDR[/MASK]) for public server
      //
      // LISTEN_BACKLOG        max number of ready to be delivered connections to accept()
      // USE_TCP_OPTIMIZATION  flag indicating the use of TCP/IP options to optimize data transmission (TCP_CORK, TCP_DEFER_ACCEPT, TCP_QUICKACK)
      // SET_REALTIME_PRIORITY flag indicating that the preforked processes will be scheduled under the real-time policies SCHED_FIFO
      //
      // PID_FILE       write pid on file indicated
      // WELCOME_MSG    message of welcome to send initially to client
      // RUN_AS_USER    downgrade security to that user account
      // DOCUMENT_ROOT  The directory out of which you will serve your documents
      //
      // LOG_FILE       locations for file log
      // LOG_FILE_SZ    memory size for file log
      // LOG_MSG_SIZE  limit length of print network message to LOG_MSG_SIZE chars (default 128)
      //
      // PLUGIN         list of plugins to load, a flexible way to add specific functionality to the server
      // PLUGIN_DIR     directory of plugins to load
      //
      // REQ_TIMEOUT    timeout for request from client
      // CGI_TIMEOUT    timeout for cgi execution
      //
      // MAX_KEEP_ALIVE Specifies the maximum number of requests that can be served through a Keep-Alive (Persistent) session.
      //                (Value <= 0 will disable Keep-Alive) (default 1020)
      //
      // DH_FILE        DH param
      // CERT_FILE      certificate of server
      // KEY_FILE       private key of server
      // PASSWORD       password for private key of server
      // 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)
      //
      // PREFORK_CHILD  number of child server processes created at startup ( 0 - serialize, no forking
      //                                                                      1 - classic, forking after accept client)
      //                                                                     >1 - pool of process serialize plus monitoring process)
      // ---------------------------------------------------------------------------------------------------------------------------------------

      (void) cfg.open(cfg_str);

      server = new Server(&cfg);

      server->go();
      }
Example #19
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UTimeDate data1(31,12,99), data2("31/12/99");

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )
   U_ASSERT( UTimeDate("31/12/1900").getJulian() == 2415385 )
   U_ASSERT( UTimeDate("01/01/1970").getJulian() == 2440588 )

   U_ASSERT( data1 == data2 )
   U_ASSERT( data1.getDayOfWeek() == 5 ) // Venerdi
   U_ASSERT( data2.getDayOfYear() == 365 )

   U_ASSERT( UTimeDate("1/3/00").getDayOfWeek() == 3 ) // Mercoledi
   U_ASSERT( UTimeDate(31,12,0).getDayOfYear() == 366 )

   UTimeDate data3(60,2000);
   UTimeDate data4("29/02/00");

   U_ASSERT( data3 == data4 )
   U_ASSERT( data3.getDayOfYear() == 60 )

   UTimeDate data5(60,1901);
   UTimeDate data6("1/3/1901");

   U_ASSERT( data5 == data6 )

   U_ASSERT( UTimeDate(17, 5, 2002).isValid() == true )  // TRUE   May 17th 2002 is valid
   U_ASSERT( UTimeDate(30, 2, 2002).isValid() == false ) // FALSE  Feb 30th does not exist
   U_ASSERT( UTimeDate(29, 2, 2004).isValid() == true )  // TRUE   2004 is a leap year

   UTimeDate data7(29, 2, 2004);

   UString x = data7.strftime("%Y-%m-%d");

   U_ASSERT( x == U_STRING_FROM_CONSTANT("2004-02-29") )

   U_ASSERT( UTimeDate("14/09/1752").getJulian() == 2361222 )

   cout << "Date: " << data6.strftime("%d/%m/%y") << '\n';

   while (cin >> data6) cout << data6 << '\n';

   U_ASSERT( UTimeDate::getSecondFromTime("19030314104248Z", true, "%4u%2u%2u%2u%2u%2uZ") < u_now->tv_sec )

   /*
   typedef struct static_date {
      struct timeval _timeval;      // => u_now
      char lock1[1];
      char date1[17+1];             // 18/06/12 18:45:56
      char lock2[1];
      char date2[26+1];             // 04/Jun/2012:18:18:37 +0200
      char lock3[1];
      char date3[6+29+2+12+2+19+1]; // Date: Wed, 20 Jun 2012 11:43:17 GMT\r\nServer: ULib\r\nConnection: close\r\n
   } static_date;
   */

   ULog::static_date log_data;

   (void) u_strftime2(log_data.date1, 17,               "%d/%m/%y %T",    u_now->tv_sec + u_now_adjust);
   (void) u_strftime2(log_data.date2, 26,               "%d/%b/%Y:%T %z", u_now->tv_sec + u_now_adjust);
   (void) u_strftime2(log_data.date3, 6+29+2+12+2+17+2, "Date: %a, %d %b %Y %T GMT\r\nServer: ULib\r\nConnection: close\r\n", u_now->tv_sec);

   U_INTERNAL_DUMP("date1 = %.17S date2 = %.26S date3+6 = %.29S", log_data.date1, log_data.date2, log_data.date3+6)

   /*
   for (int i = 0; i < 360; ++i)
      {
      u_now->tv_sec++;

      UTimeDate::updateTime(log_data.date1   + 12);
      UTimeDate::updateTime(log_data.date2   + 15);
      UTimeDate::updateTime(log_data.date3+6 + 20);

      cout.write(log_data.date1, 17);
      cout.write(" - ", 3);
      cout.write(log_data.date2, 26);
      cout.write(" - ", 3);
      cout.write(log_data.date3+6, 29);
      cout.put('\n');
      }
   */
}
Example #20
0
      U_DELETE(filter_ext)
      }

   if (posting)             U_DELETE(posting)
   if (bad_words)           U_DELETE(bad_words)
   if (suffix_bad_words)    U_DELETE(suffix_bad_words)
   if (suffix_skip_tag_xml) U_DELETE(suffix_skip_tag_xml)
}

void IR::setBadWords()
{
   U_TRACE(5, "IR::setBadWords()")

   if (t == U_NULLPTR) t = new UTokenizer;

   cfg_skip_tag_xml = cfg[U_STRING_FROM_CONSTANT("SKIP_TAG_XML")];

   if (cfg_skip_tag_xml) suffix_skip_tag_xml = new UVector<UString>(cfg_skip_tag_xml);

   cfg_bad_words = cfg[U_STRING_FROM_CONSTANT("BAD_WORDS")];

   if (cfg_bad_words)
      {
      U_NEW_STRING(bad_words, UString(cfg_bad_words)); 

      cfg_bad_words_ext = cfg[U_STRING_FROM_CONSTANT("BAD_WORDS_EXT")];

      if (cfg_bad_words_ext) suffix_bad_words = new UVector<UString>(cfg_bad_words_ext);
      }
}
Example #21
0
   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_ASSERT( num_args == 2 )

      U_ASSERT( opt[(uint32_t)0U] == U_STRING_FROM_CONSTANT("1") )
      U_ASSERT( opt[(uint32_t)1U] == U_STRING_FROM_CONSTANT("pippo") )
      U_ASSERT( opt[(uint32_t)2U] == U_STRING_FROM_CONSTANT("Hello") )
      U_ASSERT( opt[(uint32_t)3U] == U_STRING_FROM_CONSTANT("1") )
      U_ASSERT( opt[(uint32_t)4U] == U_STRING_FROM_CONSTANT("Bucaiolo_a_te") )

      U_ASSERT( opt['a'] == U_STRING_FROM_CONSTANT("1") )
      U_ASSERT( opt['b'] == U_STRING_FROM_CONSTANT("pippo") )
      U_ASSERT( opt['c'] == U_STRING_FROM_CONSTANT("Hello") )

      U_ASSERT( opt[U_STRING_FROM_CONSTANT("option_with_no_short_1")] == U_STRING_FROM_CONSTANT("1") )
      U_ASSERT( opt[U_STRING_FROM_CONSTANT("option_with_no_short_2")] == U_STRING_FROM_CONSTANT("Bucaiolo_a_te") )

      U_ASSERT( strcmp(argv[optind], "argument_1") == 0 )
      ++optind;
      U_ASSERT( strcmp(argv[optind], "argument_2") == 0 )

      u_atexit(reset);

      (void) write(STDOUT_FILENO, U_CONSTANT_TO_PARAM("AutoSending SIGTERM...\n"));
      
#  ifndef DEBUG
      UInterrupt::act.sa_flags   = 0;
      UInterrupt::act.sa_handler = UInterrupt::handlerInterrupt;

      (void) U_SYSCALL(sigaction, "%d,%p,%p", SIGTERM, &UInterrupt::act, 0); // 15
#  endif

      UInterrupt::sendSignal(SIGTERM, u_pid);
      }
Example #22
0
 virtual UString getMethodName() const { return U_STRING_FROM_CONSTANT("add"); }
Example #23
0
   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();
      }
Example #24
0
// action.cpp

#include "action.h"

#include <ulib/mime/multipart.h>
#include <ulib/utility/escape.h>
#include <ulib/utility/services.h>
#include <ulib/utility/xml_escape.h>

bool Action::loadFileConfig(UString& cfg_str)
{
   U_TRACE(5, "Action::loadFileConfig(%.*S)", U_STRING_TO_TRACE(cfg_str))

   if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("action.cfg");

   if (cfg.open(cfg_str))
      {
      // -----------------------------------------------------------------------------------------------
      // configuration parameters
      // -----------------------------------------------------------------------------------------------
      //  REQUEST_TEMPLATE  scanf form to extract data
      // RESPONSE_TEMPLATE printf form to output       response
      //    ERROR_TEMPLATE printf form to output error response
      // -----------------------------------------------------------------------------------------------

      req_tmpl = UFile::contentOf(cfg[U_STRING_FROM_CONSTANT( "REQUEST_TEMPLATE")]);
      res_tmpl = UFile::contentOf(cfg[U_STRING_FROM_CONSTANT("RESPONSE_TEMPLATE")]);
      err_tmpl = UFile::contentOf(cfg[U_STRING_FROM_CONSTANT(   "ERROR_TEMPLATE")]);

      U_RETURN(true);
      }
Example #25
0
   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>");

      (void) document.reserve(x.size());

      UBase64::decode(x, document);

      if (document.empty()) U_ERROR("decoding data read failed");

      // manage arguments...

      if ( U_DATA_URI &&
          *U_DATA_URI == '\0')
         {
         U_ERROR("DATA_URI is mandatory");
         }

      if ( U_X509 &&
          *U_X509 == '\0')
         {
         U_ERROR("X509 is mandatory");
         }

      if ( U_KEY_HANDLE &&
          *U_KEY_HANDLE == '\0')
         {
         U_ERROR("KEY_HANDLE is mandatory");
         }

      UCertificate cert(UString(U_X509));

      if (cert.isValid() == false) U_ERROR("certificate not valid");

      U_INTERNAL_DUMP("U_CA_STORE = %S", U_CA_STORE)

      xades_c = (U_CA_STORE != U_NULLPTR);

      digest_algorithm = getOptionValue(U_DIGEST_ALGORITHM, "DigestAlgorithm");

      alg = u_dgst_get_algoritm(digest_algorithm.c_str());

      if (alg == -1) U_ERROR("I can't find the digest algorithm for: %s", digest_algorithm.data());

      signing_time                       = getOptionValue(U_SIGNING_TIME,                       "SigningTime").strtol();
      claimed_role                       = getOptionValue(U_CLAIMED_ROLE,                       "ClaimedRole");
      production_place_city              = getOptionValue(U_PRODUCTION_PLACE_CITY,              "ProductionPlaceCity");
      production_place_state_or_province = getOptionValue(U_PRODUCTION_PLACE_STATE_OR_PROVINCE, "ProductionPlaceStateOrProvince");
      production_place_postal_code       = getOptionValue(U_PRODUCTION_PLACE_POSTAL_CODE,       "ProductionPlacePostalCode");
      production_place_country_name      = getOptionValue(U_PRODUCTION_PLACE_COUNTRY_NAME,      "ProductionPlaceCountryName");
      data_object_format_mimetype        = getOptionValue("",                                   "DataObjectFormatMimeType");

      if (xades_c == false) num_ca = 0;
      else
         {
         // XAdES-C
         // -------------------------------------------------------------------------------------------------------------  
         str_CApath          = getOptionValue(U_CA_STORE,            "CAStore");
         signature_timestamp = getOptionValue(U_SIGNATURE_TIMESTAMP, "SignatureTimeStamp");

         if (str_CApath.empty() ||
             UServices::setupOpenSSLStore(U_NULLPTR, str_CApath.c_str()) == false)
            {
            U_ERROR("error on setting CA Store: %S", str_CApath.data());
            }

         num_ca = cert.getSignerCertificates(vec_ca, U_NULLPTR, 0);

         if (UCertificate::verify_result == false)
            {
            UServices::setVerifyStatus();

            U_ERROR("error on verifying the certificate: %.*s", u_buffer_len, u_buffer);
            }
         // -------------------------------------------------------------------------------------------------------------  
         }

      u_base64_max_columns  = U_OPENSSL_BASE64_MAX_COLUMN;
      U_line_terminator_len = 2;

      UString modulus          = cert.getModulus(),
              exponent         = cert.getExponent();
              X509IssuerName   = cert.getIssuerForLDAP(),
              X509SubjectName  = cert.getSubjectForLDAP(),
              X509Certificate  = cert.getEncoded("DER");
              X509SerialNumber = cert.getSerialNumber();

      UString X509CertificateValue(U_CAPACITY), KeyInfo(U_CAPACITY);

      UBase64::encode(X509Certificate, X509CertificateValue);

      u_base64_max_columns = 0;

      KeyInfo.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_KEYINFO_TEMPLATE),
                       U_STRING_TO_TRACE(modulus),
                       U_STRING_TO_TRACE(exponent),
                       U_STRING_TO_TRACE(X509SubjectName),
                       U_STRING_TO_TRACE(X509IssuerName),
                       X509SerialNumber,
                       U_STRING_TO_TRACE(X509CertificateValue));

      UString ObjectDigestValue(200U),
              Reference(U_CAPACITY), dataObjectFormat(U_CAPACITY),
              XMLDSIGReference(U_CAPACITY), XMLDSIGReferenceC14N(U_CAPACITY);

      // ---------------------------------------------------------------------------------------------------------------
      // check for OOffice or MS-Word document...
      // ---------------------------------------------------------------------------------------------------------------
      utility.handlerConfig(cfg);

      (void) utility.checkDocument(document, U_DATA_URI, true);
      // ---------------------------------------------------------------------------------------------------------------

      for (uint32_t i = 0, n = utility.vdocument.size(); i < n; ++i)
         {
         uri       = utility.vuri[i];
         to_digest = utility.vdocument[i];

         // ---------------------------------------------------------------------------------------------------------------
         // 2. Compute the message digest of the text, m = Hash(C).
         // ---------------------------------------------------------------------------------------------------------------
         ObjectDigestValue.setEmpty();

         UServices::generateDigest(alg, 0, to_digest, ObjectDigestValue, true);
         // ---------------------------------------------------------------------------------------------------------------

         Reference.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_REFERENCE_TEMPLATE), uri.c_str(),
                            U_STRING_TO_TRACE(digest_algorithm),
                            U_STRING_TO_TRACE(ObjectDigestValue));

         XMLDSIGReference     +=                        Reference;
         XMLDSIGReferenceC14N += UXML2Document::xmlC14N(Reference);

         if (data_object_format_mimetype.empty() == false)
            {
            dataObjectFormat.snprintf(U_CONSTANT_TO_PARAM(U_XADES_DATA_OBJECT_FORMAT_TEMPLATE), uri.c_str(), U_STRING_TO_TRACE(data_object_format_mimetype));

            DataObjectFormat += dataObjectFormat;
            }
         }

      setXAdESReference(); // XAdES management

      // ---------------------------------------------------------------------------------------------------------------
      // 3. Encapsulate the message digest in an XML <SignedInfo> element, SI, in canonicalized form.
      // ---------------------------------------------------------------------------------------------------------------
      UString SignedInfo(U_CONSTANT_SIZE(U_XMLDSIG_SIGNED_INFO_TEMPLATE) + XMLDSIGReference.size() + XAdESReference.size());

      SignedInfo.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_SIGNED_INFO_TEMPLATE),
                          U_STRING_TO_TRACE(digest_algorithm),
                          U_STRING_TO_TRACE(XMLDSIGReference),
                          U_STRING_TO_TRACE(XAdESReference));

      UString to_sign = UXML2Document::xmlC14N(SignedInfo);
      // ---------------------------------------------------------------------------------------------------------------

      // ---------------------------------------------------------------------------------------------------------------
      // 4. Compute the RSA signatureValue of the canonicalized <SignedInfo> element, SV = RsaSign(Ks, SI).
      // ---------------------------------------------------------------------------------------------------------------
      UString SignatureValue(U_CAPACITY), signatureTimeStamp(U_CAPACITY), archiveTimeStamp(U_CAPACITY);

      u_base64_max_columns = U_OPENSSL_BASE64_MAX_COLUMN;

      ENGINE* e;

#  ifdef _MSWINDOWS_
      e = UServices::loadEngine("HCSP", ENGINE_METHOD_RSA);
      x = U_KEY_HANDLE;
#  else
      e = U_NULLPTR;
      x = UFile::contentOf(UString(U_KEY_HANDLE));

      if (x.empty() ||
          (u_pkey = UServices::loadKey(x, U_NULLPTR, true, U_NULLPTR, e)) == U_NULLPTR)
         {
         U_ERROR("I can't load the private key: %S", U_KEY_HANDLE);
         }

#     ifdef HAVE_OPENSSL_98
      if (cert.matchPrivateKey(u_pkey) == false) U_ERROR("the private key doesn't matches the public key of the certificate");
#     endif

      x.clear();
#  endif

      UString sign = UServices::getSignatureValue(alg, to_sign, x, UString::getStringNull(), true, e);

      u_base64_max_columns = 0;

      SignatureValue.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_SIGNATURE_VALUE_TEMPLATE), U_STRING_TO_TRACE(sign));

      if (signature_timestamp.empty() == false)
         {
         to_digest = UXML2Document::xmlC14N(SignatureValue);

         UString token = getTimeStampToken(to_digest, signature_timestamp);

         signatureTimeStamp.snprintf(U_CONSTANT_TO_PARAM(U_XADES_SIGNATURE_TIMESTAMP_TEMPLATE), U_STRING_TO_TRACE(token));
         }

      // XAdES-C
      // -------------------------------------------------------------------------------------------------------------  
      if (xades_c) setXAdESUnsignedSignatureProperties();
      // -------------------------------------------------------------------------------------------------------------  

      (void) XAdESObject.reserve(U_CONSTANT_SIZE(U_XADES_TEMPLATE) +
                          signedProperties.size() +
                          unsignedSignatureProperties.size() +
                          archiveTimeStamp.size() +
                          signatureTimeStamp.size());

      XAdESObject.snprintf(U_CONSTANT_TO_PARAM(U_XADES_TEMPLATE),
                           U_STRING_TO_TRACE(signedProperties),
                           U_STRING_TO_TRACE(unsignedSignatureProperties),
                           U_STRING_TO_TRACE(archiveTimeStamp),
                           U_STRING_TO_TRACE(signatureTimeStamp));
      // ---------------------------------------------------------------------------------------------------------------

      // ---------------------------------------------------------------------------------------------------------------
      // 5. Compose the final XML document including the signatureValue, this time in non-canonicalized form.
      // ---------------------------------------------------------------------------------------------------------------
      UString output(U_CONSTANT_SIZE(U_XMLDSIG_TEMPLATE) + 8192U + 
                     SignedInfo.size() + SignatureValue.size() + XAdESObject.size());

      if (utility.ooffice)
         {
         OpenDocumentStart = U_STRING_FROM_CONSTANT("<document-signatures xmlns=\"urn:oasis:names:tc:opendocument:xmlns:digitalsignature:1.0\">");
         OpenDocumentEnd   = U_STRING_FROM_CONSTANT("</document-signatures>");
         }

      output.snprintf(U_CONSTANT_TO_PARAM(U_XMLDSIG_TEMPLATE),
                        U_STRING_TO_TRACE(OpenDocumentStart),
                        U_STRING_TO_TRACE(SignedInfo),
                        U_STRING_TO_TRACE(SignatureValue),
                        U_STRING_TO_TRACE(KeyInfo),
                        U_STRING_TO_TRACE(XAdESObject),
                        U_STRING_TO_TRACE(OpenDocumentEnd));
      // ---------------------------------------------------------------------------------------------------------------

      // ---------------------------------------------------------------------------------------------------------------
      // check for OOffice or MS-Word document...
      // ---------------------------------------------------------------------------------------------------------------
      utility.outputDocument(output);
      // ---------------------------------------------------------------------------------------------------------------
      }
Example #26
0
   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

      UString cfg_str;

      if (UApplication::isOptions()) cfg_str = opt['c'];

      // manage file configuration

      if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT(U_SYSCONFDIR "/userver.cfg");

      cfg.UFile::setPath(cfg_str);

      // ---------------------------------------------------------------------------------------------------------------------------------------
      // userver - configuration parameters
      // ---------------------------------------------------------------------------------------------------------------------------------------
      // ENABLE_IPV6    flag to indicate use of ipv6
      // SERVER         host name or ip address for the listening socket
      // PORT           port number for the listening socket
      // SOCKET_NAME    file name   for the listening socket
      // IP_ADDRESS     ip address of host for the interface connected to the Internet (autodetected if not specified)
      // ALLOWED_IP     list of comma separated client address for IP-based access control (IPADDR[/MASK])
      //
      // ENABLE_RFC1918_FILTER reject request from private IP to public server address
      // ALLOWED_IP_PRIVATE    list of comma separated client private address for IP-based access control (IPADDR[/MASK]) for public server
      //
      // LISTEN_BACKLOG             max number of ready to be delivered connections to accept()
      // SET_REALTIME_PRIORITY      flag indicating that the preforked processes will be scheduled under the real-time policies SCHED_FIFO
      // CLIENT_FOR_PARALLELIZATION min number of clients to active parallelization 
      //
      // PID_FILE       write pid on file indicated
      // WELCOME_MSG    message of welcome to send initially to client
      // RUN_AS_USER    downgrade security to that user account
      // DOCUMENT_ROOT  The directory out of which you will serve your documents
      //
      // LOG_FILE       locations for file log
      // LOG_FILE_SZ    memory size for file log
      // LOG_MSG_SIZE  limit length of print network message to LOG_MSG_SIZE chars (default 128)
      //
      // PLUGIN         list of plugins to load, a flexible way to add specific functionality to the server
      // PLUGIN_DIR     directory of plugins to load
      //
      // REQ_TIMEOUT    timeout for request from client
      // TCP_KEEP_ALIVE Specifies to active the TCP keepalive implementation in the linux kernel.
      // MAX_KEEP_ALIVE Specifies the maximum number of requests that can be served through a Keep-Alive (Persistent) session.
      //                (Value <= 0 will disable Keep-Alive)
      //
      // DH_FILE        DH param
      // CERT_FILE      certificate of server
      // KEY_FILE       private key of server
      // PASSWORD       password for private key of server
      // 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)
      //
      // PREFORK_CHILD  number of child server processes created at startup ( 0 - serialize, no forking
      //                                                                      1 - classic, forking after accept client)
      //                                                                     >1 - pool of process serialize plus monitoring process)
      // ---------------------------------------------------------------------------------------------------------------------------------------

#  ifdef U_SSL_SOCKET
      UServer_Base::bssl = true;
#  elif defined(U_UNIX_SOCKET)
      UServer_Base::bipc = true;
#  endif
      server = new Server(&cfg);

      server->run();
      }
Example #27
0
   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);
      // ---------------------------------------------------------------------------------------------------------------
      }
Example #28
0
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);
      }
}
Example #29
0
int
U_EXPORT main (int argc, char* argv[])
{
   U_ULIB_INIT(argv);

   U_TRACE(5,"main(%d)",argc)

   UString value, path, domain, port, not_found;

   HttpCookie c1(U_CONSTANT_TO_PARAM("Cookie"), U_CONSTANT_TO_PARAM("Name=value")),
              c2(U_CONSTANT_TO_PARAM("Cookie"), U_CONSTANT_TO_PARAM(COOKIE_2)),
              c5(U_CONSTANT_TO_PARAM("Cookie"), U_CONSTANT_TO_PARAM(COOKIE_5));

   U_ASSERT( c5.find(U_STRING_FROM_CONSTANT("otptoken"), value, path, domain, port)  == true )
   U_ASSERT( value   == U_STRING_FROM_CONSTANT("pluto") )

   U_ASSERT( c1.count(U_STRING_FROM_CONSTANT("Name"))    == 1 )
   U_ASSERT( c2.count(U_STRING_FROM_CONSTANT("$Domain")) == 2 )

   U_ASSERT( c1.find(U_STRING_FROM_CONSTANT("Name"), value, path, domain, port)  == true )
   U_ASSERT( value   == U_STRING_FROM_CONSTANT("value") )
   U_ASSERT( path    == not_found )
   U_ASSERT( domain  == not_found )
   U_ASSERT( port    == not_found )

   U_ASSERT( c2.find(U_STRING_FROM_CONSTANT("NameB"), value, path, domain, port)  == true )
   U_ASSERT( value   == U_STRING_FROM_CONSTANT("ValueB") )
   U_ASSERT( domain  == U_STRING_FROM_CONSTANT("domain1") )
   U_ASSERT( port    == not_found )

#ifdef SERGIO
   U_ASSERT( path    == U_STRING_FROM_CONSTANT("/") )
#else
   U_ASSERT( path    == U_STRING_FROM_CONSTANT("\"/\"") )
#endif

   U_ASSERT( c2.del(U_STRING_FROM_CONSTANT("NameB")) == true )

   value = path = domain = port = not_found;

   U_ASSERT( c2.find(U_STRING_FROM_CONSTANT("Name"), value, path, domain, port)  == false )
   U_ASSERT( value   == not_found )
   U_ASSERT( path    == not_found )
   U_ASSERT( domain  == not_found )
   U_ASSERT( port    == not_found )

   U_ASSERT( c2.find(U_STRING_FROM_CONSTANT("NameC"), value, path, domain, port)  == true )
   U_ASSERT( value   == U_STRING_FROM_CONSTANT("ValueC") )
   U_ASSERT( path    == U_STRING_FROM_CONSTANT("domain1") )

#ifdef SERGIO
   U_ASSERT( port    == U_STRING_FROM_CONSTANT("123") )
   U_ASSERT( domain  == U_STRING_FROM_CONSTANT("/") )
#else
   U_ASSERT( port    == U_STRING_FROM_CONSTANT("\"123\"") )
   U_ASSERT( domain  == U_STRING_FROM_CONSTANT("\"/\"") )
#endif

   HttpSetCookie s1(U_CONSTANT_TO_PARAM("Set-Cookie"),  U_CONSTANT_TO_PARAM(SETCOOKIE_1)),
                 s2(U_CONSTANT_TO_PARAM("Set-Cookie2"), U_CONSTANT_TO_PARAM(SETCOOKIE_2));

   U_ASSERT( s1.count(U_STRING_FROM_CONSTANT("Domain"))  == 2 )
   U_ASSERT( s2.count(U_STRING_FROM_CONSTANT("Port"))    == 1 )

   HttpCookie c3(U_CONSTANT_TO_PARAM("Cookie"), U_CONSTANT_TO_PARAM(COOKIE_AUTH) );

   U_ASSERT( c3.count(U_STRING_FROM_CONSTANT("AUTHTOKEN")) == 1 )

   value = path = domain = port = not_found;

   U_ASSERT( c3.find(U_STRING_FROM_CONSTANT("AUTHTOKEN"), value, path, domain, port)  == true )

   U_ASSERT( path    == not_found )
   U_ASSERT( domain  == not_found )
   U_ASSERT( port    == not_found )

   value.erase(value.size()-1, 1);
   value.erase(0, 1);

#ifdef U_PROXY_UNIT
   DES3engine eng("pippo");
   OtpAuthToken a(&eng, value);
#else
   u_des3_key("pippo");
   OtpAuthToken a(0, value);
#endif

   U_ASSERT( a.tid     == U_STRING_FROM_CONSTANT("Current_Server_ID") )
   U_ASSERT( a.uid     == U_STRING_FROM_CONSTANT("User_ID") )
   U_ASSERT( a.sid     == U_STRING_FROM_CONSTANT("Session_ID") )
   U_ASSERT( a.ts      == U_STRING_FROM_CONSTANT("20031125131800") )
   U_ASSERT( a.cf      == U_STRING_FROM_CONSTANT("codicefiscale1") )
   U_ASSERT( a.migrate == true )

   HttpHeader h;
   HttpField* f = new HttpField(U_STRING_FROM_CONSTANT("Content-Type"), U_STRING_FROM_CONSTANT(" application/x-www-form-urlencoded"));
   HttpBaAuthorization* ba = new HttpBaAuthorization(U_CONSTANT_TO_PARAM("Authorization"),
                                                     U_CONSTANT_TO_PARAM(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
   HttpBaAuthorization* ba1 = new HttpBaAuthorization(U_CONSTANT_TO_PARAM("Authorization"),
                                                      U_CONSTANT_TO_PARAM(" Basic dXRlbnRlMTpzaWQx"));

   h.add(ba);
   h.add(f);
   h.add(ba1);

   HttpOtpPostLogin p(U_CONSTANT_TO_PARAM(POST_BODY), U_STRING_FROM_CONSTANT("user"),
                                                    U_STRING_FROM_CONSTANT("pin"),
                                                    U_STRING_FROM_CONSTANT("token"),
                                                    U_STRING_FROM_CONSTANT("password"),
                                                    U_STRING_FROM_CONSTANT("cf"), h);

   U_ASSERT( p.user  == U_STRING_FROM_CONSTANT("stefano casazza") )
   U_ASSERT( p.pin   == U_STRING_FROM_CONSTANT("12345") )
   U_ASSERT( p.token == U_STRING_FROM_CONSTANT("autorizzativo") )

   HttpField* p1 = h.del(U_STRING_FROM_CONSTANT("Content-Type"));

   U_ASSERT( p1 !=  0 )
   U_ASSERT( p1 == f )

   HttpBaAuthorization* p2 = (HttpBaAuthorization*) h.find(U_STRING_FROM_CONSTANT("Authorization"));

   U_ASSERT( p2 !=  0 )
   U_ASSERT( p2 == ba )

   U_ASSERT( p2->user   == U_STRING_FROM_CONSTANT("Aladdin") )
   U_ASSERT( p2->passwd == U_STRING_FROM_CONSTANT("open sesame") )

   HttpBaAuthorization* p3 = (HttpBaAuthorization*) h.find(U_STRING_FROM_CONSTANT("Authorization"), 1);

   U_ASSERT( p3 !=  0 )
   U_ASSERT( p3 == ba1 )

   U_ASSERT( p3->user   == U_STRING_FROM_CONSTANT("utente1") )
   U_ASSERT( p3->passwd == U_STRING_FROM_CONSTANT("sid1") )

   h.clear();

   UString result;

   a.stringify(result);

// TID=trustACCESS1;UID=utente1;SID=;TS=20031201174127;CF=codicefiscale1
#  define COOKIE_AUTH_1 \
"U2FsdGVkX1/QsrBvmsVHx0rrX78ldh6IJu1+4GhKoJ9O5ETSbfSiDip1gszkZX7w5ah6vkYfRWI8271LcNKhUsZVehRoscudLO8uotQgeiiF1B46ITphGw=="

// TID=trustACCESS1;UID=utente1;SID=sid;TS=20031201174127;CF=codicefiscale1;HP1=Profile_Header1;HPn=Profile_Headern;MIGRATE
#  define COOKIE_AUTH_2 \
"U2FsdGVkX1+tUkpPi14NVlKhm5KUFbSH0JFvi23+8B75MnKgtyD/sc0hc0ESmSahiYozVbS6a3OoZfWDHX3G3zuUwCP7n1+3jXK0wu6niifYUW+cKBk1WUdpJZd0xjJernDsWtPfq9j30uatAhHULG57vdrKlbtxM/EIaiaUow1AeLuDiZDcTRonghpI/aaz"

#ifdef U_PROXY_UNIT
   DES3engine eng1("password");
   OtpAuthToken c(&eng1, U_STRING_FROM_CONSTANT(COOKIE_AUTH_2));
   DES3engine eng2("password");
   OtpAuthToken b(&eng2, U_STRING_FROM_CONSTANT(COOKIE_AUTH_1));
#else
   u_des3_key("password");
   OtpAuthToken c(0, U_STRING_FROM_CONSTANT(COOKIE_AUTH_2));
   u_des3_reset();
   OtpAuthToken b(0, U_STRING_FROM_CONSTANT(COOKIE_AUTH_1));
#endif

   U_ASSERT( b.is_valid() == false )
   U_ASSERT( c.is_valid() == true )

   U_ASSERT( c.tid     == U_STRING_FROM_CONSTANT("trustACCESS1") )
   U_ASSERT( c.uid     == U_STRING_FROM_CONSTANT("utente1") )
   U_ASSERT( c.sid     == U_STRING_FROM_CONSTANT("sid") )
   U_ASSERT( c.ts      == U_STRING_FROM_CONSTANT("20031201174127") )
   U_ASSERT( c.cf      == U_STRING_FROM_CONSTANT("codicefiscale1") )
   U_ASSERT( c.migrate == true )

   value = not_found;

   U_ASSERT( c.find(U_STRING_FROM_CONSTANT("HP1"), value)  == true )
   U_ASSERT( value == U_STRING_FROM_CONSTANT("Profile_Header1") )

   U_ASSERT( c.del(U_STRING_FROM_CONSTANT("HP1"))  == true )

   value = not_found;

   U_ASSERT( c.find(U_STRING_FROM_CONSTANT("HPn"), value)  == true )
   U_ASSERT( value == U_STRING_FROM_CONSTANT("Profile_Headern") )

   HttpCookie c4(U_CONSTANT_TO_PARAM("Cookie"), U_CONSTANT_TO_PARAM(COOKIE_PROBLEM) );

   U_ASSERT( c4.count(U_STRING_FROM_CONSTANT("otptoken")) == 1 )

   value = path = domain = port = not_found;

   U_ASSERT( c4.find(U_STRING_FROM_CONSTANT("otptoken"), value, path, domain, port) == true )

   value.erase(value.size()-1, 1);
   value.erase(0, 1);

#ifdef U_PROXY_UNIT
   DES3engine eng3("password");
   OtpAuthToken d(&eng3, value);
#else
   u_des3_reset();
   OtpAuthToken d(0, value);
#endif

   U_ASSERT( d.is_valid() == false )

   result.erase(result.size()-1, 1);
   result.erase(0, 1);

   cout.write(result.data(), result.size());
}
Example #30
0
   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

      if (UApplication::isOptions()) cfg_str = opt['c'];

      // manage arg operation

      // manage file configuration

      if (cfg_str.empty()) cfg_str = U_STRING_FROM_CONSTANT("form_completion.cfg");

      (void) cfg.open(cfg_str);

      int LDAP_port;
      UString var_env_name, scan_form, LDAP_host, LDAP_searchbase, password, username,
              form_template, LDAP_rootdn, LDAP_rootpw, subject_attr;

      // --------------------------------------------------------------------------------------------------------------
      // configuration parameters
      // --------------------------------------------------------------------------------------------------------------
      // X509_SUBJECT_VARIABLE    var environment to elaborate  (ex: X509_SUBJECT)
      // X509_SUBJECT_FILTER      scanf form to extract data    (ex: /C=IT/L=Rome/O=Eraclito/OU=Tac/CN=%[^/]s/Email=%*s)
      // LDAP_SERVER_ADDRESS      name ldap host                (ex: slessi)
      // LDAP_SERVER_PORT         port ldap host                (ex: 389)
      // LDAP_SERVER_BASE
      // LDAP_SERVER_ROOTDN       bind DN for ldap query data
      // LDAP_SERVER_ROOTPW       bind password for ldap query data
      // LDAP_SUBJECT_ATTRIBUTE   attribute for query filter
      // LDAP_USER_ATTRIBUTE      name user attribute           (ex: uid)
      // LDAP_PASSWD_ATTRIBUTE    name password attribute       (ex: tacPassword)
      // TEMPLATE                 name form completion to print (ex: ./lms1.templ)
      // --------------------------------------------------------------------------------------------------------------

      var_env_name    = cfg[U_STRING_FROM_CONSTANT("X509_SUBJECT_VARIABLE")];
      scan_form       = cfg[U_STRING_FROM_CONSTANT("X509_SUBJECT_FILTER")];
      LDAP_host       = cfg[U_STRING_FROM_CONSTANT("LDAP_SERVER_ADDRESS")];
      LDAP_searchbase = cfg[U_STRING_FROM_CONSTANT("LDAP_SERVER_BASE")];
      LDAP_rootdn     = cfg[U_STRING_FROM_CONSTANT("LDAP_SERVER_ROOTDN")];
      LDAP_rootpw     = cfg[U_STRING_FROM_CONSTANT("LDAP_SERVER_ROOTPW")];
      subject_attr    = cfg[U_STRING_FROM_CONSTANT("LDAP_SUBJECT_ATTRIBUTE")];
      password        = cfg[U_STRING_FROM_CONSTANT("LDAP_PASSWD_ATTRIBUTE")];
      username        = cfg[U_STRING_FROM_CONSTANT("LDAP_USER_ATTRIBUTE")];
      form_template   = cfg[U_STRING_FROM_CONSTANT("TEMPLATE")];
      LDAP_port       = cfg.readLong(U_STRING_FROM_CONSTANT("LDAP_SERVER_PORT"), 389);

      // scanf

      char buf[256];
      const char* value = (const char*) U_SYSCALL(getenv, "%S", var_env_name.c_str());
      int n = U_SYSCALL(sscanf, "%S,%S,%p,%p,%p,%p", value, scan_form.c_str(), &buf[0]);

      if (n != 1) U_ERROR("scanf error on var env <%s>...", var_env_name.c_str());

      U_INTERNAL_DUMP("sscanf() result = \"%s\"", buf)

      // login to LDAP

      ULDAP ldap;

      if (ldap.init(LDAP_host.c_str(), (LDAP_port ? LDAP_port : LDAP_PORT)) == false ||
          ldap.set_protocol() == false ||
          ldap.bind(LDAP_rootdn.c_str(), LDAP_rootpw.c_str()) == false)

         {
         U_ERROR("login to LDAP failed...");
         }

      // search to LDAP

      char buffer[4096];
      const char* attr_name[] = { username.c_str(), password.c_str(), 0 };

      (void) snprintf(buffer, sizeof(buffer), "%s=%s,%.*s", subject_attr.c_str(), buf, U_STRING_TO_TRACE(LDAP_searchbase));

      n = ldap.search(buffer, LDAP_SCOPE_BASE, (char**)attr_name);

      if (n != 1) U_ERROR("search error on ldap...");

      ULDAPEntry entry(2, attr_name, 1);

      ldap.get(entry);

      const char* sname     = entry.getCStr(0);
      const char* spassword = entry.getCStr(1);

      // write to stdout

      (void) U_SYSCALL(printf, "%S,%S,%S", UFile::contentOf(form_template).data(), sname, spassword);
      }