<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef MODEL_SQUIRREL_HPP
#define MODEL_SQUIRREL_HPP

#include <locale>
#include <algorithm>

#include "json.hpp"

namespace acorn {

/**
 *
 */
struct Squirrel : json::Serializable {
  size_t key;

  Squirrel() : key(0) {}

  /**
   *
   */
  Squirrel(std::string name, size_t age, std::string occupation)
    : key         {0}
    , name_       {name}
    , age_        {age}
    , occupation_ {occupation}
  {}

  /**
   *
   */
  std::string json() const;

  /**
   *
   */
  virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;

  /**
   *
   */
  virtual bool deserialize(const rapidjson::Document&) override;

  /**
   *
   */
  bool is_equal(const Squirrel&) const;

  /**
   *
   */
  static bool is_equal(const Squirrel&, const Squirrel&);

private:
  const std::string name_;
  const size_t      age_;
  const std::string occupation_;
}; //< struct Squirrel

/**--v----------- Implementation Details -----------v--**/

inline void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {
  writer.StartObject();

  writer.Key("key");
  writer.Uint(key);

  writer.Key("name");
  writer.String(name_);

  writer.Key("age");
  writer.Uint(age_);

  writer.Key("occupation");
  writer.String(occupation_);

  writer.EndObject();
}

inline bool Squirrel::deserialize(const rapidjson::Document& doc) {
  name_       = doc["name"].GetString();
  age_        = doc["age"].GetUint();
  occupation_ = doc["occupation"].GetString();
  return true;
}

inline std::string Squirrel::json() const {
  using namespace rapidjson;
  StringBuffer sb;
  Writer<StringBuffer> writer(sb);
  serialize(writer);
  return sb.GetString();
}

inline bool Squirrel::is_equal(const Squirrel& s) const {
  if(name_.size() not_eq s.name_.size()) {
    return false;
  }

  return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(),
    [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);
  });
}

inline bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {
  return s1.is_equal(s2);
}

inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {
  return output_device.json();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace acorn

#endif //< MODEL_SQUIRREL_HPP
<commit_msg>Corrected error in squirrel output operator<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef MODEL_SQUIRREL_HPP
#define MODEL_SQUIRREL_HPP

#include <locale>
#include <algorithm>

#include "json.hpp"

namespace acorn {

/**
 *
 */
struct Squirrel : json::Serializable {
  size_t key;

  Squirrel() : key(0) {}

  /**
   *
   */
  Squirrel(std::string name, size_t age, std::string occupation)
    : key         {0}
    , name_       {name}
    , age_        {age}
    , occupation_ {occupation}
  {}

  /**
   *
   */
  std::string json() const;

  /**
   *
   */
  virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;

  /**
   *
   */
  virtual bool deserialize(const rapidjson::Document&) override;

  /**
   *
   */
  bool is_equal(const Squirrel&) const;

  /**
   *
   */
  static bool is_equal(const Squirrel&, const Squirrel&);

private:
  const std::string name_;
  const size_t      age_;
  const std::string occupation_;
}; //< struct Squirrel

/**--v----------- Implementation Details -----------v--**/

inline void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {
  writer.StartObject();

  writer.Key("key");
  writer.Uint(key);

  writer.Key("name");
  writer.String(name_);

  writer.Key("age");
  writer.Uint(age_);

  writer.Key("occupation");
  writer.String(occupation_);

  writer.EndObject();
}

inline bool Squirrel::deserialize(const rapidjson::Document& doc) {
  name_       = doc["name"].GetString();
  age_        = doc["age"].GetUint();
  occupation_ = doc["occupation"].GetString();
  return true;
}

inline std::string Squirrel::json() const {
  using namespace rapidjson;
  StringBuffer sb;
  Writer<StringBuffer> writer(sb);
  serialize(writer);
  return sb.GetString();
}

inline bool Squirrel::is_equal(const Squirrel& s) const {
  if(name_.size() not_eq s.name_.size()) {
    return false;
  }

  return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(),
    [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);
  });
}

inline bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {
  return s1.is_equal(s2);
}

inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {
  return output_device << s.json();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace acorn

#endif //< MODEL_SQUIRREL_HPP
<|endoftext|>


<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*     2016 Matthias Gierlings
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)

#include <botan/tls_client.h>
#include <botan/tls_policy.h>
#include <botan/x509path.h>
#include <botan/ocsp.h>
#include <botan/hex.h>
#include <botan/parsing.h>
#include <fstream>

#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
   #include <botan/tls_session_manager_sqlite.h>
#endif

#include <string>
#include <memory>

#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
#include <winsock2.h>
#include <WS2tcpip.h>

int close(int fd)
   {
   return ::closesocket(fd);
   }

int read(int s, void* buf, size_t len)
   {
   return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
   }

int send(int s, const uint8_t* buf, size_t len, int flags)
   {
   return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
   }

#define STDIN_FILENO _fileno(stdin)
typedef size_t ssize_t;
#else
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif

#if !defined(MSG_NOSIGNAL)
   #define MSG_NOSIGNAL 0
#endif

#include "credentials.h"

namespace Botan_CLI {

class TLS_Client final : public Command, public Botan::TLS::Callbacks
   {
   public:
      TLS_Client()
         : Command("tls_client host --port=443 --print-certs --policy= "
                   "--tls1.0 --tls1.1 --tls1.2 "
                   "--session-db= --session-db-pass= --next-protocols= --type=tcp")
         {
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if(::WSAStartup(wsa_version, &wsa_data) != 0)
            {
            throw CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
            }

         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
            {
            ::WSACleanup();
            throw CLI_Error("Could not find a usable version of Winsock.dll");
            }
#endif
         }

      ~TLS_Client()
         {
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
         ::WSACleanup();
#endif
         }

      void go() override
         {
         // TODO client cert auth

         std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;

         const std::string sessions_db = get_arg("session-db");

         if(!sessions_db.empty())
            {
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
            const std::string sessions_passphrase = get_arg("session-db-pass");
            session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));
#else
            error_output() << "Ignoring session DB file, sqlite not enabled\n";
#endif
            }

