Example #1
0
void DS::Stream::writeSafeString(const String& value, DS::StringType format)
{
    if (format == e_StringUTF16) {
        StringBuffer<chr16_t> buffer = value.toUtf16();
        uint16_t length = value.length() & 0x0FFF;
        chr16_t* data = new chr16_t[length];
        memcpy(data, buffer.data(), length * sizeof(chr16_t));
        for (uint16_t i=0; i<length; ++i)
            data[i] = ~data[i];
        write<uint16_t>(length | 0xF000);
        writeBytes(data, length * sizeof(chr16_t));
        write<chr16_t>(0);
        delete[] data;
    } else {
        StringBuffer<chr8_t> buffer = (format == e_StringUTF8) ? value.toUtf8()
                                                               : value.toRaw();
        uint16_t length = value.length() & 0x0FFF;
        chr8_t* data = new chr8_t[length];
        memcpy(data, buffer.data(), length * sizeof(chr8_t));
        for (uint16_t i=0; i<length; ++i)
            data[i] = ~data[i];
        write<uint16_t>(length | 0xF000);
        writeBytes(data, length * sizeof(chr8_t));
        delete[] data;
    }
}
Example #2
0
void DS::Stream::writeString(const String& value, DS::StringType format)
{
    if (format == e_StringUTF16) {
        StringBuffer<chr16_t> buffer = value.toUtf16();
        writeBytes(buffer.data(), buffer.length());
    } else {
        StringBuffer<chr8_t> buffer = (format == e_StringUTF8) ? value.toUtf8()
                                                               : value.toRaw();
        writeBytes(buffer.data(), buffer.length());
    }
}
Example #3
0
DS::ShaHash DS::BuggyHashPassword(const String& username, const String& password)
{
    StringBuffer<chr16_t> wuser = username.toUtf16();
    StringBuffer<chr16_t> wpass = password.toUtf16();
    chr16_t* buffer = new chr16_t[wuser.length() + wpass.length()];
    memcpy(buffer, wpass.data(), wpass.length() * sizeof(chr16_t));
    memcpy(buffer + wpass.length(), wuser.data(), wuser.length() * sizeof(chr16_t));
    buffer[wpass.length() - 1] = 0;
    buffer[wpass.length() + wuser.length() - 1] = 0;
    ShaHash hash = ShaHash::Sha0(buffer, (wuser.length() + wpass.length()) * sizeof(chr16_t));
    delete[] buffer;
    return hash;
}
Example #4
0
void serial_helper_func<A,String>::g(SerializerWriter &ar,type &val)
{
	const char *p;
	intarr_t n;

	if(ar.flags.get(Serializer::STRCVT_UTF8))
	{
		StringBuffer<char> sb;
		if(!IConv::ansi_to_utf8(sb,val.c_str(),val.size()))
		{
			ar.errstr("invalid string");
			return;
		}
		p=sb.data();
		n=(intarr_t)sb.size();
	}
	else
	{
		p=val.c_str();
		n=(intarr_t)val.size();
	}

	serial_pod<A,intarr_t>::g(ar,n);
	if(n>0)
	{
		ar.send((char *)p,n);
	}

}
Example #5
0
inline void String::_do_assign(const wchar_t* p1,uintptr_t n)
{
	StringBuffer<char> sb;
	IConv::unicode_to_utf8(sb,p1,n);

	_do_assign(sb.data(),sb.size());
}
Example #6
0
gcc_const
static inline StringBuffer<TCHAR, 32>
FormatUserAltitude(double value)
{
  StringBuffer<TCHAR, 32> buffer;
  FormatUserAltitude(value, buffer.data());
  return buffer;
}
Example #7
0
gcc_const
static inline StringBuffer<TCHAR, 32>
FormatUserTaskSpeed(double value, bool precision=true)
{
  StringBuffer<TCHAR, 32> buffer;
  FormatUserTaskSpeed(value, buffer.data(), true, precision);
  return buffer;
}
Example #8
0
gcc_const
static inline StringBuffer<TCHAR, 32>
FormatUserDistanceSmart(double value)
{
  StringBuffer<TCHAR, 32> buffer;
  FormatUserDistanceSmart(value, buffer.data());
  return buffer;
}
Example #9
0
gcc_const
static inline StringBuffer<TCHAR, 8>
FormatLocalTimeHHMM(int time, RoughTimeDelta utc_offset)
{
  StringBuffer<TCHAR, 8> buffer;
  FormatLocalTimeHHMM(buffer.data(), time, utc_offset);
  return buffer;
}
Example #10
0
gcc_const
static inline StringBuffer<TCHAR, 16>
FormatAngleDelta(Angle value)
{
  StringBuffer<TCHAR, 16> buffer;
  FormatAngleDelta(buffer.data(), buffer.capacity(), value);
  return buffer;
}
Example #11
0
gcc_const
static inline StringBuffer<TCHAR, 16>
FormatBearing(unsigned degrees_value)
{
  StringBuffer<TCHAR, 16> buffer;
  FormatBearing(buffer.data(), buffer.capacity(), degrees_value);
  return buffer;
}
Example #12
0
gcc_const
static inline StringBuffer<TCHAR, 8>
FormatSignedTimeHHMM(int time)
{
  StringBuffer<TCHAR, 8> buffer;
  FormatSignedTimeHHMM(buffer.data(), time);
  return buffer;
}
Example #13
0
bool HttpProtocol::ProxyRequest(Transport *transport, bool force,
                                const std::string &url,
                                int &code, std::string &error,
                                StringBuffer &response,
                                HeaderMap *extraHeaders /* = NULL */) {
  assert(transport);
  if (transport->headersSent()) {
    raise_warning("Cannot proxy request - headers already sent");
    return false;
  }

  HeaderMap requestHeaders;
  transport->getHeaders(requestHeaders);
  if (extraHeaders) {
    for (HeaderMap::const_iterator iter = extraHeaders->begin();
         iter != extraHeaders->end(); ++iter) {
      std::vector<std::string> &values = requestHeaders[iter->first];
      values.insert(values.end(), iter->second.begin(), iter->second.end());
    }
  }

  int size = 0;
  const char *data = nullptr;
  if (transport->getMethod() == Transport::Method::POST) {
    data = (const char *)transport->getPostData(size);
  }

  std::vector<String> responseHeaders;
  HttpClient http;
  code = http.request(transport->getMethodName(),
                      url.c_str(), data, size, response, &requestHeaders,
                      &responseHeaders);

  if (code == 0) {
    if (!force) return false; // so we can retry
    Logger::Error("Unable to proxy %s: %s", url.c_str(),
                  http.getLastError().c_str());
    error = http.getLastError();
    return true;
  }

  for (unsigned int i = 0; i < responseHeaders.size(); i++) {
    String &header = responseHeaders[i];
    if (header.find(":") != String::npos &&
        header.find("Content-Length: ") != 0 &&
        header.find("Client-Transfer-Encoding: ") != 0 &&
        header.find("Transfer-Encoding: ") != 0 &&
        header.find("Connection: ") != 0) {
      transport->addHeader(header.data());
    }
  }
  const char* respData = response.data();
  if (!respData) {
    respData = "";
  }
  Logger::Verbose("Response code was %d when proxying %s", code, url.c_str());
  return true;
}
Example #14
0
static inline bool
TextEntryDialog(StringBuffer<TCHAR, N> &text,
                const TCHAR *caption,
                bool default_shift_state)
{
  AllowedCharacters accb=AllowedCharacters();
  return TextEntryDialog(text.data(), text.capacity(),
                         caption, accb, default_shift_state);
}
Example #15
0
gcc_const
static inline StringBuffer<TCHAR, 64>
FormatTimespanSmart(int timespan, unsigned max_tokens = 1,
                    const TCHAR *separator = _T(" "))
{
  StringBuffer<TCHAR, 64> buffer;
  FormatTimespanSmart(buffer.data(), timespan, max_tokens, separator);
  return buffer;
}
Example #16
0
gcc_pure
static inline StringBuffer<TCHAR, 32>
FormatGeoPoint(const GeoPoint &location, CoordinateFormat format,
               TCHAR separator = _T(' '))
{
  StringBuffer<TCHAR, 32> buffer;
  auto result = FormatGeoPoint(location, buffer.data(), buffer.capacity(),
                               format, separator);
  if (result == nullptr)
    buffer.clear();
  return buffer;
}
Example #17
0
bool HttpProtocol::PrepareCookieVariable(Array& cookie,
        Transport *transport) {

    string cookie_data = transport->getHeader("Cookie");
    if (!cookie_data.empty()) {
        StringBuffer sb;
        sb.append(cookie_data);
        DecodeCookies(cookie, (char*)sb.data());
        return true;
    } else {
        return false;
    }
}
Example #18
0
uint32_t DS::FileManifest::encodeToStream(DS::Stream* stream)
{
    uint32_t start = stream->tell();

    for (auto it = m_files.begin(); it != m_files.end(); ++it) {
        StringBuffer<chr16_t> wstrbuf = (*it)->m_filename.toUtf16();
        stream->writeBytes(wstrbuf.data(), wstrbuf.length() * sizeof(chr16_t));
        stream->write<chr16_t>(0);

        wstrbuf = (*it)->m_downloadName.toUtf16();
        stream->writeBytes(wstrbuf.data(), wstrbuf.length() * sizeof(chr16_t));
        stream->write<chr16_t>(0);

        stream->writeBytes((*it)->m_fileHash, 32 * sizeof(chr16_t));
        stream->write<chr16_t>(0);

        stream->writeBytes((*it)->m_downloadHash, 32 * sizeof(chr16_t));
        stream->write<chr16_t>(0);

        stream->write<uint16_t>((*it)->m_fileSize >> 16);
        stream->write<uint16_t>((*it)->m_fileSize & 0xFFFF);
        stream->write<uint16_t>(0);

        stream->write<uint16_t>((*it)->m_downloadSize >> 16);
        stream->write<uint16_t>((*it)->m_downloadSize & 0xFFFF);
        stream->write<uint16_t>(0);

        stream->write<uint16_t>((*it)->m_flags >> 16);
        stream->write<uint16_t>((*it)->m_flags & 0xFFFF);
        stream->write<uint16_t>(0);
    }
    stream->write<uint16_t>(0);

    DS_DASSERT((stream->tell() - start) % sizeof(chr16_t) == 0);
    return (stream->tell() - start) / sizeof(chr16_t);
}
Example #19
0
void XDebugServer::sendMessage(xdebug_xml_node& xml) {
  auto const message = xdebug_xml_return_node(&xml);
  auto const message_len = message.size() + sizeof(XML_MSG_HEADER) - 1;

  log("-> %s\n\n", message.data());
  logFlush();

  StringBuffer buf;
  buf.append(static_cast<int64_t>(message_len));
  buf.append('\0');
  buf.append(XML_MSG_HEADER);
  buf.append(message);
  buf.append('\0');

  write(m_socket, buf.data(), buf.size());
  return;
}
Example #20
0
void XDebugServer::sendMessage(xdebug_xml_node& xml) {
  // Convert xml to an xdebug_str.
  xdebug_str xml_message = {0, 0, nullptr};
  xdebug_xml_return_node(&xml, &xml_message);
  size_t msg_len = xml_message.l + sizeof(XML_MSG_HEADER) - 1;

  // Log the message
  log("-> %s\n\n", xml_message.d);
  logFlush();

  StringBuffer buf;
  buf.append(static_cast<int64_t>(msg_len));
  buf.append('\0');
  buf.append(XML_MSG_HEADER);
  buf.append(xml_message.d);
  buf.append('\0');

  write(m_socket, buf.data(), buf.size());
  return;
}
Example #21
0
bool HttpRequestHandler::handleProxyRequest(Transport *transport, bool force) {
  string url = RuntimeOption::ProxyOrigin + transport->getServerObject();

  int code = 0;
  std::string error;
  StringBuffer response;
  if (!HttpProtocol::ProxyRequest(transport, force, url, code, error,
                                  response)) {
    return false;
  }
  if (code == 0) {
    transport->sendString(error, 500, false, false, "handleProxyRequest");
    return true;
  }

  const char* respData = response.data();
  if (!respData) {
    respData = "";
  }
  transport->sendRaw((void*)respData, response.size(), code);
  return true;
}
Example #22
0
static void json_create_zval(Variant &z, StringBuffer &buf, int type) {
  switch (type) {
  case KindOfInt64:
    {
      const char *p = buf.data();
      ASSERT(p);
      if (p == NULL) {
        z = 0LL;
        return;
      }

      bool neg = (buf.charAt(0) == '-');

      int len = buf.size();
      if (neg) len--;
      if (len >= MAX_LENGTH_OF_LONG - 1) {
        if (len == MAX_LENGTH_OF_LONG - 1) {
          int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits);
          if (!(cmp < 0 || (cmp == 0 && neg))) {
            z = strtod(p, NULL);
            return;
          }
        } else {
          z = strtod(p, NULL);
          return;
        }
      }
      z = strtoll(buf.data(), NULL, 10);
    }
    break;
  case KindOfDouble:
    z = buf.data() ? strtod(buf.data(), NULL) : 0.0;
    break;
  case KindOfString:
    z = buf.detach();
    buf.reset();
    break;
  case KindOfBoolean:
    z = (buf.data() && (*buf.data() == 't'));
    break;
  default:
    z = null;
    break;
  }
}
Example #23
0
bool TestServer::TestHttpClient() {
  ServerPtr server;
  for (s_server_port = PORT_MIN; s_server_port <= PORT_MAX; s_server_port++) {
    try {
      server = ServerPtr(new TypedServer<LibEventServer, EchoHandler>
                         ("127.0.0.1", s_server_port, 50, -1));
      server->start();
      break;
    } catch (FailedToListenException e) {
      if (s_server_port == PORT_MAX) throw;
    }
  }

  HeaderMap headers;
  headers["Cookie"].push_back("c1=v1;c2=v2;");
  headers["Cookie"].push_back("c3=v3;c4=v4;");
  string url = "http://127.0.0.1:" + lexical_cast<string>(s_server_port) +
    "/echo?name=value";

  for (int i = 0; i < 10; i++) {
    HttpClient http;
    StringBuffer response;
    vector<String> responseHeaders;
    int code = http.get(url.c_str(), response, &headers, &responseHeaders);
    VS(code, 200);
    VS(response.data(),
       ("\nGET param: name = value"
        "\nHeader: Accept"
        "\n0: */*"
        "\nHeader: Cookie"
        "\n0: c1=v1;c2=v2;"
        "\n1: c3=v3;c4=v4;"
        "\nHeader: Host"
        "\n0: 127.0.0.1:" + lexical_cast<string>(s_server_port)).c_str());

    bool found = false;
    for (unsigned int i = 0; i < responseHeaders.size(); i++) {
      if (responseHeaders[i] == "Custom: blah") {
        found = true;
      }
    }
    VERIFY(found);
  }
  for (int i = 0; i < 10; i++) {
    HttpClient http;
    StringBuffer response;
    vector<String> responseHeaders;
    int code = http.post(url.c_str(), "postdata", 8, response, &headers,
                         &responseHeaders);
    VS(code, 200);
    VS(response.data(),
       ("\nGET param: name = value"
        "\nPOST data: postdata"
        "\nHeader: Accept"
        "\n0: */*"
        "\nHeader: Content-Length"
        "\n0: 8"
        "\nHeader: Content-Type"
        "\n0: application/x-www-form-urlencoded"
        "\nHeader: Cookie"
        "\n0: c1=v1;c2=v2;"
        "\n1: c3=v3;c4=v4;"
        "\nHeader: Host"
        "\n0: 127.0.0.1:" + lexical_cast<string>(s_server_port)).c_str());

    bool found = false;
    for (unsigned int i = 0; i < responseHeaders.size(); i++) {
      if (responseHeaders[i] == "Custom: blah") {
        found = true;
      }
    }
    VERIFY(found);
  }

  server->stop();
  server->waitForEnd();
  return Count(true);
}
bool AdminRequestHandler::handleStatsRequest(const std::string &cmd,
                                             Transport *transport) {
  if (cmd == "stats-on") {
    RuntimeOption::EnableStats = true;
    transport->sendString("OK\n");
    return true;
  }
  if (cmd == "stats-off") {
    RuntimeOption::EnableStats = false;
    transport->sendString("OK\n");
    return true;
  }
  if (cmd == "stats-clear") {
    ServerStats::Clear();
    transport->sendString("OK\n");
    return true;
  }

  if (cmd == "stats-web") {
    return toggle_switch(transport, RuntimeOption::EnableWebStats);
  }
  if (cmd == "stats-mem") {
    toggle_switch(transport, RuntimeOption::EnableMemoryStats);
    return true;
  }
  if (cmd == "stats-malloc") {
    toggle_switch(transport, RuntimeOption::EnableMallocStats);
    LeakDetectable::EnableMallocStats(RuntimeOption::EnableMallocStats);
    return true;
  }
  if (cmd == "stats-apc") {
    return toggle_switch(transport, RuntimeOption::EnableAPCStats);
  }
  if (cmd == "stats-apc-key") {
    return toggle_switch(transport, RuntimeOption::EnableAPCKeyStats);
  }
  if (cmd == "stats-mcc") {
    return toggle_switch(transport, RuntimeOption::EnableMemcacheStats);
  }
  if (cmd == "stats-sql") {
    return toggle_switch(transport, RuntimeOption::EnableSQLStats);
  }
  if (cmd == "stats-mutex") {
    int sampling = transport->getIntParam("sampling");
    if (sampling > 0) {
      LockProfiler::s_profile_sampling = sampling;
    }
    return toggle_switch(transport, LockProfiler::s_profile);
  }

  if (cmd == "stats.keys") {
    int64 from = transport->getInt64Param("from");
    int64 to = transport->getInt64Param("to");
    string out;
    ServerStats::GetKeys(out, from, to);
    transport->sendString(out);
    return true;
  }
  if (cmd == "stats.xml") {
    return send_report(transport, ServerStats::XML, "application/xml");
  }
  if (cmd == "stats.json") {
    return send_report(transport, ServerStats::JSON, "application/json");
  }
  if (cmd == "stats.kvp") {
    return send_report(transport, ServerStats::KVP, "text/plain");
  }
  if (cmd == "stats.html" || cmd == "stats.htm") {
    return send_report(transport, ServerStats::HTML, "text/html");
  }

  if (cmd == "stats.xsl") {
    string xsl;
    if (!RuntimeOption::StatsXSLProxy.empty()) {
      StringBuffer response;
      if (HttpClient().get(RuntimeOption::StatsXSLProxy.c_str(), response) ==
          200) {
        xsl = response.data();
        if (!xsl.empty()) {
          transport->addHeader("Content-Type", "application/xml");
          transport->sendString(xsl);
          return true;
        }
      }
    }
    transport->sendString("Not Found\n", 404);
    return true;
  }

  return false;
}
Example #25
0
/**
 * PHP has "EGPCS" processing order of these global variables, and this
 * order is important in preparing $_REQUEST that needs to know which to
 * overwrite what when name happens to be the same.
 */
