std::pair<String, StoragePtr> createTableFromDefinition(
    const String & definition,
    const String & database_name,
    const String & database_data_path,
    Context & context,
    bool has_force_restore_data_flag,
    const String & description_for_error_message)
{
    ParserCreateQuery parser;
    ASTPtr ast = parseQuery(parser, definition.data(), definition.data() + definition.size(), description_for_error_message, 0);

    ASTCreateQuery & ast_create_query = typeid_cast<ASTCreateQuery &>(*ast);
    ast_create_query.attach = true;
    ast_create_query.database = database_name;

    /// We do not directly use `InterpreterCreateQuery::execute`, because
    /// - the database has not been created yet;
    /// - the code is simpler, since the query is already brought to a suitable form.
    if (!ast_create_query.columns)
        throw Exception("Missing definition of columns.", ErrorCodes::EMPTY_LIST_OF_COLUMNS_PASSED);

    ColumnsDescription columns = InterpreterCreateQuery::getColumnsDescription(*ast_create_query.columns, context);

    return
    {
        ast_create_query.table,
        StorageFactory::instance().get(
            ast_create_query,
            database_data_path, ast_create_query.table, database_name, context, context.getGlobalContext(),
            columns,
            true, has_force_restore_data_flag)
    };
}
Example #2
0
Variant HHVM_METHOD(XMLReader, getAttributeNs,
                    const String& name,
                    const String& namespaceURI) {
  auto* data = Native::data<XMLReader>(this_);
  SYNC_VM_REGS_SCOPED();
  if (name.empty() || namespaceURI.empty()) {
    raise_warning("Attribute Name and Namespace URI cannot be empty");
    return false;
  }

  char *retchar = nullptr;
  if (data->m_ptr) {
    retchar = (char *)xmlTextReaderGetAttributeNs(data->m_ptr,
                                                  (xmlChar *)name.data(),
                                                  (xmlChar *)namespaceURI.data());
  }

  if (retchar) {
    String ret((const char*)retchar, CopyString);
    xmlFree(retchar);
    return ret;
  } else {
    return init_null();
  }
}
Example #3
0
  static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx) {
    CurlResource *ch = (CurlResource *)ctx;
    ReadHandler *t  = &ch->m_read;

    int length = -1;
    switch (t->method) {
    case PHP_CURL_DIRECT:
      if (!t->fp.isNull()) {
        int data_size = size * nmemb;
        String ret = t->fp->read(data_size);
        length = ret.size();
        if (length) {
          memcpy(data, ret.data(), length);
        }
      }
      break;
    case PHP_CURL_USER:
      {
        int data_size = size * nmemb;
        Variant ret = ch->do_callback(
          t->callback, make_packed_array(Resource(ch), t->fp, data_size));
        if (ret.isString()) {
          String sret = ret.toString();
          length = data_size < sret.size() ? data_size : sret.size();
          memcpy(data, sret.data(), length);
        }
        break;
      }
    }
    return length;
  }