         if(!session_mgr)
            {
            session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));
            }

         std::string policy_file = get_arg("policy");

         std::unique_ptr<Botan::TLS::Policy> policy;

         if(policy_file.size() > 0)
            {
            std::ifstream policy_stream(policy_file);
            if(!policy_stream.good())
               {
               error_output() << "Failed reading policy file\n";
               return;
               }
            policy.reset(new Botan::TLS::Text_Policy(policy_stream));
            }

         if(!policy)
            {
            policy.reset(new Botan::TLS::Policy);
            }

         Basic_Credentials_Manager creds;

         const std::string host = get_arg("host");
         const uint16_t port = get_arg_sz("port");
         const std::string transport = get_arg("type");
         const std::string next_protos = get_arg("next-protocols");

         if(transport != "tcp" && transport != "udp")
            {
            throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
            }

         const bool use_tcp = (transport == "tcp");

         const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ',');

         m_sockfd = connect_to_host(host, port, use_tcp);

         using namespace std::placeholders;

         auto version = policy->latest_supported_version(!use_tcp);

         if(flag_set("tls1.0"))
            {
            version = Botan::TLS::Protocol_Version::TLS_V10;
            }
         else if(flag_set("tls1.1"))
            {
            version = Botan::TLS::Protocol_Version::TLS_V11;
            }

         struct sockaddr_storage addrbuf;
         std::string hostname;
         if(!host.empty() &&
               inet_pton(AF_INET, host.c_str(), &addrbuf) != 1 &&
               inet_pton(AF_INET6, host.c_str(), &addrbuf) != 1)
            {
            hostname = host;
            }

         Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(),
                                   Botan::TLS::Server_Information(hostname, port),
                                   version, protocols_to_offer);

         bool first_active = true;

         while(!client.is_closed())
            {
            fd_set readfds;
            FD_ZERO(&readfds);
            FD_SET(m_sockfd, &readfds);

            if(client.is_active())
               {
               FD_SET(STDIN_FILENO, &readfds);
               if(first_active && !protocols_to_offer.empty())
                  {
                  std::string app = client.application_protocol();
                  if(app != "")
                     {
                     output() << "Server choose protocol: " << client.application_protocol() << "\n";
                     }
                  first_active = false;
                  }
               }

            struct timeval timeout = { 1, 0 };

            ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);

            if(FD_ISSET(m_sockfd, &readfds))
               {
               uint8_t buf[4 * 1024] = { 0 };

               ssize_t got = ::read(m_sockfd, buf, sizeof(buf));

               if(got == 0)
                  {
                  output() << "EOF on socket\n";
                  break;
                  }
               else if(got == -1)
                  {
                  output() << "Socket error: " << errno << " " << std::strerror(errno) << "\n";
                  continue;
                  }

               client.received_data(buf, got);
               }

            if(FD_ISSET(STDIN_FILENO, &readfds))
               {
               uint8_t buf[1024] = { 0 };
               ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));

               if(got == 0)
                  {
                  output() << "EOF on stdin\n";
                  client.close();
                  break;
                  }
               else if(got == -1)
                  {
                  output() << "Stdin error: " << errno << " " << std::strerror(errno) << "\n";
                  continue;
                  }

               if(got == 2 && buf[1] == '\n')
                  {
                  char cmd = buf[0];

                  if(cmd == 'R' || cmd == 'r')
                     {
                     output() << "Client initiated renegotiation\n";
                     client.renegotiate(cmd == 'R');
                     }
                  else if(cmd == 'Q')
                     {
                     output() << "Client initiated close\n";
                     client.close();
                     }
                  }
               else
                  {
                  client.send(buf, got);
                  }
               }

            if(client.timeout_check())
               {
               output() << "Timeout detected\n";
               }
            }

         ::close(m_sockfd);
         }

   private:
      int connect_to_host(const std::string& host, uint16_t port, bool tcp)
         {
         addrinfo hints = {};
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
         addrinfo* res, *rp = nullptr;

         if(::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0)
            {
            throw CLI_Error("getaddrinfo failed for " + host);
            }

         int fd = 0;

         for(rp = res; rp != nullptr; rp = rp->ai_next)
            {
            fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(fd == -1)
               {
               continue;
               }

            if(::connect(fd, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::close(fd);
               continue;
               }

            break;
            }

         ::freeaddrinfo(res);

         if(rp == nullptr) // no address succeeded
            {
            throw CLI_Error("connect failed");
            }

         return fd;
         }

      void tls_verify_cert_chain(
         const std::vector<Botan::X509_Certificate>& cert_chain,
         const std::vector<std::shared_ptr<const Botan::OCSP::Response>>& ocsp,
         const std::vector<Botan::Certificate_Store*>& trusted_roots,
         Botan::Usage_Type usage,
         const std::string& hostname,
         const Botan::TLS::Policy& policy) override
         {
         if(cert_chain.empty())
            {
            throw std::invalid_argument("Certificate chain was empty");
            }

         Botan::Path_Validation_Restrictions restrictions(
            policy.require_cert_revocation_info(),
            policy.minimum_signature_strength());

         auto ocsp_timeout = std::chrono::milliseconds(1000);

         Botan::Path_Validation_Result result = Botan::x509_path_validate(
               cert_chain,
               restrictions,
               trusted_roots,
               hostname,
               usage,
               std::chrono::system_clock::now(),
               ocsp_timeout,
               ocsp);

         output() << "Certificate validation status: " << result.result_string() << "\n";
         if(result.successful_validation())
            {
            auto status = result.all_statuses();

            if(status.size() > 0 && status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD))
               {
               output() << "Valid OCSP response for this server\n";
               }
            }
         }

      bool tls_session_established(const Botan::TLS::Session& session) override
         {
         output() << "Handshake complete, " << session.version().to_string()
                  << " using " << session.ciphersuite().to_string() << "\n";

         if(!session.session_id().empty())
            {
            output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n";
            }

         if(!session.session_ticket().empty())
            {
            output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n";
            }

         if(flag_set("print-certs"))
            {
            const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();

            for(size_t i = 0; i != certs.size(); ++i)
               {
               output() << "Certificate " << i + 1 << "/" << certs.size() << "\n";
               output() << certs[i].to_string();
               output() << certs[i].PEM_encode();
               }
            }

         return true;
         }

      static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)
         {
         int r = ::send(sockfd, buf, length, MSG_NOSIGNAL);

         if(r == -1)
            {
            throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
            }
         }

      void tls_emit_data(const uint8_t buf[], size_t length) override
         {
         size_t offset = 0;

         while(length)
            {
            ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);

            if(sent == -1)
               {
               if(errno == EINTR)
                  {
                  sent = 0;
                  }
               else
                  {
                  throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
                  }
               }

            offset += sent;
            length -= sent;
            }
         }

      void tls_alert(Botan::TLS::Alert alert) override
         {
         output() << "Alert: " << alert.type_string() << "\n";
         }

      void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override
         {
         for(size_t i = 0; i != buf_size; ++i)
            {
            output() << buf[i];
            }
         }

   private:
      int m_sockfd = -1;
   };

BOTAN_REGISTER_COMMAND("tls_client", TLS_Client);

}

#endif
<commit_msg>Avoid uninitialized field warnings<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*     2016 Matthias Gierlings
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)

#include <botan/tls_client.h>
#include <botan/tls_policy.h>
#include <botan/x509path.h>
#include <botan/ocsp.h>
#include <botan/hex.h>
#include <botan/parsing.h>
#include <fstream>

#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
   #include <botan/tls_session_manager_sqlite.h>
#endif

#include <string>
#include <memory>

#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
#include <winsock2.h>
#include <WS2tcpip.h>

int close(int fd)
   {
   return ::closesocket(fd);
   }

int read(int s, void* buf, size_t len)
   {
   return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
   }

int send(int s, const uint8_t* buf, size_t len, int flags)
   {
   return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
   }

#define STDIN_FILENO _fileno(stdin)
typedef size_t ssize_t;
#else
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif

#if !defined(MSG_NOSIGNAL)
   #define MSG_NOSIGNAL 0
#endif

#include "credentials.h"

namespace Botan_CLI {

class TLS_Client final : public Command, public Botan::TLS::Callbacks
   {
   public:
      TLS_Client()
         : Command("tls_client host --port=443 --print-certs --policy= "
                   "--tls1.0 --tls1.1 --tls1.2 "
                   "--session-db= --session-db-pass= --next-protocols= --type=tcp")
         {
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
         WSAData wsa_data;
         WORD wsa_version = MAKEWORD(2, 2);

         if(::WSAStartup(wsa_version, &wsa_data) != 0)
            {
            throw CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
            }

         if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
            {
            ::WSACleanup();
            throw CLI_Error("Could not find a usable version of Winsock.dll");
            }
#endif
         }

      ~TLS_Client()
         {
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
         ::WSACleanup();
#endif
         }

      void go() override
         {
         // TODO client cert auth

         std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;

         const std::string sessions_db = get_arg("session-db");

         if(!sessions_db.empty())
            {
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
            const std::string sessions_passphrase = get_arg("session-db-pass");
            session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));
#else
            error_output() << "Ignoring session DB file, sqlite not enabled\n";
#endif
            }