void HttpProtocol::PrepareSystemVariables(Transport *transport,
                                          const RequestURI &r,
                                          const SourceRootInfo &sri) {
  SystemGlobals *g = (SystemGlobals*)get_global_variables();
  const VirtualHost *vhost = VirtualHost::GetCurrent();

  // reset global symbols to nulls or empty arrays
  pm_php$globals$symbols_php();

  Variant &server = g->GV(_SERVER);
  server.set("REQUEST_START_TIME", time(NULL));

  // $_ENV
  process_env_variables(g->GV(_ENV));
  g->GV(_ENV).set("HPHP", 1);
  g->GV(_ENV).set("HPHP_SERVER", 1);
#ifdef HOTPROFILER
  g->GV(_ENV).set("HPHP_HOTPROFILER", 1);
#endif

  Variant &request = g->GV(_REQUEST);

  // $_GET and $_REQUEST
  if (!r.queryString().empty()) {
    DecodeParameters(g->GV(_GET), r.queryString().data(),
                     r.queryString().size());
    CopyParams(request, g->GV(_GET));
  }

  string contentType = transport->getHeader("Content-Type");
  string contentLength = transport->getHeader("Content-Length");
  // $_POST and $_REQUEST
  if (transport->getMethod() == Transport::POST) {
    bool needDelete = false;
    int size = 0;
    const void *data = transport->getPostData(size);
    if (data && size) {
      ASSERT(((char*)data)[size] == 0); // we need a NULL terminated string
      string boundary;
      int content_length = atoi(contentLength.c_str());
      bool rfc1867Post = IsRfc1867(contentType, boundary);
      string files;
      if (rfc1867Post) {
        if (content_length > VirtualHost::GetMaxPostSize()) {
          // $_POST and $_FILES are empty
          Logger::Warning("POST Content-Length of %d bytes exceeds "
                          "the limit of %lld bytes",
                          content_length, VirtualHost::GetMaxPostSize());
          needDelete = read_all_post_data(transport, data, size);
        } else {
          if (transport->hasMorePostData()) {
            needDelete = true;
            data = Util::buffer_duplicate(data, size);
          }
          DecodeRfc1867(transport, g->GV(_POST), g->GV(_FILES),
                        content_length, data, size, boundary);
        }
        ASSERT(!transport->getFiles(files));
      } else {
        needDelete = read_all_post_data(transport, data, size);

        bool decodeData = strncasecmp(contentType.c_str(),
                                       DEFAULT_POST_CONTENT_TYPE,
                                       sizeof(DEFAULT_POST_CONTENT_TYPE)-1) == 0;
        // Always decode data for now. (macvicar)
        decodeData = true;

        if (decodeData) {
          DecodeParameters(g->GV(_POST), (const char*)data, size, true);
        }

        bool ret = transport->getFiles(files);
        if (ret) {
          g->GV(_FILES) = f_unserialize(files);
        }
      }
      CopyParams(request, g->GV(_POST));
      if (needDelete) {
        if (RuntimeOption::AlwaysPopulateRawPostData) {
          g->GV(HTTP_RAW_POST_DATA) = String((char*)data, size, AttachString);
        } else {
          free((void *)data);
        }
      } else {
        // For literal we disregard RuntimeOption::AlwaysPopulateRawPostData
        g->GV(HTTP_RAW_POST_DATA) = String((char*)data, size, AttachLiteral);
      }
    }
  }

  // $_COOKIE
  string cookie_data = transport->getHeader("Cookie");
  if (!cookie_data.empty()) {
    StringBuffer sb;
    sb.append(cookie_data);
    DecodeCookies(g->GV(_COOKIE), (char*)sb.data());
    CopyParams(request, g->GV(_COOKIE));
  }

  // $_SERVER

  // HTTP_ headers -- we don't exclude headers we handle elsewhere (e.g.,
  // Content-Type, Authorization), since the CGI "spec" merely says the server
  // "may" exclude them; this is not what APE does, but it's harmless.
  HeaderMap headers;
  transport->getHeaders(headers);
  for (HeaderMap::const_iterator iter = headers.begin();
       iter != headers.end(); ++iter) {
    const vector<string> &values = iter->second;
    for (unsigned int i = 0; i < values.size(); i++) {
      String key = "HTTP_";
      key += StringUtil::ToUpper(iter->first).replace("-", "_");
      server.set(key, String(values[i]));
    }
  }
  string host = transport->getHeader("Host");
  String hostName(VirtualHost::GetCurrent()->serverName(host));
  string hostHeader(host);
  if (hostHeader.empty()) {
    server.set("HTTP_HOST", hostName);
    StackTraceNoHeap::AddExtraLogging("Server", hostName.data());
  } else {
    StackTraceNoHeap::AddExtraLogging("Server", hostHeader.c_str());
  }
  if (hostName.empty() || RuntimeOption::ForceServerNameToHeader) {
    hostName = hostHeader;
    // _SERVER['SERVER_NAME'] shouldn't contain the port number
    int colonPos = hostName.find(':');
    if (colonPos != String::npos) {
      hostName = hostName.substr(0, colonPos);
    }
  }

  // APE sets CONTENT_TYPE and CONTENT_LENGTH without HTTP_
  if (!contentType.empty()) {
    server.set("CONTENT_TYPE", String(contentType));
  }
  if (!contentLength.empty()) {
    server.set("CONTENT_LENGTH", String(contentLength));
  }

  // APE processes Authorization: Basic into PHP_AUTH_USER and PHP_AUTH_PW
  string authorization = transport->getHeader("Authorization");
  if (!authorization.empty()) {
    if (strncmp(authorization.c_str(), "Basic ", 6) == 0) {
      // it's safe to pass this as a string literal since authorization
      // outlives decodedAuth; this saves us a superfluous copy.
      String decodedAuth =
        StringUtil::Base64Decode(String(authorization.c_str() + 6));
      int colonPos = decodedAuth.find(':');
      if (colonPos != String::npos) {
        server.set("PHP_AUTH_USER", decodedAuth.substr(0, colonPos));
        server.set("PHP_AUTH_PW", decodedAuth.substr(colonPos + 1));
      }
    }
  }

  server.set("REQUEST_URI", String(transport->getUrl(), CopyString));
  server.set("SCRIPT_URL", r.originalURL());
  String prefix(transport->isSSL() ? "https://" : "http://");
  String port_suffix("");

  // Need to append port
  if (!transport->isSSL() && RuntimeOption::ServerPort != 80) {
    port_suffix = ":" + RuntimeOption::ServerPort;
  }
  server.set("SCRIPT_URI", String(prefix +
                                  (hostHeader.empty() ?
                                    hostName + port_suffix : hostHeader)
                                  + r.originalURL()));

  if (r.rewritten()) {
    // when URL is rewritten, PHP decided to put original URL as SCRIPT_NAME
    String name = r.originalURL();
    if (!r.pathInfo().empty()) {
      int pos = name.find(r.pathInfo());
      if (pos >= 0) {
        name = name.substr(0, pos);
      }
    }
    if (r.defaultDoc()) {
      if (!name.empty() && name[name.length() - 1] != '/') {
        name += "/";
      }
      name += String(RuntimeOption::DefaultDocument);
    }
    server.set("SCRIPT_NAME", name);
  } else {
    server.set("SCRIPT_NAME", r.resolvedURL());
  }
  if (!r.rewritten() && r.pathInfo().empty()) {
    server.set("PHP_SELF", r.resolvedURL());
  } else {
    // when URL is rewritten, or pathinfo is not empty, use original URL
    server.set("PHP_SELF", r.originalURL());
  }

  server.set("SCRIPT_FILENAME", r.absolutePath());
  if (r.pathInfo().empty()) {
    server.set("PATH_TRANSLATED", r.absolutePath());
  } else {
    server.set("PATH_TRANSLATED",
               String(vhost->getDocumentRoot() + r.pathInfo().data()));
    server.set("PATH_INFO", r.pathInfo());
  }

  server.set("argv", r.queryString());
  server.set("argc", 0);
  server.set("GATEWAY_INTERFACE", "CGI/1.1");
  server.set("SERVER_ADDR", String(RuntimeOption::ServerPrimaryIP));
  server.set("SERVER_NAME", hostName);
  server.set("SERVER_PORT", RuntimeOption::ServerPort);
  server.set("SERVER_SOFTWARE", "HPHP");
  server.set("SERVER_PROTOCOL", "HTTP/" + transport->getHTTPVersion());
  server.set("SERVER_ADMIN", "");
  server.set("SERVER_SIGNATURE", "");
  switch (transport->getMethod()) {
  case Transport::GET:  server.set("REQUEST_METHOD", "GET");  break;
  case Transport::HEAD: server.set("REQUEST_METHOD", "HEAD"); break;
  case Transport::POST:
    if (transport->getExtendedMethod() == NULL) {
      server.set("REQUEST_METHOD", "POST");
    } else {
      server.set("REQUEST_METHOD", transport->getExtendedMethod());
    }
    break;
  default:              server.set("REQUEST_METHOD", "");     break;
  }
  server.set("HTTPS", transport->isSSL() ? "1" : "");
  server.set("REQUEST_TIME", time(NULL));
  server.set("QUERY_STRING", r.queryString());

  server.set("REMOTE_ADDR", String(transport->getRemoteHost(), CopyString));
  server.set("REMOTE_HOST", ""); // I don't think we need to nslookup
  server.set("REMOTE_PORT", 0);  // TODO: quite useless

  server.set("DOCUMENT_ROOT", String(vhost->getDocumentRoot()));

  for (map<string, string>::const_iterator iter =
         RuntimeOption::ServerVariables.begin();
       iter != RuntimeOption::ServerVariables.end(); ++iter) {
      server.set(String(iter->first), String(iter->second));
  }
  const map<string, string> &vServerVars = vhost->getServerVars();
  for (map<string, string>::const_iterator iter =
         vServerVars.begin();
       iter != vServerVars.end(); ++iter) {
    server.set(String(iter->first), String(iter->second));
  }
  sri.setServerVariables(server);

  const char *threadType = transport->getThreadTypeName();
  server.set("THREAD_TYPE", threadType);
  StackTraceNoHeap::AddExtraLogging("ThreadType", threadType);

#ifdef TAINTED
  taint_array_variant(g->GV(_GET), "$_GET");
  taint_array_variant(g->GV(_POST), "$_POST");
  taint_array_variant(g->GV(_SERVER), "$_SERVER");
  taint_array_variant(g->GV(_COOKIE), "$_COOKIE");
#endif
}
Example #26
0
String::String(const StringBuffer<unsigned char>& o)
{
	m_ptr=StringDetail::str_dup((char*)o.data(),o.size());
}
Example #27
0
String::String(const StringBuffer<char>& o)
{
	m_ptr=StringDetail::str_dup(o.data(),o.size());
}
Example #28
0
 bool Get(const char *key, StringBuffer<TCHAR, max> &value) const {
   return Get(key, value.data(), value.capacity());
 }