Example #4
0
Variant HHVM_FUNCTION(version_compare,
                      const String& version1,
                      const String& version2,
                      const String& sop /*="" */) {
  const char *op = sop.data();
  int op_len = sop.size();
  int compare = php_version_compare(version1.data(), version2.data());
  if (sop.empty()) {
    return compare;
  }
  if (!strncmp(op, "<", op_len) || !strncmp(op, "lt", op_len)) {
    return compare == -1;
  }
  if (!strncmp(op, "<=", op_len) || !strncmp(op, "le", op_len)) {
    return compare != 1;
  }
  if (!strncmp(op, ">", op_len) || !strncmp(op, "gt", op_len)) {
    return compare == 1;
  }
  if (!strncmp(op, ">=", op_len) || !strncmp(op, "ge", op_len)) {
    return compare != -1;
  }
  if (!strncmp(op, "==", op_len) || !strncmp(op, "=", op_len) ||
      !strncmp(op, "eq", op_len)) {
    return compare == 0;
  }
  if (!strncmp(op, "!=", op_len) || !strncmp(op, "<>", op_len) ||
      !strncmp(op, "ne", op_len)) {
    return compare != 0;
  }
  return init_null();
}
Example #5
0
int64_t HHVM_FUNCTION(mcrypt_module_get_algo_block_size,
                                   const String& algorithm,
                                   const String& lib_dir /* = null_string */) {
  String dir = lib_dir.empty() ? String(MCG(algorithms_dir)) : lib_dir;
  return mcrypt_module_get_algo_block_size((char*)algorithm.data(),
                                           (char*)dir.data());
}
size_t io::writeUnicodeText(ID3_Writer& writer, String data, bool bom)
{
  ID3_Writer::pos_type beg = writer.getCur();
  size_t size = (data.size() / 2) * 2;
  if (size == 0)
  {
    return 0;
  }
  int is_bom = isBOM(data[0],data[1]);
  if (!is_bom && bom) {
    // Write the BOM: 0xFEFF
    const unsigned char BOMch1 = 0xFE;
    const unsigned char BOMch2 = 0xFF;
    writer.writeChars(&BOMch1, 1);
    writer.writeChars(&BOMch2, 1);
  }
  for (size_t i = 0; i < size; i += 2)
  {
    if (!i && !bom && is_bom) {
      // Skip unneeded leading BOM
      continue;
    }
    if (is_bom >= 0) {
      writer.writeChars(data.data()+i, 1);
      writer.writeChars(data.data()+i+1, 1);
    }
    else {
      writer.writeChars(data.data()+i+1, 1);
      writer.writeChars(data.data()+i, 1);
    }
  }
  return writer.getCur() - beg;
}
Example #7
0
static Variant HHVM_FUNCTION(bcpowmod, const String& left, const String& right,
                             const String& modulus, int64_t scale /* = -1 */) {
    if (scale < 0) scale = BCG(bc_precision);
    bc_num first, second, mod, result;
    bc_init_num(&first);
    bc_init_num(&second);
    bc_init_num(&mod);
    bc_init_num(&result);
    SCOPE_EXIT {
        bc_free_num(&first);
        bc_free_num(&second);
        bc_free_num(&mod);
        bc_free_num(&result);
    };
    php_str2num(&first, (char*)left.data());
    php_str2num(&second, (char*)right.data());
    php_str2num(&mod, (char*)modulus.data());
    if (bc_raisemod(first, second, mod, &result, scale) == -1) {
        return false;
    }
    if (result->n_scale > scale) {
        result->n_scale = scale;
    }
    String ret(bc_num2str(result), AttachString);
    return ret;
}
Example #8
0
Variant HHVM_FUNCTION(vprintf, const Variant& vformat, const Variant& args) {
    String format = vformat.toString();
    String output = string_printf(format.data(), format.size(), args.toArray());
    if (output.isNull()) return false;
    g_context->write(output.data(), output.size());
    return output.size();
}
Example #9
0
	inline Optional<uint32> ParseIntOpt<uint32>(const String& str, Radix radix)
	{
		# if defined (SIV3D_TARGET_WINDOWS)

			wchar* p;
			const unsigned long result = ::wcstoul(str.data(), &p, radix.value());

			if (str.data() == p)
			{
				return none;
			}

			return result;

		# elif defined (SIV3D_TARGET_OSX)

			wchar* p;
			const unsigned long result = ::wcstoul(str.data(), &p, radix.value());

			if (str.data() == p || UINT32_MAX < result)
			{
				return none;
			}

			return static_cast<uint32>(result);

		# endif
	}