         if(!session_mgr)
            {
            session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));
            }

         std::string policy_file = get_arg("policy");

         std::unique_ptr<Botan::TLS::Policy> policy;

         if(policy_file.size() > 0)
            {
            std::ifstream policy_stream(policy_file);
            if(!policy_stream.good())
               {
               error_output() << "Failed reading policy file\n";
               return;
               }
            policy.reset(new Botan::TLS::Text_Policy(policy_stream));
            }

         if(!policy)
            {
            policy.reset(new Botan::TLS::Policy);
            }

         Basic_Credentials_Manager creds;

         const std::string host = get_arg("host");
         const uint16_t port = get_arg_sz("port");
         const std::string transport = get_arg("type");
         const std::string next_protos = get_arg("next-protocols");

         if(transport != "tcp" && transport != "udp")
            {
            throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
            }

         const bool use_tcp = (transport == "tcp");

         const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ',');

         m_sockfd = connect_to_host(host, port, use_tcp);

         using namespace std::placeholders;

         auto version = policy->latest_supported_version(!use_tcp);

         if(flag_set("tls1.0"))
            {
            version = Botan::TLS::Protocol_Version::TLS_V10;
            }
         else if(flag_set("tls1.1"))
            {
            version = Botan::TLS::Protocol_Version::TLS_V11;
            }

         struct sockaddr_storage addrbuf;
         std::string hostname;
         if(!host.empty() &&
               inet_pton(AF_INET, host.c_str(), &addrbuf) != 1 &&
               inet_pton(AF_INET6, host.c_str(), &addrbuf) != 1)
            {
            hostname = host;
            }

         Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(),
                                   Botan::TLS::Server_Information(hostname, port),
                                   version, protocols_to_offer);

         bool first_active = true;

         while(!client.is_closed())
            {
            fd_set readfds;
            FD_ZERO(&readfds);
            FD_SET(m_sockfd, &readfds);

            if(client.is_active())
               {
               FD_SET(STDIN_FILENO, &readfds);
               if(first_active && !protocols_to_offer.empty())
                  {
                  std::string app = client.application_protocol();
                  if(app != "")
                     {
                     output() << "Server choose protocol: " << client.application_protocol() << "\n";
                     }
                  first_active = false;
                  }
               }

            struct timeval timeout = { 1, 0 };

            ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);

            if(FD_ISSET(m_sockfd, &readfds))
               {
               uint8_t buf[4 * 1024] = { 0 };

               ssize_t got = ::read(m_sockfd, buf, sizeof(buf));

               if(got == 0)
                  {
                  output() << "EOF on socket\n";
                  break;
                  }
               else if(got == -1)
                  {
                  output() << "Socket error: " << errno << " " << std::strerror(errno) << "\n";
                  continue;
                  }

               client.received_data(buf, got);
               }

            if(FD_ISSET(STDIN_FILENO, &readfds))
               {
               uint8_t buf[1024] = { 0 };
               ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));

               if(got == 0)
                  {
                  output() << "EOF on stdin\n";
                  client.close();
                  break;
                  }
               else if(got == -1)
                  {
                  output() << "Stdin error: " << errno << " " << std::strerror(errno) << "\n";
                  continue;
                  }

               if(got == 2 && buf[1] == '\n')
                  {
                  char cmd = buf[0];

                  if(cmd == 'R' || cmd == 'r')
                     {
                     output() << "Client initiated renegotiation\n";
                     client.renegotiate(cmd == 'R');
                     }
                  else if(cmd == 'Q')
                     {
                     output() << "Client initiated close\n";
                     client.close();
                     }
                  }
               else
                  {
                  client.send(buf, got);
                  }
               }

            if(client.timeout_check())
               {
               output() << "Timeout detected\n";
               }
            }

         ::close(m_sockfd);
         }

   private:
      int connect_to_host(const std::string& host, uint16_t port, bool tcp)
         {
         addrinfo hints;
         std::memset(&hints, 0, sizeof(hints));
         hints.ai_family = AF_UNSPEC;
         hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
         addrinfo* res, *rp = nullptr;

         if(::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0)
            {
            throw CLI_Error("getaddrinfo failed for " + host);
            }

         int fd = 0;

         for(rp = res; rp != nullptr; rp = rp->ai_next)
            {
            fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);

            if(fd == -1)
               {
               continue;
               }

            if(::connect(fd, rp->ai_addr, rp->ai_addrlen) != 0)
               {
               ::close(fd);
               continue;
               }

            break;
            }

         ::freeaddrinfo(res);

         if(rp == nullptr) // no address succeeded
            {
            throw CLI_Error("connect failed");
            }

         return fd;
         }

      void tls_verify_cert_chain(
         const std::vector<Botan::X509_Certificate>& cert_chain,
         const std::vector<std::shared_ptr<const Botan::OCSP::Response>>& ocsp,
         const std::vector<Botan::Certificate_Store*>& trusted_roots,
         Botan::Usage_Type usage,
         const std::string& hostname,
         const Botan::TLS::Policy& policy) override
         {
         if(cert_chain.empty())
            {
            throw std::invalid_argument("Certificate chain was empty");
            }

         Botan::Path_Validation_Restrictions restrictions(
            policy.require_cert_revocation_info(),
            policy.minimum_signature_strength());

         auto ocsp_timeout = std::chrono::milliseconds(1000);

         Botan::Path_Validation_Result result = Botan::x509_path_validate(
               cert_chain,
               restrictions,
               trusted_roots,
               hostname,
               usage,
               std::chrono::system_clock::now(),
               ocsp_timeout,
               ocsp);

         output() << "Certificate validation status: " << result.result_string() << "\n";
         if(result.successful_validation())
            {
            auto status = result.all_statuses();

            if(status.size() > 0 && status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD))
               {
               output() << "Valid OCSP response for this server\n";
               }
            }
         }

      bool tls_session_established(const Botan::TLS::Session& session) override
         {
         output() << "Handshake complete, " << session.version().to_string()
                  << " using " << session.ciphersuite().to_string() << "\n";

         if(!session.session_id().empty())
            {
            output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n";
            }

         if(!session.session_ticket().empty())
            {
            output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n";
            }

         if(flag_set("print-certs"))
            {
            const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();

            for(size_t i = 0; i != certs.size(); ++i)
               {
               output() << "Certificate " << i + 1 << "/" << certs.size() << "\n";
               output() << certs[i].to_string();
               output() << certs[i].PEM_encode();
               }
            }

         return true;
         }

      static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)
         {
         int r = ::send(sockfd, buf, length, MSG_NOSIGNAL);

         if(r == -1)
            {
            throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
            }
         }

      void tls_emit_data(const uint8_t buf[], size_t length) override
         {
         size_t offset = 0;

         while(length)
            {
            ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);

            if(sent == -1)
               {
               if(errno == EINTR)
                  {
                  sent = 0;
                  }
               else
                  {
                  throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
                  }
               }

            offset += sent;
            length -= sent;
            }
         }

      void tls_alert(Botan::TLS::Alert alert) override
         {
         output() << "Alert: " << alert.type_string() << "\n";
         }

      void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override
         {
         for(size_t i = 0; i != buf_size; ++i)
            {
            output() << buf[i];
            }
         }

   private:
      int m_sockfd = -1;
   };

BOTAN_REGISTER_COMMAND("tls_client", TLS_Client);

}

#endif
<|endoftext|>


<commit_before>//===--- SIL.cpp - Implements random SIL functionality --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILUndef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/ClangImporter/ClangModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"

using namespace swift;

SILUndef *SILUndef::get(SILType Ty, SILModule *M) {
  // Unique these.
  SILUndef *&Entry = M->UndefValues[Ty];
  if (Entry == nullptr)
    Entry = new (*M) SILUndef(Ty);
  return Entry;
}

FormalLinkage swift::getDeclLinkage(const ValueDecl *D) {
  const DeclContext *fileContext = D->getDeclContext()->getModuleScopeContext();

  // Clang declarations are public and can't be assured of having a
  // unique defining location.
  if (isa<ClangModuleUnit>(fileContext))
    return FormalLinkage::PublicNonUnique;

  if (!D->hasAccess()) {
    assert(D->getDeclContext()->isLocalContext());
    return FormalLinkage::Private;
  }

  switch (D->getEffectiveAccess()) {
  case AccessLevel::Public:
  case AccessLevel::Open:
    return FormalLinkage::PublicUnique;
  case AccessLevel::Internal:
    return FormalLinkage::HiddenUnique;
  case AccessLevel::FilePrivate:
  case AccessLevel::Private:
    return FormalLinkage::Private;
  }

  llvm_unreachable("Unhandled access level in switch.");
}

SILLinkage swift::getSILLinkage(FormalLinkage linkage,
                                ForDefinition_t forDefinition) {
  switch (linkage) {
  case FormalLinkage::PublicUnique:
    return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);

  case FormalLinkage::PublicNonUnique:
    // FIXME: any place we have to do this that actually requires
    // uniqueness is buggy.
    return (forDefinition ? SILLinkage::Shared : SILLinkage::PublicExternal);

  case FormalLinkage::HiddenUnique:
    return (forDefinition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);

  case FormalLinkage::Private:
    return SILLinkage::Private;
  }
  llvm_unreachable("bad formal linkage");
}

SILLinkage
swift::getLinkageForProtocolConformance(const NormalProtocolConformance *C,
                                        ForDefinition_t definition) {
  // Behavior conformances are always private.
  if (C->isBehaviorConformance())
    return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);

  // If the conformance was synthesized by the ClangImporter, give it
  // shared linkage.
  if (isa<ClangModuleUnit>(C->getDeclContext()->getModuleScopeContext()))
    return SILLinkage::Shared;

  auto typeDecl = C->getType()->getNominalOrBoundGenericNominal();
  AccessLevel access = std::min(C->getProtocol()->getEffectiveAccess(),
                                typeDecl->getEffectiveAccess());
  switch (access) {
    case AccessLevel::Private:
    case AccessLevel::FilePrivate:
      return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);

    case AccessLevel::Internal:
      return (definition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);

    default:
      return (definition ? SILLinkage::Public : SILLinkage::PublicExternal);
  }
}
<commit_msg>SIL: All declarations have access after type checking<commit_after>//===--- SIL.cpp - Implements random SIL functionality --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILUndef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/ClangImporter/ClangModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"

using namespace swift;

SILUndef *SILUndef::get(SILType Ty, SILModule *M) {
  // Unique these.
  SILUndef *&Entry = M->UndefValues[Ty];
  if (Entry == nullptr)
    Entry = new (*M) SILUndef(Ty);
  return Entry;
}