Example #29
0
std::string CmdPrint::FormatResult(const char *format, CVarRef ret) {
  if (format == nullptr) {
    String sret = DebuggerClient::FormatVariable(ret, -1);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "v") == 0) {
    String sret = DebuggerClient::FormatVariable(ret, -1, true);
    return string(sret.data(), sret.size());
  }

  if (strcmp(format, "dec") == 0 ||
      strcmp(format, "unsigned") == 0 ||
      ret.isInteger()) {
    int64 nret = ret.toInt64();
    char buf[64];
    if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIx64, nret);
      return buf;
    }
    if (strcmp(format, "oct") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIo64, nret);
      return buf;
    }
    if (strcmp(format, "dec") == 0) {
      snprintf(buf, sizeof(buf), "%" PRId64, nret);
      return buf;
    }
    if (strcmp(format, "unsigned") == 0) {
      snprintf(buf, sizeof(buf), "%" PRIu64, nret);
      return buf;
    }
    if (strcmp(format, "time") == 0) {
      StringBuffer sb;
      DateTime dt(nret);
      sb.append("RFC822:            ");
      sb.append(dt.toString(DateTime::RFC822));
      sb.append("\nRFC850:            ");
      sb.append(dt.toString(DateTime::RFC850));
      sb.append("\nRFC1036:           ");
      sb.append(dt.toString(DateTime::RFC1036));
      sb.append("\nRFC1123/RSS:       ");
      sb.append(dt.toString(DateTime::RFC1123));
      sb.append("\nRFC2822:           ");
      sb.append(dt.toString(DateTime::RFC2822));
      sb.append("\nRFC3339/ATOM/W3C:  ");
      sb.append(dt.toString(DateTime::RFC3339));
      sb.append("\nISO8601:           ");
      sb.append(dt.toString(DateTime::ISO8601));
      sb.append("\nCookie:            ");
      sb.append(dt.toString(DateTime::Cookie));
      sb.append("\nHttpHeader:        ");
      sb.append(dt.toString(DateTime::HttpHeader));
      return sb.data();
    }

    assert(false);
  }

  String sret = DebuggerClient::FormatVariable(ret, -1);
  if (strcmp(format, "hex") == 0 || strcmp(format, "x") == 0 ||
      strcmp(format, "oct") == 0) {
    StringBuffer sb;
    for (int i = 0; i < sret.size(); i++) {
      char ch = sret[i];
      if (isprint(ch)) {
        sb.append(ch);
      } else {
        char buf[6];
        if (strcmp(format, "oct") == 0) {
          snprintf(buf, sizeof(buf), "\\%03o", ch);
        } else {
          snprintf(buf, sizeof(buf), "\\x%02x", ch);
        }
        sb.append(buf);
      }
    }
    return sb.data() ? sb.data() : "";
  }
  if (strcmp(format, "time") == 0) {
    DateTime dt;
    int64 ts = -1;
    if (dt.fromString(ret.toString(), SmartObject<TimeZone>())) {
      bool err;
      ts = dt.toTimeStamp(err);
    }
    return String(ts).data();
  }

  assert(false);
  return "";
}
Example #30
0
/**
 * Precondition: m_originalURL and m_queryString are set
 * Postcondition: Output is false and we are redirecting OR
 *  m_rewrittenURL is set and m_queryString is updated if needed
 */