Example #10
0
String HHVM_FUNCTION(gethostbyname, const String& hostname) {
  IOStatusHelper io("gethostbyname", hostname.data());
  if (RuntimeOption::EnableDnsCache) {
    Variant success;
    Variant resolved = f_apc_fetch(hostname, ref(success),
                                   SHARED_STORE_DNS_CACHE);
    if (same(success, true)) {
      if (same(resolved, false)) {
        return hostname;
      }
      return resolved.toString();
    }
  }

  HostEnt result;
  if (!safe_gethostbyname(hostname.data(), result)) {
    if (RuntimeOption::EnableDnsCache) {
      f_apc_store(hostname, false, RuntimeOption::DnsCacheTTL,
                  SHARED_STORE_DNS_CACHE);
    }
    return hostname;
  }

  struct in_addr in;
  memcpy(&in.s_addr, *(result.hostbuf.h_addr_list), sizeof(in.s_addr));
  String ret(safe_inet_ntoa(in));
  if (RuntimeOption::EnableDnsCache) {
    f_apc_store(hostname, ret, RuntimeOption::DnsCacheTTL,
                SHARED_STORE_DNS_CACHE);
  }
  return ret;
}
Example #11
0
void HttpProtocol::DecodeParameters(Array& variables, const char *data,
                                    int size, bool post /* = false */) {
  if (data == nullptr || size == 0) {
    return;
  }

  const char *s = data;
  const char *e = s + size;
  const char *p, *val;

  while (s < e && (p = (const char *)memchr(s, '&', (e - s)))) {
  last_value:
    if ((val = (const char *)memchr(s, '=', (p - s)))) {
      int len = val - s;
      String sname = url_decode(s, len);

      val++;
      len = p - val;
      String value = url_decode(val, len);

      register_variable(variables, (char*)sname.data(), value);
    } else if (!post) {
      int len = p - s;
      String sname = url_decode(s, len);
      register_variable(variables, (char*)sname.data(),
                        empty_string_variant_ref);
    }
    s = p + 1;
  }
  if (s < e) {
    p = e;
    goto last_value;
  }
}
Example #12
0
int main(int, char **)
try
{
    using namespace DB;

    ReadBufferFromFileDescriptor in(STDIN_FILENO);
    WriteBufferFromFileDescriptor out(STDOUT_FILENO);

    String query;
    readStringUntilEOF(query, in);

    ParserSelectQuery parser;
    ASTPtr ast = parseQuery(parser, query.data(), query.data() + query.size(), "query");

    CollectAliases collector;
    collector.process(ast);
    collector.dump(out);

    return 0;
}
catch (...)
{
    std::cerr << DB::getCurrentExceptionMessage(true) << "\n";
    return 1;
}
Example #13
0
bool ZipFile::open(const String& filename, const String& mode) {
  assert(m_gzFile == nullptr);

  if (strchr(mode.c_str(), '+')) {
    raise_warning("cannot open a zlib stream for reading and writing "
                    "at the same time!");
    return false;
  }

  m_innerFile = File::Open(filename, mode);
  if (m_innerFile.is<MemFile>()) {
    // We need an FD for the correct zlib APIs; MemFiles don't have an FD
    if (strchr(mode.c_str(), 'w')) {
      raise_warning("Cannot write to this stream type");
      return false;
    }
    auto buffer = m_innerFile.getTyped<MemFile>();
    auto file = NEWOBJ(TempFile);
    while (!buffer->eof()) {
      file->write(buffer->read(File::CHUNK_SIZE));
    }
    file->rewind();
    m_tempFile = Resource(file);
    return (m_gzFile = gzdopen(dup(file->fd()), mode.data()));
  }
  if (m_innerFile.is<File>()) {
    auto file = m_innerFile.getTyped<File>();
    m_tempFile.reset();
    return (m_gzFile = gzdopen(dup(file->fd()), mode.data()));
  }
  return false;
}
Example #14
0
Variant f_mysql_multi_query(const String& query, const Variant& link_identifier /* = null */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (conn == nullptr) {
    return false;
  }
  MySQL *mySQL = MySQL::Get(link_identifier);
  if (!mySQL->m_multi_query && !mysql_set_server_option(conn, MYSQL_OPTION_MULTI_STATEMENTS_ON)) {
    mySQL->m_multi_query = true;
  }

  if (mysql_real_query(conn, query.data(), query.size())) {
#ifdef HHVM_MYSQL_TRACE_MODE
    if (RuntimeOption::EnableHipHopSyntax) {
      raise_notice("runtime/ext_mysql: failed executing [%s] [%s]",
                   query.data(), mysql_error(conn));
    }
#endif
      // turning this off clears the errors
      if (!mysql_set_server_option(conn, MYSQL_OPTION_MULTI_STATEMENTS_OFF)) {
        mySQL->m_multi_query = false;
      }
      return false;
  }
  return true;
}
Example #15
0
int64_t HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,
                                           const String& key,
                                           const String& iv) {
  MCrypt *pm = td.getTyped<MCrypt>();
  int max_key_size = mcrypt_enc_get_key_size(pm->m_td);
  int iv_size = mcrypt_enc_get_iv_size(pm->m_td);

  if (key.empty()) {
    raise_warning("Key size is 0");
  }

  unsigned char *key_s = (unsigned char *)malloc(key.size());
  memset(key_s, 0, key.size());

  unsigned char *iv_s = (unsigned char *)malloc(iv_size + 1);
  memset(iv_s, 0, iv_size + 1);

  int key_size;
  if (key.size() > max_key_size) {
    raise_warning("Key size too large; supplied length: %d, max: %d",
                    key.size(), max_key_size);
    key_size = max_key_size;
  } else {
    key_size = key.size();
  }
  memcpy(key_s, key.data(), key.size());

  if (iv.size() != iv_size) {
    raise_warning("Iv size incorrect; supplied length: %d, needed: %d",
                    iv.size(), iv_size);
  }
  memcpy(iv_s, iv.data(), iv_size);

  mcrypt_generic_deinit(pm->m_td);
  int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);

  /* If this function fails, close the mcrypt module to prevent crashes
   * when further functions want to access this resource */
  if (result < 0) {
    pm->close();
    switch (result) {
    case -3:
      raise_warning("Key length incorrect");
      break;
    case -4:
      raise_warning("Memory allocation error");
      break;
    case -1:
    default:
      raise_warning("Unknown error");
      break;
    }
  }
  pm->m_init = true;
  free(iv_s);
  free(key_s);
  return result;
}
Example #16
0
int String::rfind(const String& s, int pos /* = 0 */,
                  bool caseSensitive /* = true */) const {
  if (empty()) return -1;
  if (s.size() == 1) {
    return rfind(*s.data(), pos, caseSensitive);
  }
  return string_rfind(m_str->data(), m_str->size(),
                      s.data(), s.size(), pos, caseSensitive);
}
Example #17
0
String MySQL::GetHash(const String& host, int port, const String& socket,
                      const String& username, const String& password,
                      int client_flags) {
    char buf[1024];
    snprintf(buf, sizeof(buf), "%s:%d:%s:%s:%s:%d",
             host.data(), port, socket.data(),
             username.data(), password.data(), client_flags);
    return String(buf, CopyString);
}
Example #18
0
Variant f_idate(const String& format,
                int64_t timestamp /* = TimeStamp::Current() */) {
  if (format.size() != 1) {
    throw_invalid_argument("format: %s", format.data());
    return false;
  }
  int64_t ret = DateTime(timestamp, false).toInteger(*format.data());
  if (ret == -1) return false;
  return ret;
}
Example #19
0
BlockIO executeQuery(
	const String & query,
	Context & context,
	bool internal,
	QueryProcessingStage::Enum stage)
{
	BlockIO streams;
	std::tie(std::ignore, streams) = executeQueryImpl(query.data(), query.data() + query.size(), context, internal, stage);
	return streams;
}
ASTPtr DatabaseDictionary::getCreateDatabaseQuery(const Context & /*context*/) const
{
    String query;
    {
        WriteBufferFromString buffer(query);
        buffer << "CREATE DATABASE " << backQuoteIfNeed(name) << " ENGINE = Dictionary";
    }
    ParserCreateQuery parser;
    return parseQuery(parser, query.data(), query.data() + query.size(), "", 0);
}
Example #21
0
Variant HHVM_FUNCTION(getservbyname, const String& service,
                      const String& protocol) {
    Lock lock(NetworkMutex);

    struct servent *serv = getservbyname(service.data(), protocol.data());
    if (serv == NULL) {
        return false;
    }
    return ntohs(serv->s_port);
}
Example #22
0
bool c_XMLWriter::t_startpi(const String& target) {
  if (xmlValidateName((xmlChar*)target.data(), 0)) {
    raise_warning("invalid PI target: %s", target.data());
    return false;
  }
  int ret = -1;
  if (m_ptr) {
    ret = xmlTextWriterStartPI(m_ptr, (xmlChar*)target.data());
  }
  return ret != -1;
}
Example #23
0
 void testEncodeEmpty()
 {
   const String empty;
   CPPUNIT_ASSERT(empty.data(String::Latin1).isEmpty());
   CPPUNIT_ASSERT(empty.data(String::UTF8).isEmpty());
   CPPUNIT_ASSERT_EQUAL(ByteVector("\xFF\xFE"), empty.data(String::UTF16));
   CPPUNIT_ASSERT(empty.data(String::UTF16LE).isEmpty());
   CPPUNIT_ASSERT(empty.data(String::UTF16BE).isEmpty());
   CPPUNIT_ASSERT(empty.to8Bit(false).empty());
   CPPUNIT_ASSERT(empty.to8Bit(true).empty());
 }