FormalLinkage swift::getDeclLinkage(const ValueDecl *D) {
  const DeclContext *fileContext = D->getDeclContext()->getModuleScopeContext();

  // Clang declarations are public and can't be assured of having a
  // unique defining location.
  if (isa<ClangModuleUnit>(fileContext))
    return FormalLinkage::PublicNonUnique;

  switch (D->getEffectiveAccess()) {
  case AccessLevel::Public:
  case AccessLevel::Open:
    return FormalLinkage::PublicUnique;
  case AccessLevel::Internal:
    return FormalLinkage::HiddenUnique;
  case AccessLevel::FilePrivate:
  case AccessLevel::Private:
    return FormalLinkage::Private;
  }

  llvm_unreachable("Unhandled access level in switch.");
}

SILLinkage swift::getSILLinkage(FormalLinkage linkage,
                                ForDefinition_t forDefinition) {
  switch (linkage) {
  case FormalLinkage::PublicUnique:
    return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);

  case FormalLinkage::PublicNonUnique:
    // FIXME: any place we have to do this that actually requires
    // uniqueness is buggy.
    return (forDefinition ? SILLinkage::Shared : SILLinkage::PublicExternal);

  case FormalLinkage::HiddenUnique:
    return (forDefinition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);

  case FormalLinkage::Private:
    return SILLinkage::Private;
  }
  llvm_unreachable("bad formal linkage");
}

SILLinkage
swift::getLinkageForProtocolConformance(const NormalProtocolConformance *C,
                                        ForDefinition_t definition) {
  // Behavior conformances are always private.
  if (C->isBehaviorConformance())
    return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);

  // If the conformance was synthesized by the ClangImporter, give it
  // shared linkage.
  if (isa<ClangModuleUnit>(C->getDeclContext()->getModuleScopeContext()))
    return SILLinkage::Shared;

  auto typeDecl = C->getType()->getNominalOrBoundGenericNominal();
  AccessLevel access = std::min(C->getProtocol()->getEffectiveAccess(),
                                typeDecl->getEffectiveAccess());
  switch (access) {
    case AccessLevel::Private:
    case AccessLevel::FilePrivate:
      return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);

    case AccessLevel::Internal:
      return (definition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);

    default:
      return (definition ? SILLinkage::Public : SILLinkage::PublicExternal);
  }
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#undef NDEBUG

// O_LARGEFILE is a GNU extension.
#ifdef __APPLE__
#define  O_LARGEFILE  0
#endif

// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
//
#include "../3rdParty/ply.h"

namespace ospray {
  namespace sg {
#if 0
    namespace ply {
      using std::string;
      using std::cout;
      using std::endl;

#define FALSE           0
#define TRUE            1

#define X               0
#define Y               1
#define Z               2

      enum {
        FACE_INDICES = 0,
        FACE_RED,
        FACE_GREEN,
        FACE_BLUE
      };

      typedef float Point[3];
      typedef float Vector[3];

      typedef struct Vertex {
        int    id;
        Point  coord;            /* coordinates of vertex */
        Point  normal;            /* normal of vertex */
        unsigned char red;
        unsigned char green;
        unsigned char blue;
        unsigned char nfaces;    /* number of face indices in list */
        int *faces;              /* face index list */
        void *other_props;       /* other properties */
      } Vertex;

      typedef struct Face {
        int id;
        unsigned char nverts;    /* number of vertex indices in list */
        int *verts;              /* vertex index list */
        unsigned char red;
        unsigned char green;
        unsigned char blue;

        void *other_props;       /* other properties */
      } Face;

      PlyProperty vert_props[] = { /* list of property information for a vertex */
        {(char*)"x", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[X]), 0, 0, 0, 0},
        {(char*)"y", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Y]), 0, 0, 0, 0},
        {(char*)"z", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Z]), 0, 0, 0, 0},
        {(char*)"nx", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[X]), 0, 0, 0, 0},
        {(char*)"ny", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Y]), 0, 0, 0, 0},
        {(char*)"nz", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Z]), 0, 0, 0, 0},
        {(char*)"diffuse_red", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,red), 0, 0, 0, 0},
        {(char*)"diffuse_green", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,green), 0, 0, 0, 0},
        {(char*)"diffuse_blue", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,blue), 0, 0, 0, 0},
      };
      enum {
        VTX_X = 0,
        VTX_Y,
        VTX_Z,
        VTX_NX,
        VTX_NY,
        VTX_NZ,
        VTX_RED,
        VTX_GREEN,
        VTX_BLUE
      };

      PlyProperty face_props[] = { /* list of property information for a face */
        {(char*)"vertex_indices", PLY_INT, PLY_INT, offsetof(Face,verts),
         1, PLY_UCHAR, PLY_UCHAR, offsetof(Face,nverts)},
        {(char*)"red", PLY_UCHAR, PLY_UCHAR, offsetof(Face,red), 0, 0, 0, 0},
        {(char*)"green", PLY_UCHAR, PLY_UCHAR, offsetof(Face,green), 0, 0, 0, 0},
        {(char*)"blue", PLY_UCHAR, PLY_UCHAR, offsetof(Face,blue), 0, 0, 0, 0},
      };

      void readFile(const std::string &fileName, std::shared_ptr<sg::TriangleMesh> mesh)
      {
        int nprops;
        PlyProperty **plist;
        float version;
        int vertices = 0;

        int triangles = 0;

        int has_x, has_y, has_z;
        int has_face_red=0; // face colors
        int has_face_green=0; // face colors
        int has_face_blue=0; // face colors
        int has_vertex_red=0; // vertex colors
        int has_vertex_green=0; // vertex colors
        int has_vertex_blue=0; // vertex colors
        int has_nx=0, has_ny=0, has_nz=0;
        int has_fverts=0;

        PlyOtherElems *other_elements = NULL;
        PlyOtherProp *vert_other,*face_other;//,*edge_other;

        char **element_list = NULL;
        int file_type = 0;

        std::shared_ptr<sg::DataVector3f> pos = std::make_shared<sg::DataVector3f>();
        std::shared_ptr<sg::DataVector3f> nor = std::make_shared<sg::DataVector3f>();
        std::shared_ptr<sg::DataVector3i> idx = std::make_shared<sg::DataVector3i>();

        /*** Read in the original PLY object ***/
        const char *filename = fileName.c_str();
        FILE *file;
        bool isPipe = false;

        if (strlen(filename) > 7 && !strcmp(filename+strlen(filename)-7,".ply.gz")) {
#ifdef _WIN32
          THROW_SG_ERROR("#osp:sg:ply: gzipped file not supported yet on Windows");
#else
          isPipe = true;
          char cmd[10000];
          sprintf(cmd,"/usr/bin/gunzip -c %s",filename);
          file = popen(cmd,"r");
#endif
        } else
          file = fopen(filename,"rb");

        if (!file)
          throw std::runtime_error("#osp:sg:ply: could not open '"+fileName+"'");

        int nelems = -1;
        PlyFile *ply  = ply_read (file, &nelems, &element_list);
        ply_get_info (ply, &version, &file_type);

        for (int i=0; i<nelems; i++) {
          int num_elems;

          /* get the description of the first element */
          char *elem_name = element_list[i];
          plist = ply_get_element_description (ply, elem_name, &num_elems, &nprops);

          if (equal_strings ("vertex", elem_name)) {
            /* create a vertex list to hold all the vertices */

            /* set up for getting vertex elements */
            /* verify which properties these vertices have */
            has_x = has_y = has_z = FALSE;
            has_nx = has_ny = has_nz = FALSE;

            for (int j=0; j<nprops; j++) {
              if (equal_strings("x", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_X]);  /* x */
                has_x = TRUE;
              } else if (equal_strings("y", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_Y]);  /* y */
                has_y = TRUE;
              } else if (equal_strings("z", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_Z]);  /* z */
                has_z = TRUE;
              }

              if (equal_strings("nx", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NX]);  /* x */
                has_nx = TRUE;
              } else if (equal_strings("ny", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NY]);  /* y */
                has_ny = TRUE;
              } else if (equal_strings("nz", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NZ]);  /* z */
                has_nz = TRUE;
              } else if (equal_strings("diffuse_red", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_RED]);  /* z */
                has_vertex_red = TRUE;
              } else if (equal_strings("diffuse_green", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_GREEN]);  /* z */
                has_vertex_green = TRUE;
              } else if (equal_strings("diffuse_blue", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_BLUE]);  /* z */
                has_vertex_blue = TRUE;
              }
            }

            vert_other = ply_get_other_properties (ply, elem_name,
                                                   offsetof(Vertex,other_props));

            /* test for necessary properties */
            if ((!has_x) || (!has_y) || (!has_z))
              {
                fprintf(stderr, "Vertices don't have x, y, and z\n");
                exit(-1);
              }

            vertices = num_elems;
            if (has_nx && has_ny && has_nz)
              nor->v.resize(vertices);
            pos->v.resize(vertices);

            /* grab all the vertex elements */
            for (int j=0; j<vertices; j++) {
              Vertex tmp;
              ply_get_element (ply, (void *) &tmp);
              pos->v[j] = vec3f(tmp.coord[0],tmp.coord[1],tmp.coord[2]);
              if (has_nx && has_ny && has_nz)
                nor->v[j] = vec3f(tmp.normal[0],tmp.normal[1],tmp.normal[2]);
            }
          } else if (equal_strings ("face", elem_name)) {

            /* create a list to hold all the face elements */
            cout << "num faces : " << (num_elems) << endl;

            /* set up for getting face elements */
            /* verify which properties these vertices have */
            has_fverts = FALSE;

            for (int j=0; j<nprops; j++) {
              if (equal_strings("vertex_indices", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_INDICES]);/* vertex_indices */
                has_fverts = TRUE;
              } else if (equal_strings("red", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_RED]);/* vertex_indices */
                has_face_red = TRUE;
              } else if (equal_strings("green", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_GREEN]);/* vertex_indices */
                has_face_green = TRUE;
              } else if (equal_strings("blue", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_BLUE]);/* vertex_indices */
                has_face_blue = TRUE;
              }
            }
            face_other = ply_get_other_properties (ply, elem_name,
                                                   offsetof(Face,other_props));

            /* test for necessary properties */
            if (!has_fverts) {
              fprintf(stderr, "Faces must have vertex indices\n");
              exit(-1);
            }

            triangles = num_elems;
            // numTrisWritten += num_elems;

            /* grab all the face elements */
            Face tmp;
            tmp.verts = NULL;
            tmp.other_props = NULL;
            for (int j=0; j<num_elems; j++)  {
              ply_get_element (ply, (void *) &tmp);
              if (!has_face_blue) {
                tmp.red = tmp.green = tmp.blue = 255;
              }
              if (tmp.nverts == 3) {
                // if (has_face_blue)
                //   material = getMaterial(tmp.red,tmp.green,tmp.blue);;

                vec3i vtx;
                vtx.x = tmp.verts[0]; //builder.addVertex(pos[tmp.verts[0]]);
                vtx.y = tmp.verts[1]; //builder.addVertex(pos[tmp.verts[1]]);
                vtx.z = tmp.verts[2]; //builder.addVertex(pos[tmp.verts[2]]);
                idx->v.push_back(vtx);
              } else {
                PRINT((int)tmp.nverts);
                FATAL("can only read ply files made up of triangles...");
              }
              free(tmp.verts);
              if (tmp.other_props) free(tmp.other_props);
            }
          }
          else {
            other_elements = ply_get_other_element (ply, elem_name, num_elems);
            ply_free_other_elements(other_elements);
          }
        }

        int num_comments;
        char **comments;
        // PlyOtherProp *vert_other,*face_other;//,*edge_other;

        int num_obj_info;
        char **obj_info;

        comments = ply_get_comments (ply, &num_comments);
        obj_info = ply_get_obj_info (ply, &num_obj_info);

        ply_close (ply);

        for (int i=0;i<ply->nelems;i++) {
          if (ply->elems[i]) continue;
          PlyElement *e = ply->elems[i];
          FREE(e->name);
          FREE(e->store_prop);
          if (e->props) {
            for (int j=0;j<e->nprops;j++) {
              PlyProperty *p = e->props[j];
              if (!e) continue;
              FREE(p->name);
              FREE(p);
            }
            FREE(e->props);
          }
          FREE(e);
        }

        free(ply->elems);

        mesh->index = idx;
        mesh->vertex = pos;
        if (!nor->v.empty())
          mesh->normal = nor;
      }

    } // ::ospray::sg::ply