bool RequestURI::rewriteURL(const VirtualHost *vhost, Transport *transport,
                            const std::string &pathTranslation,
                            const std::string &sourceRoot) {
  bool qsa = false;
  int redirect = 0;
  std::string host = transport->getHeader("host");
  m_rewrittenURL = m_originalURL;
  if (vhost->rewriteURL(host, m_rewrittenURL, qsa, redirect)) {
    m_rewritten = true;
    if (qsa && !m_queryString.empty()) {
      m_rewrittenURL += (m_rewrittenURL.find('?') < 0) ? "?" : "&";
      m_rewrittenURL += m_queryString;
    }
    if (redirect) {
      if (m_rewrittenURL.substr(0, 7) != s_http &&
          m_rewrittenURL.substr(0, 8) != s_https) {
        PrependSlash(m_rewrittenURL);
      }
      if (redirect < 0) {
        std::string error;
        StringBuffer response;
        int code = 0;
        HttpProtocol::ProxyRequest(transport, true,
                                   m_rewrittenURL.toCppString(),
                                   code, error,
                                   response);
        if (!code) {
          transport->sendString(error, 500, false, false, "proxyRequest");
        } else {
          const char* respData = response.data();
          if (!respData) respData = "";
          transport->sendRaw(const_cast<char*>(respData),
                             response.size(), code);
        }
        transport->onSendEnd();
      } else {
        transport->redirect(m_rewrittenURL.c_str(), redirect);
      }
      return false;
    }
    splitURL(m_rewrittenURL, m_rewrittenURL, m_queryString);
  }
  m_rewrittenURL = FileUtil::canonicalize(m_rewrittenURL);
  if (!m_rewritten && m_rewrittenURL.charAt(0) == '/') {
    // A un-rewritten URL is always relative, so remove prepending /
    m_rewrittenURL = m_rewrittenURL.substr(1);
  }

  // If the URL refers to a folder but does not end
  // with a slash, then we need to redictect
  String url = m_rewrittenURL;
  if (!url.empty() &&
      url.charAt(url.length() - 1) != '/') {
    if (virtualFolderExists(vhost, sourceRoot, pathTranslation, url)) {
      if (m_originalURL.find("..") != String::npos) {
        transport->sendString(getDefault404(), 404);
        transport->onSendEnd();
        return false;
      }
      url += "/";
      m_rewritten = true;
      String queryStr;
      m_rewrittenURL = m_originalURL;
      m_rewrittenURL += "/";
      if (!m_queryString.empty()) {
        m_rewrittenURL += "?";
        m_rewrittenURL += m_queryString;
      }
      if (m_rewrittenURL.substr(0, 7) != s_http &&
          m_rewrittenURL.substr(0, 8) != s_https) {
        PrependSlash(m_rewrittenURL);
      }
      transport->redirect(m_rewrittenURL.c_str(), 301);
      return false;
    }
  }

  return true;
}