Example #24
0
 void testEncodeNonLatin1()
 {
   const String jpn(L"\u65E5\u672C\u8A9E");
   CPPUNIT_ASSERT_EQUAL(ByteVector("\xE5\x2C\x9E"), jpn.data(String::Latin1));
   CPPUNIT_ASSERT_EQUAL(ByteVector("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"), jpn.data(String::UTF8));
   CPPUNIT_ASSERT_EQUAL(ByteVector("\xFF\xFE\xE5\x65\x2C\x67\x9E\x8A"), jpn.data(String::UTF16));
   CPPUNIT_ASSERT_EQUAL(ByteVector("\xE5\x65\x2C\x67\x9E\x8A"), jpn.data(String::UTF16LE));
   CPPUNIT_ASSERT_EQUAL(ByteVector("\x65\xE5\x67\x2C\x8A\x9E"), jpn.data(String::UTF16BE));
   CPPUNIT_ASSERT_EQUAL(std::string("\xE5\x2C\x9E"), jpn.to8Bit(false));
   CPPUNIT_ASSERT_EQUAL(std::string("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"), jpn.to8Bit(true));
 }
Example #25
0
bool c_XMLWriter::t_startdtdattlist(const String& name) {
  if (xmlValidateName((xmlChar*)name.data(), 0)) {
    raise_warning("invalid element name: %s", name.data());
    return false;
  }
  int ret = -1;
  if (m_ptr) {
    ret = xmlTextWriterStartDTDAttlist(m_ptr, (xmlChar*)name.data());
  }
  return ret != -1;
}
Example #26
0
bool c_XMLWriter::t_startdtdentity(const String& name, bool isparam) {
  if (xmlValidateName((xmlChar*)name.data(), 0)) {
    raise_warning("invalid attribute name: %s", name.data());
    return false;
  }
  int ret = -1;
  if (m_ptr) {
    ret = xmlTextWriterStartDTDEntity(m_ptr, isparam, (xmlChar*)name.data());
  }
  return ret != -1;
}
Example #27
0
void JsonString::appendReferencedString(StringBuilder& target, String src)
{
    target.append('\"');
    
    const wchar_t* end = src.data() + src.length();
    for (const wchar_t* p = src.data(); p != end; ++p)
    {
        appendChar(target, *p);
    }
    
    target.append('\"');
}
Example #28
0
bool c_XMLWriter::t_writedtdelement(const String& name, const String& content) {
  if (xmlValidateName((xmlChar*)name.data(), 0)) {
    raise_warning("invalid element name: %s", name.data());
    return false;
  }
  int ret = -1;
  if (m_ptr) {
    ret = xmlTextWriterWriteDTDElement(m_ptr, (xmlChar*)name.data(),
                                       (xmlChar*)content.data());
  }
  return ret != -1;
}
Example #29
0
Variant HHVM_FUNCTION(snappy_uncompress, const String& data) {
  size_t dsize;
  if (!snappy::GetUncompressedLength(data.data(), data.size(), &dsize)) {
    return false;
  }

  String s = String(dsize, ReserveString);
  if (!snappy::RawUncompress(data.data(), data.size(), s.mutableData())) {
    return false;
  }
  return s.setSize(dsize);
}
Example #30
0
CachedUnit createUnitFromString(const char* path,
                                const String& contents) {
  auto const md5 = MD5 {
    mangleUnitMd5(string_md5(contents.data(), contents.size())).c_str()
  };
  // Try the repo; if it's not already there, invoke the compiler.
  if (auto const unit = Repo::get().loadUnit(path, md5)) {
    return CachedUnit { unit, RDS::allocBit() };
  }
  auto const unit = compile_file(contents.data(), contents.size(), md5, path);
  return CachedUnit { unit, RDS::allocBit() };
}