#endif

    void importPLY(std::shared_ptr<Node> &world, const FileName &fileName)
    {
#if 0
      std::shared_ptr<sg::TriangleMesh> mesh =
          std::static_pointer_cast<sg::TriangleMesh>(sg::createNode(fileName.name(), "TriangleMesh"));
      ply::readFile(fileName.str(), mesh);
      world->add(std::dynamic_pointer_cast<sg::Node>(mesh));
#endif
    }

  } // ::ospray::sg
} // ::ospray
<commit_msg>re-enable and fix PLY sg importer<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#undef NDEBUG

// O_LARGEFILE is a GNU extension.
#ifdef __APPLE__
#define  O_LARGEFILE  0
#endif

// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
//
#include "../3rdParty/ply.h"

namespace ospray {
  namespace sg {
    namespace ply {
      using std::string;
      using std::cout;
      using std::endl;

#define FALSE           0
#define TRUE            1

#define X               0
#define Y               1
#define Z               2

      enum {
        FACE_INDICES = 0,
        FACE_RED,
        FACE_GREEN,
        FACE_BLUE
      };

      typedef float Point[3];
      typedef float Vector[3];

      typedef struct Vertex {
        int    id;
        Point  coord;            /* coordinates of vertex */
        Point  normal;            /* normal of vertex */
        unsigned char red;
        unsigned char green;
        unsigned char blue;
        unsigned char nfaces;    /* number of face indices in list */
        int *faces;              /* face index list */
        void *other_props;       /* other properties */
      } Vertex;

      typedef struct Face {
        int id;
        unsigned char nverts;    /* number of vertex indices in list */
        int *verts;              /* vertex index list */
        unsigned char red;
        unsigned char green;
        unsigned char blue;

        void *other_props;       /* other properties */
      } Face;

      PlyProperty vert_props[] = { /* list of property information for a vertex */
        {(char*)"x", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[X]), 0, 0, 0, 0},
        {(char*)"y", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Y]), 0, 0, 0, 0},
        {(char*)"z", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Z]), 0, 0, 0, 0},
        {(char*)"nx", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[X]), 0, 0, 0, 0},
        {(char*)"ny", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Y]), 0, 0, 0, 0},
        {(char*)"nz", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Z]), 0, 0, 0, 0},
        {(char*)"diffuse_red", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,red), 0, 0, 0, 0},
        {(char*)"diffuse_green", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,green), 0, 0, 0, 0},
        {(char*)"diffuse_blue", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,blue), 0, 0, 0, 0},
      };
      enum {
        VTX_X = 0,
        VTX_Y,
        VTX_Z,
        VTX_NX,
        VTX_NY,
        VTX_NZ,
        VTX_RED,
        VTX_GREEN,
        VTX_BLUE
      };

      PlyProperty face_props[] = { /* list of property information for a face */
        {(char*)"vertex_indices", PLY_INT, PLY_INT, offsetof(Face,verts),
         1, PLY_UCHAR, PLY_UCHAR, offsetof(Face,nverts)},
        {(char*)"red", PLY_UCHAR, PLY_UCHAR, offsetof(Face,red), 0, 0, 0, 0},
        {(char*)"green", PLY_UCHAR, PLY_UCHAR, offsetof(Face,green), 0, 0, 0, 0},
        {(char*)"blue", PLY_UCHAR, PLY_UCHAR, offsetof(Face,blue), 0, 0, 0, 0},
      };

      void readFile(const std::string &fileName, std::shared_ptr<sg::TriangleMesh> mesh)
      {
        int nprops;
        PlyProperty **plist;
        float version;
        int vertices = 0;

        int triangles = 0;

        int has_x, has_y, has_z;
        int has_face_red=0; // face colors
        int has_face_green=0; // face colors
        int has_face_blue=0; // face colors
        int has_vertex_red=0; // vertex colors
        int has_vertex_green=0; // vertex colors
        int has_vertex_blue=0; // vertex colors
        int has_nx=0, has_ny=0, has_nz=0;
        int has_fverts=0;

        PlyOtherElems *other_elements = NULL;
        PlyOtherProp *vert_other,*face_other;//,*edge_other;

        char **element_list = NULL;
        int file_type = 0;

        auto pos = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
        auto nor = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>();
        auto idx = createNode("index", "DataVector3i")->nodeAs<DataVector3i>();

        /*** Read in the original PLY object ***/
        const char *filename = fileName.c_str();
        FILE *file;
        bool isPipe = false;

        if (strlen(filename) > 7 && !strcmp(filename+strlen(filename)-7,".ply.gz")) {
#ifdef _WIN32
          THROW_SG_ERROR("#osp:sg:ply: gzipped file not supported yet on Windows");
#else
          isPipe = true;
          char cmd[10000];
          sprintf(cmd,"/usr/bin/gunzip -c %s",filename);
          file = popen(cmd,"r");
#endif
        } else
          file = fopen(filename,"rb");

        if (!file)
          throw std::runtime_error("#osp:sg:ply: could not open '"+fileName+"'");

        int nelems = -1;
        PlyFile *ply  = ply_read (file, &nelems, &element_list);
        ply_get_info (ply, &version, &file_type);

        for (int i=0; i<nelems; i++) {
          int num_elems;

          /* get the description of the first element */
          char *elem_name = element_list[i];
          plist = ply_get_element_description (ply, elem_name, &num_elems, &nprops);

          if (equal_strings ("vertex", elem_name)) {
            /* create a vertex list to hold all the vertices */

            /* set up for getting vertex elements */
            /* verify which properties these vertices have */
            has_x = has_y = has_z = FALSE;
            has_nx = has_ny = has_nz = FALSE;

            for (int j=0; j<nprops; j++) {
              if (equal_strings("x", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_X]);  /* x */
                has_x = TRUE;
              } else if (equal_strings("y", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_Y]);  /* y */
                has_y = TRUE;
              } else if (equal_strings("z", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_Z]);  /* z */
                has_z = TRUE;
              }

              if (equal_strings("nx", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NX]);  /* x */
                has_nx = TRUE;
              } else if (equal_strings("ny", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NY]);  /* y */
                has_ny = TRUE;
              } else if (equal_strings("nz", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_NZ]);  /* z */
                has_nz = TRUE;
              } else if (equal_strings("diffuse_red", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_RED]);  /* z */
                has_vertex_red = TRUE;
              } else if (equal_strings("diffuse_green", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_GREEN]);  /* z */
                has_vertex_green = TRUE;
              } else if (equal_strings("diffuse_blue", plist[j]->name)) {
                ply_get_property (ply, elem_name, &vert_props[VTX_BLUE]);  /* z */
                has_vertex_blue = TRUE;
              }
            }

            vert_other = ply_get_other_properties (ply, elem_name,
                                                   offsetof(Vertex,other_props));

            /* test for necessary properties */
            if ((!has_x) || (!has_y) || (!has_z))
              {
                fprintf(stderr, "Vertices don't have x, y, and z\n");
                exit(-1);
              }

            vertices = num_elems;
            if (has_nx && has_ny && has_nz)
              nor->v.resize(vertices);
            pos->v.resize(vertices);

            /* grab all the vertex elements */
            for (int j=0; j<vertices; j++) {
              Vertex tmp;
              ply_get_element (ply, (void *) &tmp);
              pos->v[j] = vec3f(tmp.coord[0],tmp.coord[1],tmp.coord[2]);
              if (has_nx && has_ny && has_nz)
                nor->v[j] = vec3f(tmp.normal[0],tmp.normal[1],tmp.normal[2]);
            }
          } else if (equal_strings ("face", elem_name)) {

            /* create a list to hold all the face elements */
            cout << "num faces : " << (num_elems) << endl;

            /* set up for getting face elements */
            /* verify which properties these vertices have */
            has_fverts = FALSE;

            for (int j=0; j<nprops; j++) {
              if (equal_strings("vertex_indices", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_INDICES]);/* vertex_indices */
                has_fverts = TRUE;
              } else if (equal_strings("red", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_RED]);/* vertex_indices */
                has_face_red = TRUE;
              } else if (equal_strings("green", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_GREEN]);/* vertex_indices */
                has_face_green = TRUE;
              } else if (equal_strings("blue", plist[j]->name)) {
                ply_get_property(ply, elem_name, &face_props[FACE_BLUE]);/* vertex_indices */
                has_face_blue = TRUE;
              }
            }
            face_other = ply_get_other_properties (ply, elem_name,
                                                   offsetof(Face,other_props));

            /* test for necessary properties */
            if (!has_fverts) {
              fprintf(stderr, "Faces must have vertex indices\n");
              exit(-1);
            }

            triangles = num_elems;
            // numTrisWritten += num_elems;

            /* grab all the face elements */
            Face tmp;
            tmp.verts = NULL;
            tmp.other_props = NULL;
            for (int j=0; j<num_elems; j++)  {
              ply_get_element (ply, (void *) &tmp);
              if (!has_face_blue) {
                tmp.red = tmp.green = tmp.blue = 255;
              }
              if (tmp.nverts == 3) {
                // if (has_face_blue)
                //   material = getMaterial(tmp.red,tmp.green,tmp.blue);;

                vec3i vtx;
                vtx.x = tmp.verts[0]; //builder.addVertex(pos[tmp.verts[0]]);
                vtx.y = tmp.verts[1]; //builder.addVertex(pos[tmp.verts[1]]);
                vtx.z = tmp.verts[2]; //builder.addVertex(pos[tmp.verts[2]]);
                idx->v.push_back(vtx);
              } else {
                PRINT((int)tmp.nverts);
                FATAL("can only read ply files made up of triangles...");
              }
              free(tmp.verts);
              if (tmp.other_props) free(tmp.other_props);
            }
          }
          else {
            other_elements = ply_get_other_element (ply, elem_name, num_elems);
            ply_free_other_elements(other_elements);
          }
        }

        int num_comments;
        char **comments;
        // PlyOtherProp *vert_other,*face_other;//,*edge_other;

        int num_obj_info;
        char **obj_info;

        comments = ply_get_comments (ply, &num_comments);
        obj_info = ply_get_obj_info (ply, &num_obj_info);

        ply_close (ply);

        for (int i=0;i<ply->nelems;i++) {
          if (ply->elems[i]) continue;
          PlyElement *e = ply->elems[i];
          FREE(e->name);
          FREE(e->store_prop);
          if (e->props) {
            for (int j=0;j<e->nprops;j++) {
              PlyProperty *p = e->props[j];
              if (!e) continue;
              FREE(p->name);
              FREE(p);
            }
            FREE(e->props);
          }
          FREE(e);
        }

        free(ply->elems);

        mesh->add(idx);
        mesh->add(pos);
        if (!nor->v.empty())
          mesh->add(nor);
      }

    } // ::ospray::sg::ply

    void importPLY(std::shared_ptr<Node> &world, const FileName &fileName)
    {
      auto mesh = sg::createNode(fileName.name(),
                                 "TriangleMesh")->nodeAs<TriangleMesh>();
      ply::readFile(fileName.str(), mesh);
      world->add(mesh);
    }

  } // ::ospray::sg
} // ::ospray
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/video/video_quality_test.h"

namespace webrtc {
namespace flags {

// Flags common with video loopback, with different default values.
DEFINE_int32(width, 1850, "Video width (crops source).");
size_t Width() {
  return static_cast<size_t>(FLAGS_width);
}

DEFINE_int32(height, 1110, "Video height (crops source).");
size_t Height() {
  return static_cast<size_t>(FLAGS_height);
}

DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
  return static_cast<int>(FLAGS_fps);
}

DEFINE_int32(min_bitrate, 50, "Call and stream min bitrate in kbps.");
int MinBitrateKbps() {
  return static_cast<int>(FLAGS_min_bitrate);
}

DEFINE_int32(start_bitrate, 200, "Call start bitrate in kbps.");
int StartBitrateKbps() {
  return static_cast<int>(FLAGS_start_bitrate);
}

DEFINE_int32(target_bitrate, 2000, "Stream target bitrate in kbps.");
int TargetBitrateKbps() {
  return static_cast<int>(FLAGS_target_bitrate);
}

DEFINE_int32(max_bitrate, 2000, "Call and stream max bitrate in kbps.");
int MaxBitrateKbps() {
  return static_cast<int>(FLAGS_max_bitrate);
}

DEFINE_int32(num_temporal_layers, 2, "Number of temporal layers to use.");
int NumTemporalLayers() {
  return static_cast<int>(FLAGS_num_temporal_layers);
}

// Flags common with video loopback, with equal default values.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
  return static_cast<std::string>(FLAGS_codec);
}

DEFINE_int32(selected_tl,
             -1,
             "Temporal layer to show or analyze. -1 to disable filtering.");
int SelectedTL() {
  return static_cast<int>(FLAGS_selected_tl);
}

DEFINE_int32(
    duration,
    0,
    "Duration of the test in seconds. If 0, rendered will be shown instead.");
int DurationSecs() {
  return static_cast<int>(FLAGS_duration);
}

DEFINE_string(output_filename, "", "Target graph data filename.");
std::string OutputFilename() {
  return static_cast<std::string>(FLAGS_output_filename);
}

DEFINE_string(graph_title,
              "",
              "If empty, title will be generated automatically.");
std::string GraphTitle() {
  return static_cast<std::string>(FLAGS_graph_title);
}

DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
  return static_cast<int>(FLAGS_loss_percent);
}

DEFINE_int32(link_capacity,
             0,
             "Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacityKbps() {
  return static_cast<int>(FLAGS_link_capacity);
}

DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
  return static_cast<int>(FLAGS_queue_size);
}

DEFINE_int32(avg_propagation_delay_ms,
             0,
             "Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
  return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}

DEFINE_int32(std_propagation_delay_ms,
             0,
             "Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
  return static_cast<int>(FLAGS_std_propagation_delay_ms);
}

DEFINE_int32(selected_stream, 0, "ID of the stream to show or analyze.");
int SelectedStream() {
  return static_cast<int>(FLAGS_selected_stream);
}

DEFINE_int32(num_spatial_layers, 1, "Number of spatial layers to use.");
int NumSpatialLayers() {
  return static_cast<int>(FLAGS_num_spatial_layers);
}

DEFINE_int32(selected_sl,
             -1,
             "Spatial layer to show or analyze. -1 to disable filtering.");
int SelectedSL() {
  return static_cast<int>(FLAGS_selected_sl);
}

DEFINE_string(stream0,
              "",
              "Comma separated values describing VideoStream for stream #0.");
std::string Stream0() {
  return static_cast<std::string>(FLAGS_stream0);
}

DEFINE_string(stream1,
              "",
              "Comma separated values describing VideoStream for stream #1.");
std::string Stream1() {
  return static_cast<std::string>(FLAGS_stream1);
}

DEFINE_string(sl0,
              "",
              "Comma separated values describing SpatialLayer for layer #0.");
std::string SL0() {
  return static_cast<std::string>(FLAGS_sl0);
}

DEFINE_string(sl1,
              "",
              "Comma separated values describing SpatialLayer for layer #1.");
std::string SL1() {
  return static_cast<std::string>(FLAGS_sl1);
}

DEFINE_bool(logs, false, "print logs to stderr");

DEFINE_bool(send_side_bwe, true, "Use send-side bandwidth estimation");

DEFINE_bool(allow_reordering, false, "Allow packet reordering to occur");

DEFINE_string(
    force_fieldtrials,
    "",
    "Field trials control experimental feature code which can be forced. "
    "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
    " will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
    "trials are separated by \"/\"");

// Screenshare-specific flags.
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrateKbps() {
  return FLAGS_min_transmit_bitrate;
}

DEFINE_int32(slide_change_interval,
             10,
             "Interval (in seconds) between simulated slide changes.");
int SlideChangeInterval() {
  return static_cast<int>(FLAGS_slide_change_interval);
}

DEFINE_int32(
    scroll_duration,
    0,
    "Duration (in seconds) during which a slide will be scrolled into place.");
int ScrollDuration() {
  return static_cast<int>(FLAGS_scroll_duration);
}

}  // namespace flags

void Loopback() {
  FakeNetworkPipe::Config pipe_config;
  pipe_config.loss_percent = flags::LossPercent();
  pipe_config.link_capacity_kbps = flags::LinkCapacityKbps();
  pipe_config.queue_length_packets = flags::QueueSize();
  pipe_config.queue_delay_ms = flags::AvgPropagationDelayMs();
  pipe_config.delay_standard_deviation_ms = flags::StdPropagationDelayMs();
  pipe_config.allow_reordering = flags::FLAGS_allow_reordering;

  Call::Config::BitrateConfig call_bitrate_config;
  call_bitrate_config.min_bitrate_bps = flags::MinBitrateKbps() * 1000;
  call_bitrate_config.start_bitrate_bps = flags::StartBitrateKbps() * 1000;
  call_bitrate_config.max_bitrate_bps = flags::MaxBitrateKbps() * 1000;

  VideoQualityTest::Params params{
      {flags::Width(), flags::Height(), flags::Fps(),
       flags::MinBitrateKbps() * 1000, flags::TargetBitrateKbps() * 1000,
       flags::MaxBitrateKbps() * 1000, flags::Codec(),
       flags::NumTemporalLayers(), flags::SelectedTL(),
       flags::MinTransmitBitrateKbps() * 1000, call_bitrate_config,
       flags::FLAGS_send_side_bwe},
      {},  // Video specific.
      {true, flags::SlideChangeInterval(), flags::ScrollDuration()},
      {"screenshare", 0.0, 0.0, flags::DurationSecs(), flags::OutputFilename(),
       flags::GraphTitle()},
      pipe_config,
      flags::FLAGS_logs};

  std::vector<std::string> stream_descriptors;
  stream_descriptors.push_back(flags::Stream0());
  stream_descriptors.push_back(flags::Stream1());
  std::vector<std::string> SL_descriptors;
  SL_descriptors.push_back(flags::SL0());
  SL_descriptors.push_back(flags::SL1());
  VideoQualityTest::FillScalabilitySettings(
      &params, stream_descriptors, flags::SelectedStream(),
      flags::NumSpatialLayers(), flags::SelectedSL(), SL_descriptors);

  VideoQualityTest test;
  if (flags::DurationSecs()) {
    test.RunWithAnalyzer(params);
  } else {
    test.RunWithVideoRenderer(params);
  }
}
}  // namespace webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  webrtc::test::InitFieldTrialsFromString(
      webrtc::flags::FLAGS_force_fieldtrials);
  webrtc::test::RunTest(webrtc::Loopback);
  return 0;
}
<commit_msg>Update default parameters in screenshare_loopback test<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/video/video_quality_test.h"

namespace webrtc {
namespace flags {

// Flags common with video loopback, with different default values.
DEFINE_int32(width, 1850, "Video width (crops source).");
size_t Width() {
  return static_cast<size_t>(FLAGS_width);
}

DEFINE_int32(height, 1110, "Video height (crops source).");
size_t Height() {
  return static_cast<size_t>(FLAGS_height);
}

DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
  return static_cast<int>(FLAGS_fps);
}

DEFINE_int32(min_bitrate, 50, "Call and stream min bitrate in kbps.");
int MinBitrateKbps() {
  return static_cast<int>(FLAGS_min_bitrate);
}

DEFINE_int32(start_bitrate,
             Call::Config::kDefaultStartBitrateBps / 1000,
             "Call start bitrate in kbps.");
int StartBitrateKbps() {
  return static_cast<int>(FLAGS_start_bitrate);
}

DEFINE_int32(target_bitrate, 200, "Stream target bitrate in kbps.");
int TargetBitrateKbps() {
  return static_cast<int>(FLAGS_target_bitrate);
}

DEFINE_int32(max_bitrate, 2000, "Call and stream max bitrate in kbps.");
int MaxBitrateKbps() {
  return static_cast<int>(FLAGS_max_bitrate);
}

DEFINE_int32(num_temporal_layers, 2, "Number of temporal layers to use.");
int NumTemporalLayers() {
  return static_cast<int>(FLAGS_num_temporal_layers);
}

// Flags common with video loopback, with equal default values.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
  return static_cast<std::string>(FLAGS_codec);
}

DEFINE_int32(selected_tl,
             -1,
             "Temporal layer to show or analyze. -1 to disable filtering.");
int SelectedTL() {
  return static_cast<int>(FLAGS_selected_tl);
}

DEFINE_int32(
    duration,
    0,
    "Duration of the test in seconds. If 0, rendered will be shown instead.");
int DurationSecs() {
  return static_cast<int>(FLAGS_duration);
}

DEFINE_string(output_filename, "", "Target graph data filename.");
std::string OutputFilename() {
  return static_cast<std::string>(FLAGS_output_filename);
}

DEFINE_string(graph_title,
              "",
              "If empty, title will be generated automatically.");
std::string GraphTitle() {
  return static_cast<std::string>(FLAGS_graph_title);
}

DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
  return static_cast<int>(FLAGS_loss_percent);
}

DEFINE_int32(link_capacity,
             0,
             "Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacityKbps() {
  return static_cast<int>(FLAGS_link_capacity);
}

DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
  return static_cast<int>(FLAGS_queue_size);
}

DEFINE_int32(avg_propagation_delay_ms,
             0,
             "Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
  return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}

DEFINE_int32(std_propagation_delay_ms,
             0,
             "Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
  return static_cast<int>(FLAGS_std_propagation_delay_ms);
}

DEFINE_int32(selected_stream, 0, "ID of the stream to show or analyze.");
int SelectedStream() {
  return static_cast<int>(FLAGS_selected_stream);
}

DEFINE_int32(num_spatial_layers, 1, "Number of spatial layers to use.");
int NumSpatialLayers() {
  return static_cast<int>(FLAGS_num_spatial_layers);
}

DEFINE_int32(selected_sl,
             -1,
             "Spatial layer to show or analyze. -1 to disable filtering.");
int SelectedSL() {
  return static_cast<int>(FLAGS_selected_sl);
}

DEFINE_string(stream0,
              "",
              "Comma separated values describing VideoStream for stream #0.");
std::string Stream0() {
  return static_cast<std::string>(FLAGS_stream0);
}

DEFINE_string(stream1,
              "",
              "Comma separated values describing VideoStream for stream #1.");
std::string Stream1() {
  return static_cast<std::string>(FLAGS_stream1);
}

DEFINE_string(sl0,
              "",
              "Comma separated values describing SpatialLayer for layer #0.");
std::string SL0() {
  return static_cast<std::string>(FLAGS_sl0);
}

DEFINE_string(sl1,
              "",
              "Comma separated values describing SpatialLayer for layer #1.");
std::string SL1() {
  return static_cast<std::string>(FLAGS_sl1);
}

DEFINE_bool(logs, false, "print logs to stderr");

DEFINE_bool(send_side_bwe, true, "Use send-side bandwidth estimation");

DEFINE_bool(allow_reordering, false, "Allow packet reordering to occur");

DEFINE_string(
    force_fieldtrials,
    "",
    "Field trials control experimental feature code which can be forced. "
    "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
    " will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
    "trials are separated by \"/\"");

// Screenshare-specific flags.
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrateKbps() {
  return FLAGS_min_transmit_bitrate;
}

DEFINE_int32(slide_change_interval,
             10,
             "Interval (in seconds) between simulated slide changes.");
int SlideChangeInterval() {
  return static_cast<int>(FLAGS_slide_change_interval);
}

DEFINE_int32(
    scroll_duration,
    0,
    "Duration (in seconds) during which a slide will be scrolled into place.");
int ScrollDuration() {
  return static_cast<int>(FLAGS_scroll_duration);
}

}  // namespace flags

void Loopback() {
  FakeNetworkPipe::Config pipe_config;
  pipe_config.loss_percent = flags::LossPercent();
  pipe_config.link_capacity_kbps = flags::LinkCapacityKbps();
  pipe_config.queue_length_packets = flags::QueueSize();
  pipe_config.queue_delay_ms = flags::AvgPropagationDelayMs();
  pipe_config.delay_standard_deviation_ms = flags::StdPropagationDelayMs();
  pipe_config.allow_reordering = flags::FLAGS_allow_reordering;

  Call::Config::BitrateConfig call_bitrate_config;
  call_bitrate_config.min_bitrate_bps = flags::MinBitrateKbps() * 1000;
  call_bitrate_config.start_bitrate_bps = flags::StartBitrateKbps() * 1000;
  call_bitrate_config.max_bitrate_bps = flags::MaxBitrateKbps() * 1000;

  VideoQualityTest::Params params{
      {flags::Width(), flags::Height(), flags::Fps(),
       flags::MinBitrateKbps() * 1000, flags::TargetBitrateKbps() * 1000,
       flags::MaxBitrateKbps() * 1000, flags::Codec(),
       flags::NumTemporalLayers(), flags::SelectedTL(),
       flags::MinTransmitBitrateKbps() * 1000, call_bitrate_config,
       flags::FLAGS_send_side_bwe},
      {},  // Video specific.
      {true, flags::SlideChangeInterval(), flags::ScrollDuration()},
      {"screenshare", 0.0, 0.0, flags::DurationSecs(), flags::OutputFilename(),
       flags::GraphTitle()},
      pipe_config,
      flags::FLAGS_logs};

  std::vector<std::string> stream_descriptors;
  stream_descriptors.push_back(flags::Stream0());
  stream_descriptors.push_back(flags::Stream1());
  std::vector<std::string> SL_descriptors;
  SL_descriptors.push_back(flags::SL0());
  SL_descriptors.push_back(flags::SL1());
  VideoQualityTest::FillScalabilitySettings(
      &params, stream_descriptors, flags::SelectedStream(),
      flags::NumSpatialLayers(), flags::SelectedSL(), SL_descriptors);

  VideoQualityTest test;
  if (flags::DurationSecs()) {
    test.RunWithAnalyzer(params);
  } else {
    test.RunWithVideoRenderer(params);
  }
}
}  // namespace webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  webrtc::test::InitFieldTrialsFromString(
      webrtc::flags::FLAGS_force_fieldtrials);
  webrtc::test::RunTest(webrtc::Loopback);
  return 0;
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>

using namespace shl;
using namespace std;

class TestSource : public GrammarSource {
public:
    TestSource();
    virtual const std::string load_data(const std::string& grammar_name) const;
    virtual const std::vector<std::string> list_grammars() const;
private:
    string ruby;
    string html;
    string php;
};

TestSource::TestSource() {
    ruby = load_string("fixture/ruby.json");
    html = load_string("fixture/html.json");
    php = load_string("fixture/php.json");
}

const std::string TestSource::load_data(const std::string& grammar_name) const {
    if ( grammar_name == "text.html.basic" ) return html;
    if ( grammar_name == "source.ruby" ) return ruby;
    if ( grammar_name == "text.html.php" ) return php;

    return "";
}

const std::vector<std::string> TestSource::list_grammars() const {
    vector<string> list = {"text.html.basic", "source.ruby", "text.html.php"};

    return list;
}

TEST_CASE("GrammarRegistry Test") {
    SECTION("can load all grammar presented by the GrammarSource") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        REQUIRE( registry.contain_grammar("text.html.basic") );
        REQUIRE( registry.contain_grammar("source.ruby") );
    }

    SECTION("all include is resolved") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        Grammar* html_grammar_ptr  = &registry.get_grammar("text.html.basic");
        Grammar& grammar = registry.get_grammar("source.ruby");

        REQUIRE( grammar.patterns.size() == 88 );
        REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.name == "source.ruby" );
        REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.ptr == &grammar );

        REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.name == "text.html.basic" );
        REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.ptr == html_grammar_ptr );
    }

    SECTION("all injections is loaded") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        Grammar& php = registry.get_grammar("text.html.php");
        REQUIRE( !php.empty() );
        REQUIRE( !php.injections.empty() );
    }
}
<commit_msg>test local repos are loaded. injections are all loaded<commit_after>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>

using namespace shl;
using namespace std;

class TestSource : public GrammarSource {
public:
    TestSource();
    virtual const std::string load_data(const std::string& grammar_name) const;
    virtual const std::vector<std::string> list_grammars() const;
private:
    string ruby;
    string html;
    string php;
};

TestSource::TestSource() {
    ruby = load_string("fixture/ruby.json");
    html = load_string("fixture/html.json");
    php = load_string("fixture/php.json");
}

const std::string TestSource::load_data(const std::string& grammar_name) const {
    if ( grammar_name == "text.html.basic" ) return html;
    if ( grammar_name == "source.ruby" ) return ruby;
    if ( grammar_name == "text.html.php" ) return php;

    return "";
}

const std::vector<std::string> TestSource::list_grammars() const {
    vector<string> list = {"text.html.basic", "source.ruby", "text.html.php"};

    return list;
}

TEST_CASE("GrammarRegistry Test") {
    SECTION("can load all grammar presented by the GrammarSource") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        REQUIRE( registry.contain_grammar("text.html.basic") );
        REQUIRE( registry.contain_grammar("source.ruby") );
    }

    SECTION("all include is resolved") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        Grammar* html_grammar_ptr  = &registry.get_grammar("text.html.basic");
        Grammar& grammar = registry.get_grammar("source.ruby");

        REQUIRE( grammar.patterns.size() == 88 );
        REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.name == "source.ruby" );
        REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.ptr == &grammar );

        REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.name == "text.html.basic" );
        REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.ptr == html_grammar_ptr );
    }

    SECTION("local repository is resolved") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        Grammar& php = registry.get_grammar("text.html.php");
        REQUIRE( !php.empty() );
        REQUIRE( !php.repository.empty() );
        REQUIRE( !php.repository["heredoc"].repository.empty() );
        REQUIRE( php.repository["heredoc"].patterns[0].patterns[0].include.ptr == &php.repository["heredoc"].repository["heredoc_interior"] );
    }

    SECTION("all injections is loaded") {
        shared_ptr<GrammarSource> source(new TestSource());
        GrammarRegistry registry(source);

        Grammar& php = registry.get_grammar("text.html.php");
        REQUIRE( !php.empty() );
        REQUIRE( !php.injections.empty() );
        REQUIRE( !php.repository["heredoc"].patterns[0].injections.empty() );
    }
}
<|endoftext|>