Example #1
0
bool WddxPacket::recursiveAddVar(const String& varName,
                                 const Variant& varVariant,
                                 bool hasVarTag) {

  bool isArray = varVariant.isArray();
  bool isObject = varVariant.isObject();

  if (isArray || isObject) {
    if (hasVarTag) {
      m_packetString.append("<var name='");
      m_packetString.append(varName.data());
      m_packetString.append("'>");
    }

    Array varAsArray;
    Object varAsObject = varVariant.toObject();
    if (isArray) varAsArray = varVariant.toArray();
    if (isObject) varAsArray = varAsObject.toArray();

    int length = varAsArray.length();
    if (length > 0) {
      ArrayIter it = ArrayIter(varAsArray);
      if (it.first().isString()) isObject = true;
      if (isObject) {
        m_packetString.append("<struct>");
        if (!isArray) {
          m_packetString.append("<var name='php_class_name'><string>");
          m_packetString.append(varAsObject->getClassName());
          m_packetString.append("</string></var>");
        }
      } else {
        m_packetString.append("<array length='");
        m_packetString.append(std::to_string(length));
        m_packetString.append("'>");
      }
      for (ArrayIter it(varAsArray); it; ++it) {
        Variant key = it.first();
        Variant value = it.second();
        recursiveAddVar(key.toString(), value, isObject);
      }
      if (isObject) {
        m_packetString.append("</struct>");
      }
      else {
        m_packetString.append("</array>");
      }
    }
    else {
      //empty object
      if (isObject) {
        m_packetString.append("<struct>");
        if (!isArray) {
          m_packetString.append("<var name='php_class_name'><string>");
          m_packetString.append(varAsObject->getClassName());
          m_packetString.append("</string></var>");
        }
        m_packetString.append("</struct>");
      }
    }
    if (hasVarTag) {
      m_packetString.append("</var>");
    }
    return true;
  }

  String varType = getDataTypeString(varVariant.getType());
  if (!getWddxEncoded(varType, "", varName, false).empty()) {
    String varValue;
    if (varType.compare("boolean") == 0) {
      varValue = varVariant.toBoolean() ? "true" : "false";
    } else {
      varValue = StringUtil::HtmlEncode(varVariant.toString(),
                                        StringUtil::QuoteStyle::Double,
                                        "UTF-8", false, false).toCppString();
    }
    m_packetString.append(
      getWddxEncoded(varType, varValue, varName, hasVarTag));
    return true;
  }

  return false;
}
Example #2
0
size_t RenderV2ToFile(const ID3_TagImpl& tag, fstream& file)
{
  ID3D_NOTICE( "RenderV2ToFile: starting" );
  if (!file)
  {
    ID3D_WARNING( "RenderV2ToFile: error in file" );
    return 0;
  }

  String tagString;
  io::StringWriter writer(tagString);
  id3::v2::render(writer, tag);
  ID3D_NOTICE( "RenderV2ToFile: rendered v2" );

  const char* tagData = tagString.data();
  size_t tagSize = tagString.size();
  // if the new tag fits perfectly within the old and the old one
  // actually existed (ie this isn't the first tag this file has had)
  if ((!tag.GetPrependedBytes() && !ID3_GetDataSize(tag)) ||
      (tagSize == tag.GetPrependedBytes()))
  {
    file.seekp(0, ios::beg);
    file.write(tagData, tagSize);
  }
  else
  {
    String filename = tag.GetFileName();
    String sTmpSuffix = ".XXXXXX";
    if (filename.size() + sTmpSuffix.size() > ID3_PATH_LENGTH)
    {
      // log this
      return 0;
      //ID3_THROW_DESC(ID3E_NoFile, "filename too long");
    }
    char sTempFile[ID3_PATH_LENGTH];
    strcpy(sTempFile, filename.c_str());
    strcat(sTempFile, sTmpSuffix.c_str());

#if ((defined(__GNUC__) && __GNUC__ >= 3  ) || !defined(HAVE_MKSTEMP))
    // This section is for Windows folk && gcc 3.x folk
    fstream tmpOut;
    createFile(sTempFile, tmpOut);

    tmpOut.write(tagData, tagSize);
    file.seekg(tag.GetPrependedBytes(), ios::beg);
    char *tmpBuffer[BUFSIZ];
    while (!file.eof())
    {
      file.read((char *)tmpBuffer, BUFSIZ);
      size_t nBytes = file.gcount();
      tmpOut.write((char *)tmpBuffer, nBytes);
    }

#else //((defined(__GNUC__) && __GNUC__ >= 3  ) || !defined(HAVE_MKSTEMP))

    // else we gotta make a temp file, copy the tag into it, copy the
    // rest of the old file after the tag, delete the old file, rename
    // this new file to the old file's name and update the handle

    int fd = mkstemp(sTempFile);
    if (fd < 0)
    {
      remove(sTempFile);
      //ID3_THROW_DESC(ID3E_NoFile, "couldn't open temp file");
    }

    ofstream tmpOut(fd);
    if (!tmpOut)
    {
      tmpOut.close();
      remove(sTempFile);
      return 0;
      // log this
      //ID3_THROW(ID3E_ReadOnly);
    }

    tmpOut.write(tagData, tagSize);
    file.seekg(tag.GetPrependedBytes(), ios::beg);
    uchar tmpBuffer[BUFSIZ];
    while (file)
    {
      file.read(tmpBuffer, BUFSIZ);
      size_t nBytes = file.gcount();
      tmpOut.write(tmpBuffer, nBytes);
    }

    close(fd); //closes the file

#endif ////((defined(__GNUC__) && __GNUC__ >= 3  ) || !defined(HAVE_MKSTEMP))

    tmpOut.close();
    file.close();

    // the following sets the permissions of the new file
    // to be the same as the original
#if defined(HAVE_SYS_STAT_H)
    struct stat fileStat;
    if(stat(filename.c_str(), &fileStat) == 0)
    {
#endif //defined(HAVE_SYS_STAT_H)
      remove(filename.c_str());
      rename(sTempFile, filename.c_str());
#if defined(HAVE_SYS_STAT_H)
      chmod(filename.c_str(), fileStat.st_mode);
    }
#endif //defined(HAVE_SYS_STAT_H)

//    file = tmpOut;
    file.clear();//to clear the eof mark
    openWritableFile(filename, file);
  }

  return tagSize;
}
Example #3
0
String TimeZone::AbbreviationToName(String abbr, int utcoffset /* = -1 */,
                                    bool isdst /* = true */) {
  return String(timelib_timezone_id_from_abbr(abbr.data(), utcoffset,
                                              isdst ? -1 : 0),
                CopyString);
}
Example #4
0
Variant HHVM_FUNCTION(hexdec, const Variant& hex_string) {
  String str = hex_string.toString();
  return string_base_to_numeric(str.data(), str.size(), 16);
}
  Variant appendOrPrependFilter(CResRef stream,
                 const String& filtername,
                 CVarRef readwrite,
                 CVarRef params,
                 bool append) {
    const char* func_name =
      append ? "stream_filter_append()" : "stream_filter_prepend()";

    if (!m_registeredFilters.exists(filtername)) {
      raise_warning("%s: unable to locate filter \"%s\"",
                    func_name,
                    filtername->data());
      return false;
    }

    auto file = stream.getTyped<File>();
    assert(file);

    int mode = readwrite.toInt32();
    if (!mode) {
      auto str = file->getMode();
      /* The documentation says a read filter is only created for 'r' and '+'
       * modes, but the implementation will always create one unless
       * STREAM_FILTER_WRITE is passed.
       *
       * This branch is only executed if no STREAM_FILTER* args were passed,
       * so we always create a READ filter.
       */
      mode = k_STREAM_FILTER_READ;
      if (str.find('+') != -1 || str.find('w') != -1 || str.find('a') != -1) {
        mode |= k_STREAM_FILTER_WRITE;
      }
    }
    if (!(mode & k_STREAM_FILTER_ALL)) {
      return false;
    }

    // If it's ALL we create two resources, but only return one - this
    // matches Zend, and is the documented behavior.
    Resource ret;
    if (mode & k_STREAM_FILTER_READ) {
      auto resource = createInstance(func_name,
                                     stream,
                                     filtername,
                                     params);
      if (resource.isNull()) {
        return false;
      }
      ret = resource;
      if (append) {
        file->appendReadFilter(resource);
      } else {
        file->prependReadFilter(resource);
      }
    }
    if (mode & k_STREAM_FILTER_WRITE) {
      auto resource = createInstance(func_name,
                                     stream,
                                     filtername,
                                     params);
      if (resource.isNull()) {
        return false;
      }
      ret = resource;
      if (append) {
        file->appendWriteFilter(resource);
      } else {
        file->prependWriteFilter(resource);
      }
    }
    return ret;
  }
Example #6
0
bool HHVM_FUNCTION(trigger_error, const String& error_msg,
                   int error_type /* = k_E_USER_NOTICE */) {
  std::string msg = error_msg.data(); // not toCppString()
  if (UNLIKELY(g_context->getThrowAllErrors())) {
    throw Exception(folly::sformat("throwAllErrors: {}", error_type));
  }
  if (error_type == k_E_USER_ERROR) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::IfUnhandled,
                           "\nFatal error: ");
    return true;
  }
  if (error_type == k_E_USER_WARNING) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nWarning: ");
    return true;
  }
  if (error_type == k_E_USER_NOTICE) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nNotice: ");
    return true;
  }
  if (error_type == k_E_USER_DEPRECATED) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nDeprecated: ");
    return true;
  }
  if (error_type == k_E_STRICT) {
    // So that we can raise strict warnings for mismatched
    // params in FCallBuiltin
    raise_strict_warning(msg);
    return true;
  }

  ActRec* fp = g_context->getStackFrame();

  if (fp->m_func->nativeFuncPtr() == (BuiltinFunction)HHVM_FN(trigger_error)) {
    fp = g_context->getOuterVMFrame(fp);
  }
  if (fp && fp->m_func->isBuiltin()) {
    if (error_type == k_E_ERROR) {
      raise_error_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_WARNING) {
      raise_warning_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_NOTICE) {
      raise_notice_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_DEPRECATED) {
      raise_deprecated_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_RECOVERABLE_ERROR) {
      raise_recoverable_error_without_first_frame(msg);
      return true;
    }
  }
  raise_warning("Invalid error type specified");
  return false;
}
Example #7
0
void PDOConnection::persistentSave() {
  String serialized = f_serialize(def_stmt_ctor_args);
  serialized_def_stmt_ctor_args = string(serialized.data(), serialized.size());
  def_stmt_ctor_args.reset();
}
Example #8
0
bool Transport::setCookie(CStrRef name, CStrRef value, int64 expire /* = 0 */,
                          CStrRef path /* = "" */, CStrRef domain /* = "" */,
                          bool secure /* = false */,
                          bool httponly /* = false */,
                          bool encode_url /* = true */) {
    if (!name.empty() && strpbrk(name.data(), "=,; \t\r\n\013\014")) {
        Logger::Warning("Cookie names can not contain any of the following "
                        "'=,; \\t\\r\\n\\013\\014'");
        return false;
    }

    if (!encode_url &&
            !value.empty() && strpbrk(value.data(), ",; \t\r\n\013\014")) {
        Logger::Warning("Cookie values can not contain any of the following "
                        "',; \\t\\r\\n\\013\\014'");
        return false;
    }

    char *encoded_value = NULL;
    int len = 0;
    if (!value.empty() && encode_url) {
        int encoded_value_len = value.size();
        encoded_value = url_encode(value.data(), encoded_value_len);
        len += encoded_value_len;
    } else if (!value.empty()) {
        encoded_value = strdup(value.data());
        len += value.size();
    }
    len += path.size();
    len += domain.size();

    std::string cookie;
    cookie.reserve(len + 100);
    if (value.empty()) {
        /*
         * MSIE doesn't delete a cookie when you set it to a null value
         * so in order to force cookies to be deleted, even on MSIE, we
         * pick an expiry date 1 year and 1 second in the past
         */
        String sdt = DateTime(time(NULL) - 31536001, true)
                     .toString(DateTime::Cookie);
        cookie += name.data();
        cookie += "=deleted; expires=";
        cookie += sdt.data();
    } else {
        cookie += name.data();
        cookie += "=";
        cookie += encoded_value ? encoded_value : "";
        if (expire > 0) {
            if (expire > 253402300799LL) {
                raise_warning("Expiry date cannot have a year greater then 9999");
                return false;
            }
            cookie += "; expires=";
            String sdt = DateTime(expire, true).toString(DateTime::Cookie);
            cookie += sdt.data();
        }
    }

    if (encoded_value) {
        free(encoded_value);
    }

    if (!path.empty()) {
        cookie += "; path=";
        cookie += path.data();
    }
    if (!domain.empty()) {
        cookie += "; domain=";
        cookie += domain.data();
    }
    if (secure) {
        cookie += "; secure";
    }
    if (httponly) {
        cookie += "; httponly";
    }

    FiberWriteLock lock(this);
    m_responseCookies[name.data()] = cookie;
    return true;
}
Example #9
0
bool c_Collator::t_sortwithsortkeys(VRefParam arr) {
  char*       sortKeyBuf = NULL; /* buffer to store sort keys */
  int32_t     sortKeyBufSize = DEF_SORT_KEYS_BUF_SIZE; /* buffer size */
  ptrdiff_t   sortKeyBufOffset = 0; /* pos in buffer to store sort key */
  int32_t     sortKeyLen = 0; /* the length of currently processing key */
  int32_t     bufLeft = 0;
  int32_t     bufIncrement = 0;

  /* buffer to store 'indexes' which will be passed to 'qsort' */
  collator_sort_key_index_t* sortKeyIndxBuf = NULL;
  int32_t     sortKeyIndxBufSize   = DEF_SORT_KEYS_INDX_BUF_SIZE;
  int32_t     sortKeyIndxSize      = sizeof( collator_sort_key_index_t );

  int32_t     sortKeyCount         = 0;
  int32_t     j                    = 0;

  /* tmp buffer to hold current processing string in utf-16 */
  UChar*      utf16_buf            = NULL;
  /* the length of utf16_buf */
  int         utf16_buf_size       = DEF_UTF16_BUF_SIZE;
  /* length of converted string */
  int         utf16_len            = 0;

  m_errcode.clear();
  s_intl_error->m_error.clear();

  /*
   * Sort specified array.
   */
  if (!arr.isArray()) {
    return true;
  }
  Array hash = arr.toArray();
  if (hash.size() == 0) {
    return true;
  }

  /* Create bufers */
  sortKeyBuf     = (char*)calloc(sortKeyBufSize, sizeof(char));
  sortKeyIndxBuf = (collator_sort_key_index_t*)malloc(sortKeyIndxBufSize);
  utf16_buf      = (UChar*)malloc(utf16_buf_size);

  /* Iterate through input hash and create a sort key for each value. */
  for (ssize_t pos = hash->iter_begin(); pos != ArrayData::invalid_index;
       pos = hash->iter_advance(pos)) {
    /* Convert current hash item from UTF-8 to UTF-16LE and save the result
     * to utf16_buf. */
    utf16_len = utf16_buf_size;
    /* Process string values only. */
    Variant val(hash->getValue(pos));
    if (val.isString()) {
      String str = val.toString();
      intl_convert_utf8_to_utf16(&utf16_buf, &utf16_len, str.data(),
                                 str.size(), &(m_errcode.code));
      if (U_FAILURE(m_errcode.code)) {
        m_errcode.custom_error_message = "Sort with sort keys failed";
        if (utf16_buf) {
          free(utf16_buf);
        }
        free(sortKeyIndxBuf);
        free(sortKeyBuf);
        return false;
      }
    } else {
      /* Set empty string */
      utf16_len = 0;
      utf16_buf[utf16_len] = 0;
    }

    if ((utf16_len + 1) > utf16_buf_size) {
      utf16_buf_size = utf16_len + 1;
    }

    /* Get sort key, reallocating the buffer if needed. */
    bufLeft = sortKeyBufSize - sortKeyBufOffset;

    sortKeyLen = ucol_getSortKey(m_ucoll,
                    utf16_buf,
                    utf16_len,
                    (uint8_t*)sortKeyBuf + sortKeyBufOffset,
                    bufLeft);

    /* check for sortKeyBuf overflow, increasing its size of the buffer if
       needed */
    if (sortKeyLen > bufLeft) {
      bufIncrement = ( sortKeyLen > DEF_SORT_KEYS_BUF_INCREMENT ) ?
        sortKeyLen : DEF_SORT_KEYS_BUF_INCREMENT;
      sortKeyBufSize += bufIncrement;
      bufLeft += bufIncrement;
      sortKeyBuf = (char*)realloc(sortKeyBuf, sortKeyBufSize);
      sortKeyLen = ucol_getSortKey(m_ucoll, utf16_buf, utf16_len,
                                   (uint8_t*)sortKeyBuf + sortKeyBufOffset,
                                   bufLeft);
    }

    /* check sortKeyIndxBuf overflow, increasing its size of the buffer if
       needed */
    if ((sortKeyCount + 1) * sortKeyIndxSize > sortKeyIndxBufSize) {
      bufIncrement = (sortKeyIndxSize > DEF_SORT_KEYS_INDX_BUF_INCREMENT) ?
        sortKeyIndxSize : DEF_SORT_KEYS_INDX_BUF_INCREMENT;
      sortKeyIndxBufSize += bufIncrement;
      sortKeyIndxBuf = (collator_sort_key_index_t*)realloc(sortKeyIndxBuf,
                                                           sortKeyIndxBufSize);
    }
    sortKeyIndxBuf[sortKeyCount].key = (char*)sortKeyBufOffset;
    sortKeyIndxBuf[sortKeyCount].valPos = pos;
    sortKeyBufOffset += sortKeyLen;
    ++sortKeyCount;
  }

  /* update ptrs to point to valid keys. */
  for( j = 0; j < sortKeyCount; j++ )
    sortKeyIndxBuf[j].key = sortKeyBuf + (ptrdiff_t)sortKeyIndxBuf[j].key;

  /* sort it */
  zend_qsort(sortKeyIndxBuf, sortKeyCount, sortKeyIndxSize,
             collator_cmp_sort_keys, NULL);

  /* for resulting hash we'll assign new hash keys rather then reordering */
  Array sortedHash = Array::Create();

  for (j = 0; j < sortKeyCount; j++) {
    sortedHash.append(hash->getValue(sortKeyIndxBuf[j].valPos));
  }

  /* Save sorted hash into return variable. */
  arr = sortedHash;

  if (utf16_buf)
    free(utf16_buf);

  free(sortKeyIndxBuf);
  free(sortKeyBuf);

  return true;
}
Example #10
0
void
XWindowsClipboard::icccmFillCache()
{
	LOG((CLOG_DEBUG "ICCCM fill clipboard %d", m_id));

	// see if we can get the list of available formats from the selection.
	// if not then use a default list of formats.  note that some clipboard
	// owners are broken and report TARGETS as the type of the TARGETS data
	// instead of the correct type ATOM;  allow either.
	const Atom atomTargets = m_atomTargets;
	Atom target;
	String data;
	if (!icccmGetSelection(atomTargets, &target, &data) ||
		(target != m_atomAtom && target != m_atomTargets)) {
		LOG((CLOG_DEBUG1 "selection doesn't support TARGETS"));
		data = "";
		XWindowsUtil::appendAtomData(data, XA_STRING);
	}

	XWindowsUtil::convertAtomProperty(data);
	const Atom* targets = reinterpret_cast<const Atom*>(data.data());
	const UInt32 numTargets = data.size() / sizeof(Atom);
	LOG((CLOG_DEBUG "  available targets: %s", XWindowsUtil::atomsToString(m_display, targets, numTargets).c_str()));

	// try each converter in order (because they're in order of
	// preference).
	for (ConverterList::const_iterator index = m_converters.begin();
								index != m_converters.end(); ++index) {
		IXWindowsClipboardConverter* converter = *index;

		// skip already handled targets
		if (m_added[converter->getFormat()]) {
			continue;
		}

		// see if atom is in target list
		Atom target = None;
		// XXX -- just ask for the converter's target to see if it's
		// available rather than checking TARGETS.  i've seen clipboard
		// owners that don't report all the targets they support.
		target = converter->getAtom();
		/*
		for (UInt32 i = 0; i < numTargets; ++i) {
			if (converter->getAtom() == targets[i]) {
				target = targets[i];
				break;
			}
		}
		*/
		if (target == None) {
			continue;
		}

		// get the data
		Atom actualTarget;
		String targetData;
		if (!icccmGetSelection(target, &actualTarget, &targetData)) {
			LOG((CLOG_DEBUG1 "  no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str()));
			continue;
		}

		// add to clipboard and note we've done it
		IClipboard::EFormat format = converter->getFormat();
		m_data[format]  = converter->toIClipboard(targetData);
		m_added[format] = true;
		LOG((CLOG_DEBUG "added format %d for target %s (%u %s)", format, XWindowsUtil::atomToString(m_display, target).c_str(), targetData.size(), targetData.size() == 1 ? "byte" : "bytes"));
	}
}
Example #11
0
void
XWindowsClipboard::motifFillCache()
{
	LOG((CLOG_DEBUG "Motif fill clipboard %d", m_id));

	// get the Motif clipboard header property from the root window
	Atom target;
	SInt32 format;
	String data;
	Window root = RootWindow(m_display, DefaultScreen(m_display));
	if (!XWindowsUtil::getWindowProperty(m_display, root,
								m_atomMotifClipHeader,
								&data, &target, &format, False)) {
		return;
	}

	// check that the header is okay
	const MotifClipHeader* header =
						reinterpret_cast<const MotifClipHeader*>(data.data());
	if (data.size() < sizeof(MotifClipHeader) ||
		header->m_id != kMotifClipHeader ||
		header->m_numItems < 1) {
		return;
	}

	// get the Motif item property from the root window
	char name[18 + 20];
	sprintf(name, "_MOTIF_CLIP_ITEM_%d", header->m_item);
    Atom atomItem = XInternAtom(m_display, name, False);
	data = "";
	if (!XWindowsUtil::getWindowProperty(m_display, root,
								atomItem, &data,
								&target, &format, False)) {
		return;
	}

	// check that the item is okay
	const MotifClipItem* item =
					reinterpret_cast<const MotifClipItem*>(data.data());
	if (data.size() < sizeof(MotifClipItem) ||
		item->m_id != kMotifClipItem ||
		item->m_numFormats - item->m_numDeletedFormats < 1) {
		return;
	}

	// format list is after static item structure elements
	const SInt32 numFormats = item->m_numFormats - item->m_numDeletedFormats;
	const SInt32* formats   = reinterpret_cast<const SInt32*>(item->m_size +
								reinterpret_cast<const char*>(data.data()));

	// get the available formats
	typedef std::map<Atom, String> MotifFormatMap;
	MotifFormatMap motifFormats;
	for (SInt32 i = 0; i < numFormats; ++i) {
		// get Motif format property from the root window
		sprintf(name, "_MOTIF_CLIP_ITEM_%d", formats[i]);
    	Atom atomFormat = XInternAtom(m_display, name, False);
		String data;
		if (!XWindowsUtil::getWindowProperty(m_display, root,
									atomFormat, &data,
									&target, &format, False)) {
			continue;
		}

		// check that the format is okay
		const MotifClipFormat* motifFormat =
						reinterpret_cast<const MotifClipFormat*>(data.data());
		if (data.size() < sizeof(MotifClipFormat) ||
			motifFormat->m_id != kMotifClipFormat ||
			motifFormat->m_length < 0 ||
			motifFormat->m_type == None ||
			motifFormat->m_deleted != 0) {
			continue;
		}

		// save it
		motifFormats.insert(std::make_pair(motifFormat->m_type, data));
	}
	//const UInt32 numMotifFormats = motifFormats.size();

	// try each converter in order (because they're in order of
	// preference).
	for (ConverterList::const_iterator index = m_converters.begin();
								index != m_converters.end(); ++index) {
		IXWindowsClipboardConverter* converter = *index;

		// skip already handled targets
		if (m_added[converter->getFormat()]) {
			continue;
		}

		// see if atom is in target list
		MotifFormatMap::const_iterator index2 =
								motifFormats.find(converter->getAtom());
		if (index2 == motifFormats.end()) {
			continue;
		}

		// get format
		const MotifClipFormat* motifFormat =
								reinterpret_cast<const MotifClipFormat*>(
									index2->second.data());
		const Atom target                   = motifFormat->m_type;

		// get the data (finally)
		Atom actualTarget;
		String targetData;
		if (!motifGetSelection(motifFormat, &actualTarget, &targetData)) {
			LOG((CLOG_DEBUG1 "  no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str()));
			continue;
		}

		// add to clipboard and note we've done it
		IClipboard::EFormat format = converter->getFormat();
		m_data[format]  = converter->toIClipboard(targetData);
		m_added[format] = true;
		LOG((CLOG_DEBUG "added format %d for target %s", format, XWindowsUtil::atomToString(m_display, target).c_str()));
	}
}
Example #12
0
File* DataStreamWrapper::open(const String& filename, const String& mode,
                              int options, const Variant& context) {

  // @todo: check allow_url_include?

  const char* data = filename.data();
  int data_len = filename.length();
  bool base64 = false;
  if (strncmp(data, "data:", sizeof("data:") - 1)) {
    return nullptr;
  }
  data += sizeof("data:") - 1;
  data_len -= sizeof("data:") - 1;

  // RFC 2397 specifies 'data:' as the prefix,
  // but zend's PHP supports 'data://' as well
  if (data_len >= 2 && data[0] == '/' && data[1] == '/') {
    data_len -= 2;
    data += 2;
  }

  char* comma = (char*)memchr(data, ',', data_len);
  if (comma == nullptr) {
    raise_warning("rfc2397: missing comma");
    return nullptr;
  }

  if (comma != data) {
    // we have meta
    ssize_t meta_len = comma - data;
    data_len -= meta_len;
    char* semi = (char*)memchr(data, ';', meta_len);
    char* slash = (char*)memchr(data, '/', meta_len);

    if (!slash && !semi) {
      raise_warning("rfc2397: invalid meta data");
      return nullptr;
    }

    if (!semi) {
      // only media type (type/subtype,data)
      ssize_t media_len = comma - data;
      meta_len -= media_len;
      data += media_len;
    } else if (slash && slash < semi) {
      // media type + param (type/subtype;param,data)
      ssize_t media_len = semi - data;
      meta_len -= media_len;
      data += media_len;
    } else {
      // no media type (;base64,data)
      if (semi != data // ex. foo;base64,data
          || meta_len != sizeof(";base64") - 1 // ex. ;something,data
          || memcmp(data, ";base64",
                    sizeof(";base64") - 1)) { // ex. ;base65,data
          raise_warning("rfc2397: invalid meta data");
          return nullptr;
        }
    }

    assert(data == comma || data == semi);
    // eat parameters, and figure out if we have ';base64'
    while (semi && (data == semi)) {
      data++;
      meta_len--;
      char* equals = (char*)memchr(data, '=', meta_len);
      semi = (char*)memchr(data, ';', meta_len);
      if (!equals || (semi && semi < data)) {
        // no equals, so either 'base64' or its bad
        if (meta_len != sizeof("base64") - 1 ||
            memcmp(data, "base64", sizeof("base64")-1)) {
          raise_warning("rfc2396: invalid parameter");
          return nullptr;
        }
        // it's "base64", we're done
        base64 = true;
        meta_len -= sizeof("base64") - 1;
        data += sizeof("base64") - 1;
        break;
      }
      // there's a parameter
      if (semi) {
        meta_len -= semi - data + 1;
        data = semi;
      } /* else, we're done with meta */
    }
  }
  data = comma + 1;
  data_len -= 1;
  std::unique_ptr<MemFile> file;
  String decoded;

  if (base64) {
    decoded = string_base64_decode(data, data_len, true);
    if (decoded.isNull()) {
      raise_warning("unable to decode base64 data");
      return nullptr;
    }
  } else {
    decoded = url_decode(data, data_len);
  }
  file =
    std::unique_ptr<MemFile>(newres<MemFile>(decoded.data(), decoded.size()));
  return file.release();
}
bool HttpRequestHandler::executePHPRequest(Transport *transport,
                                           RequestURI &reqURI,
                                           SourceRootInfo &sourceRootInfo,
                                           bool cachableDynamicContent) {
  ExecutionContext *context = hphp_context_init();
  if (RuntimeOption::ImplicitFlush) {
    context->obSetImplicitFlush(true);
  }
  if (RuntimeOption::EnableOutputBuffering) {
    if (RuntimeOption::OutputHandler.empty()) {
      context->obStart();
    } else {
      context->obStart(String(RuntimeOption::OutputHandler));
    }
  }
  context->setTransport(transport);

  string file = reqURI.absolutePath().c_str();
  {
    ServerStatsHelper ssh("input");
    HttpProtocol::PrepareSystemVariables(transport, reqURI, sourceRootInfo);
    reqURI.clear();
    sourceRootInfo.clear();
  }

  int code;
  bool ret = true;

  if (ret) {
    if (RuntimeOption::EnableDebugger) {
      Eval::Debugger::InterruptRequestStarted(transport->getUrl());
    }

    bool error = false;
    std::string errorMsg = "Internal Server Error";
    ret = hphp_invoke(context, file, false, Array(), null,
                      RuntimeOption::WarmupDocument,
                      RuntimeOption::RequestInitFunction,
                      RuntimeOption::RequestInitDocument,
                      RuntimeOption::RequestShutdownFunction,
                      error, errorMsg);

    if (ret) {
      String content = context->obDetachContents();
      if (cachableDynamicContent && !content.empty()) {
        ASSERT(transport->getUrl());
        string key = file + transport->getUrl();
        DynamicContentCache::TheCache.store(key, content.data(),
                                            content.size());
      }
      transport->sendRaw((void*)content.data(), content.size());
      code = transport->getResponseCode();
    } else if (error) {
      code = 500;

      std::string responseInfo = transport->getResponseInfo();
      if (responseInfo.find("explicit_header") != string::npos) {
        code = transport->getResponseCode();
      }

      string errorPage = context->getErrorPage().data();
      if (errorPage.empty()) {
        errorPage = RuntimeOption::ErrorDocument500;
      }
      if (!errorPage.empty()) {
        context->obProtect(false);
        context->obEndAll();
        context->obStart();
        context->obProtect(true);
        ret = hphp_invoke(context, errorPage, false, Array(), null,
                          RuntimeOption::WarmupDocument,
                          RuntimeOption::RequestInitFunction,
                          RuntimeOption::RequestInitDocument,
                          RuntimeOption::RequestShutdownFunction,
                          error, errorMsg);
        if (ret) {
          String content = context->obDetachContents();
          transport->sendRaw((void*)content.data(), content.size());
          code = transport->getResponseCode();
        } else {
          Logger::Error("Unable to invoke error page %s", errorPage.c_str());
          errorPage.clear(); // so we fall back to 500 return
        }
      }
      if (errorPage.empty()) {
        if (RuntimeOption::ServerErrorMessage) {
          transport->sendString(errorMsg, 500, false, false, "hphp_invoke");
        } else {
          transport->sendString(RuntimeOption::FatalErrorMessage,
                                500, false, false, "hphp_invoke");
        }
      }
    } else {
      code = 404;
      transport->sendString("Not Found", 404);
    }

    if (RuntimeOption::EnableDebugger) {
      Eval::Debugger::InterruptRequestEnded(transport->getUrl());
    }
  }

  transport->onSendEnd();
  hphp_context_exit(context, true, true, transport->getUrl());
  ServerStats::LogPage(file, code);
  return ret;
}
void HttpRequestHandler::handleRequest(Transport *transport) {
  ExecutionProfiler ep(ThreadInfo::RuntimeFunctions);

  Logger::OnNewRequest();
  GetAccessLog().onNewRequest();
  transport->enableCompression();

  ServerStatsHelper ssh("all", true);
  Logger::Verbose("receiving %s", transport->getCommand().c_str());

  // will clear all extra logging when this function goes out of scope
  StackTraceNoHeap::ExtraLoggingClearer clearer;
  StackTraceNoHeap::AddExtraLogging("URL", transport->getUrl());

  // resolve virtual host
  const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
  ASSERT(vhost);
  if (vhost->disabled() ||
      vhost->isBlocking(transport->getCommand(), transport->getRemoteHost())) {
    transport->sendString("Not Found", 404);
    return;
  }
  ServerStats::StartRequest(transport->getCommand().c_str(),
                            transport->getRemoteHost(),
                            vhost->getName().c_str());

  // resolve source root
  string host = transport->getHeader("Host");
  SourceRootInfo sourceRootInfo(host.c_str());

  if (sourceRootInfo.error()) {
    sourceRootInfo.handleError(transport);
    return;
  }

  // request URI
  string pathTranslation = m_pathTranslation ?
    vhost->getPathTranslation().c_str() : "";
  RequestURI reqURI(vhost, transport, sourceRootInfo.path(), pathTranslation);
  if (reqURI.done()) {
    return; // already handled with redirection or 404
  }
  string path = reqURI.path().data();
  string absPath = reqURI.absolutePath().data();

  // determine whether we should compress response
  bool compressed = transport->decideCompression();

  const char *data; int len;
  const char *ext = reqURI.ext();

  if (reqURI.forbidden()) {
    transport->sendString("Forbidden", 403);
    return;
  }

  bool cachableDynamicContent =
    (!RuntimeOption::StaticFileGenerators.empty() &&
     RuntimeOption::StaticFileGenerators.find(path) !=
     RuntimeOption::StaticFileGenerators.end());

  // If this is not a php file, check the static and dynamic content caches
  if (ext && strcasecmp(ext, "php") != 0) {
    if (RuntimeOption::EnableStaticContentCache) {
      bool original = compressed;
      // check against static content cache
      if (StaticContentCache::TheCache.find(path, data, len, compressed)) {
        String str;
        // (qigao) not calling stat at this point because the timestamp of
        // local cache file is not valuable, maybe misleading. This way
        // the Last-Modified header will not show in response.
        // stat(RuntimeOption::FileCache.c_str(), &st);
        if (!original && compressed) {
          data = gzdecode(data, len);
          if (data == NULL) {
            throw FatalErrorException("cannot unzip compressed data");
          }
          compressed = false;
          str = NEW(StringData)(data, len, AttachString);
        }
        sendStaticContent(transport, data, len, 0, compressed, path, ext);
        StaticContentCache::TheFileCache->adviseOutMemory();
        ServerStats::LogPage(path, 200);
        GetAccessLog().log(transport, vhost);
        return;
      }
    }

    if (RuntimeOption::EnableStaticContentFromDisk) {
      String translated = File::TranslatePath(String(absPath));
      if (!translated.empty()) {
        StringBuffer sb(translated.data());
        if (sb.valid()) {
          struct stat st;
          st.st_mtime = 0;
          stat(translated.data(), &st);
          sendStaticContent(transport, sb.data(), sb.size(), st.st_mtime,
                            false, path, ext);
          ServerStats::LogPage(path, 200);
          GetAccessLog().log(transport, vhost);
          return;
        }
      }
    }

    // check static contents that were generated by dynamic pages
    if (cachableDynamicContent) {
      // check against dynamic content cache
      ASSERT(transport->getUrl());
      string key = path + transport->getUrl();
      if (DynamicContentCache::TheCache.find(key, data, len, compressed)) {
        sendStaticContent(transport, data, len, 0, compressed, path, ext);
        ServerStats::LogPage(path, 200);
        GetAccessLog().log(transport, vhost);
        return;
      }
    }
  }

  // proxy any URLs that not specified in ServeURLs
  if (!RuntimeOption::ProxyOrigin.empty() &&
      ((RuntimeOption::UseServeURLs &&
        RuntimeOption::ServeURLs.find(path) ==
        RuntimeOption::ServeURLs.end()) ||
       (RuntimeOption::UseProxyURLs &&
        (RuntimeOption::ProxyURLs.find(path) !=
         RuntimeOption::ProxyURLs.end() ||
         MatchAnyPattern(path, RuntimeOption::ProxyPatterns) ||
         (abs(rand()) % 100) < RuntimeOption::ProxyPercentage)))) {
    for (int i = 0; i < RuntimeOption::ProxyRetry; i++) {
      bool force = (i == RuntimeOption::ProxyRetry - 1); // last one
      if (handleProxyRequest(transport, force)) break;
    }
    return;
  }

  // record request for debugging purpose
  std::string tmpfile = HttpProtocol::RecordRequest(transport);

  // main body
  hphp_session_init();
  vhost->setRequestTimeoutSeconds();

  bool ret = false;
  try {
    ret = executePHPRequest(transport, reqURI, sourceRootInfo,
                            cachableDynamicContent);
  } catch (const Eval::DebuggerException &e) {
    transport->sendString(e.what(), 200);
    transport->onSendEnd();
    hphp_context_exit(g_context.getNoCheck(), true, true, transport->getUrl());
  } catch (...) {
    Logger::Error("Unhandled exception in HPHP server engine.");
  }
  GetAccessLog().log(transport, vhost);
  /*
   * HPHP logs may need to access data in ServerStats, so we have to
   * clear the hashtable after writing the log entry.
   */
  ServerStats::Reset();
  hphp_session_exit();

  HttpProtocol::ClearRecord(ret, tmpfile);
}
Example #15
0
   std::vector<shared_ptr<Address> > 
   AddresslistParser::ParseList(const String &sList) const
   {
      std::vector<shared_ptr<Address> > vecResult;

      std::vector<String> vecCompounds;
      
      int i = 0;
      int iCurWordStartPos = 0;
      bool bIsInsideQuote = false;

      int iLength = sList.GetLength();
      const wchar_t *pCharBuf = sList.data();

      int maxIterations = 1000000;

      while (i < iLength && maxIterations > 0)
      {
         maxIterations--;

         const wchar_t sCurChar = *(pCharBuf + i);

         if (sCurChar == '\\')
            i++; // Jump an extra since next character is escaped.
         else if (sCurChar == '\"')
         {
            if (bIsInsideQuote)
               bIsInsideQuote = false;
            else
               bIsInsideQuote = true;
         }
         else if (!bIsInsideQuote && sCurChar == ',')
         {
            // We have found an unquoted comma character.
            int iCurWordLen = i - iCurWordStartPos;

            String sCurWord = sList.Mid(iCurWordStartPos, iCurWordLen);
            sCurWord.Trim();
            vecCompounds.push_back(sCurWord);

            iCurWordStartPos = i + 1;
         }
         
         i++;
      }

      if (iCurWordStartPos < sList.GetLength())
      {
         String sCurWord = sList.Mid(iCurWordStartPos);
         sCurWord.Trim();
         vecCompounds.push_back(sCurWord);
      }

      // We now have a vector containing the recipients.

      boost_foreach(String compound, vecCompounds)
      {
         String sFullName;
         String sMailbox;
         String sDomain;

         ExtractParts(compound, sFullName, sMailbox, sDomain);

         shared_ptr<Address> pAddress = shared_ptr<Address> (new Address);
         
         pAddress->sPersonalName = Charset::Encode(sFullName);
         
         // Remove <> from <*****@*****.**>
         sMailbox.Replace(_T("<"), _T(""));      
         sDomain.Replace(_T(">"), _T(""));
   
         pAddress->sMailboxName = Charset::Encode(sMailbox);
         pAddress->sDomainName = Charset::Encode(sDomain);

         vecResult.push_back(pAddress);
      }
Example #16
0
static Array HHVM_FUNCTION(getopt, const String& options,
                                   const Variant& longopts /*=null */) {
  opt_struct *opts, *orig_opts;
  int len = parse_opts(options.data(), options.size(), &opts);

  if (!longopts.isNull()) {
    Array arropts = longopts.toArray();
    int count = arropts.size();

    /* the first <len> slots are filled by the one short ops
     * we now extend our array and jump to the new added structs */
    opts = (opt_struct *)req::realloc(
      opts, sizeof(opt_struct) * (len + count + 1));
    orig_opts = opts;
    opts += len;

    memset(opts, 0, count * sizeof(opt_struct));

    for (ArrayIter iter(arropts); iter; ++iter) {
      String entry = iter.second().toString();

      opts->need_param = 0;
      opts->opt_name = strdup(entry.data());
      len = strlen(opts->opt_name);
      if ((len > 0) && (opts->opt_name[len - 1] == ':')) {
        opts->need_param++;
        opts->opt_name[len - 1] = '\0';
        if ((len > 1) && (opts->opt_name[len - 2] == ':')) {
          opts->need_param++;
          opts->opt_name[len - 2] = '\0';
        }
      }
      opts->opt_char = 0;
      opts++;
    }
  } else {
    opts = (opt_struct*) req::realloc(opts, sizeof(opt_struct) * (len + 1));
    orig_opts = opts;
    opts += len;
  }

  /* php_getopt want to identify the last param */
  opts->opt_char   = '-';
  opts->need_param = 0;
  opts->opt_name   = NULL;

  static const StaticString s_argv("argv");
  Array vargv = php_global(s_argv).toArray();
  int argc = vargv.size();
  char **argv = (char **)req::malloc((argc+1) * sizeof(char*));
  std::vector<String> holders;
  int index = 0;
  for (ArrayIter iter(vargv); iter; ++iter) {
    String arg = iter.second().toString();
    holders.push_back(arg);
    argv[index++] = (char*)arg.data();
  }
  argv[index] = NULL;

  /* after our pointer arithmetic jump back to the first element */
  opts = orig_opts;

  int o;
  char *php_optarg = NULL;
  int php_optind = 1;

  SCOPE_EXIT {
    free_longopts(orig_opts);
    req::free(orig_opts);
    req::free(argv);
  };

  Array ret = Array::Create();

  Variant val;
  int optchr = 0;
  int dash = 0; /* have already seen the - */
  char opt[2] = { '\0' };
  char *optname;
  int optname_len = 0;
  int php_optidx;
  while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1,
                         optchr, dash, php_optidx))
         != -1) {
    /* Skip unknown arguments. */
    if (o == '?') {
      continue;
    }

    /* Prepare the option character and the argument string. */
    if (o == 0) {
      optname = opts[php_optidx].opt_name;
    } else {
      if (o == 1) {
        o = '-';
      }
      opt[0] = o;
      optname = opt;
    }

    if (php_optarg != NULL) {
      /* keep the arg as binary, since the encoding is not known */
      val = String(php_optarg, CopyString);
    } else {
      val = false;
    }

    /* Add this option / argument pair to the result hash. */
    optname_len = strlen(optname);
    if (!(optname_len > 1 && optname[0] == '0') &&
        is_numeric_string(optname, optname_len, NULL, NULL, 0) ==
        KindOfInt64) {
      /* numeric string */
      int optname_int = atoi(optname);
      if (ret.exists(optname_int)) {
        Variant &e = ret.lvalAt(optname_int);
        if (!e.isArray()) {
          ret.set(optname_int, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(optname_int, val);
      }
    } else {
      /* other strings */
      String key(optname, strlen(optname), CopyString);
      if (ret.exists(key)) {
        Variant &e = ret.lvalAt(key);
        if (!e.isArray()) {
          ret.set(key, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(key, val);
      }
    }

    php_optarg = NULL;
  }

  return ret;
}
Example #17
0
void HHVM_FUNCTION(hphp_throw_fatal_error, const String& error_msg) {
  std::string msg = error_msg.data();
  raise_error(msg);
}
void HttpRequestHandler::handleRequest(Transport *transport) {
  Logger::OnNewRequest();
  GetAccessLog().onNewRequest();
  transport->enableCompression();

  Logger::Verbose("receiving %s", transport->getCommand().c_str());
  ServerStatsHelper ssh("all", true);

  // resolve virtual host
  const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
  ASSERT(vhost);
  if (vhost->disabled() ||
      vhost->isBlocking(transport->getCommand(), transport->getRemoteHost())) {
    transport->sendString("Not Found", 404);
    return;
  }
  ServerStats::StartRequest(transport->getCommand().c_str(),
                            transport->getRemoteHost(),
                            vhost->getName().c_str());

  // resolve source root
  string host = transport->getHeader("Host");
  SourceRootInfo sourceRootInfo(host.c_str());

  if (sourceRootInfo.error()) {
    sourceRootInfo.handleError(transport);
    return;
  }

  // request URI
  string pathTranslation = m_pathTranslation ?
    vhost->getPathTranslation().c_str() : "";
  RequestURI reqURI(vhost, transport, sourceRootInfo.path(), pathTranslation);
  if (reqURI.done()) {
    return; // already handled with redirection or 404
  }
  string path = reqURI.path().data();
  string absPath = reqURI.absolutePath().data();

  bool compressed = transport->acceptEncoding("gzip");
  const char *data; int len;
  size_t pos = path.rfind('.');
  const char *ext = (pos != string::npos) ? (path.c_str() + pos + 1) : NULL;
  bool cachableDynamicContent =
    (!RuntimeOption::StaticFileGenerators.empty() &&
     RuntimeOption::StaticFileGenerators.find(path) !=
     RuntimeOption::StaticFileGenerators.end());

  // If this is not a php file, check the static and dynamic content caches
  if (ext && strcasecmp(ext, "php") != 0) {
    if (RuntimeOption::EnableStaticContentCache) {
      // check against static content cache
      if (StaticContentCache::TheCache.find(path, data, len, compressed)) {
        struct stat st;
        st.st_mtime = 0;
        // (qigao) not calling stat at this point because the timestamp of
        // local cache file is not valuable, maybe misleading. This way
        // the Last-Modified header will not show in response.
        // stat(RuntimeOption::FileCache.c_str(), &st);
        sendStaticContent(transport, data, len, st.st_mtime, compressed, path);
        ServerStats::LogPage(path, 200);
        return;
      }
    }

    if (RuntimeOption::EnableStaticContentFromDisk &&
        RuntimeOption::StaticFileExtensions.find(ext) !=
        RuntimeOption::StaticFileExtensions.end()) {
      String translated = File::TranslatePath(String(absPath));
      if (!translated.empty()) {
        StringBuffer sb(translated.data());
        if (sb.valid()) {
          struct stat st;
          st.st_mtime = 0;
          stat(translated.data(), &st);
          sendStaticContent(transport, sb.data(), sb.size(), st.st_mtime,
                            false, path);
          ServerStats::LogPage(path, 200);
          return;
        }
      }
    }

    // check static contents that were generated by dynamic pages
    if (cachableDynamicContent) {
      // check against dynamic content cache
      ASSERT(transport->getUrl());
      string key = path + transport->getUrl();
      if (DynamicContentCache::TheCache.find(key, data, len, compressed)) {
        sendStaticContent(transport, data, len, 0, compressed, path);
        ServerStats::LogPage(path, 200);
        return;
      }
    }
  }

  // proxy any URLs that not specified in ServeURLs
  if (!RuntimeOption::ProxyOrigin.empty() &&
      ((RuntimeOption::UseServeURLs &&
        RuntimeOption::ServeURLs.find(path) ==
        RuntimeOption::ServeURLs.end()) ||
       (RuntimeOption::UseProxyURLs &&
        (RuntimeOption::ProxyURLs.find(path) !=
         RuntimeOption::ProxyURLs.end() ||
         MatchAnyPattern(path, RuntimeOption::ProxyPatterns) ||
         (abs(rand()) % 100) < RuntimeOption::ProxyPercentage)))) {
    for (int i = 0; i < RuntimeOption::ProxyRetry; i++) {
      bool force = (i == RuntimeOption::ProxyRetry - 1); // last one
      if (handleProxyRequest(transport, force)) break;
    }
    return;
  }

  // record request for debugging purpose
  std::string tmpfile = HttpProtocol::RecordRequest(transport);

  // main body
  hphp_session_init();

  bool ret = false;
  try {
    ret = executePHPRequest(transport, reqURI, sourceRootInfo,
                            cachableDynamicContent);
  } catch (...) {
    Logger::Error("Unhandled exception in HPHP server engine.");
  }
  GetAccessLog().log(transport);
  hphp_session_exit();

  HttpProtocol::ClearRecord(ret, tmpfile);
}
Example #19
0
  bool setOption(long option, CVarRef value) {
    if (m_cp == NULL) {
      return false;
    }
    m_error_no = CURLE_OK;

    switch (option) {
    case CURLOPT_INFILESIZE:
    case CURLOPT_VERBOSE:
    case CURLOPT_HEADER:
    case CURLOPT_NOPROGRESS:
    case CURLOPT_NOBODY:
    case CURLOPT_FAILONERROR:
    case CURLOPT_UPLOAD:
    case CURLOPT_POST:
    case CURLOPT_FTPLISTONLY:
    case CURLOPT_FTPAPPEND:
    case CURLOPT_NETRC:
    case CURLOPT_PUT:
    case CURLOPT_TIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_TIMEOUT_MS:
#endif
    case CURLOPT_FTP_USE_EPSV:
    case CURLOPT_LOW_SPEED_LIMIT:
    case CURLOPT_SSLVERSION:
    case CURLOPT_LOW_SPEED_TIME:
    case CURLOPT_RESUME_FROM:
    case CURLOPT_TIMEVALUE:
    case CURLOPT_TIMECONDITION:
    case CURLOPT_TRANSFERTEXT:
    case CURLOPT_HTTPPROXYTUNNEL:
    case CURLOPT_FILETIME:
    case CURLOPT_MAXREDIRS:
    case CURLOPT_MAXCONNECTS:
    case CURLOPT_CLOSEPOLICY:
    case CURLOPT_FRESH_CONNECT:
    case CURLOPT_FORBID_REUSE:
    case CURLOPT_CONNECTTIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_CONNECTTIMEOUT_MS:
#endif
    case CURLOPT_SSL_VERIFYHOST:
    case CURLOPT_SSL_VERIFYPEER:
      //case CURLOPT_DNS_USE_GLOBAL_CACHE: not thread-safe when set to true
    case CURLOPT_NOSIGNAL:
    case CURLOPT_PROXYTYPE:
    case CURLOPT_BUFFERSIZE:
    case CURLOPT_HTTPGET:
    case CURLOPT_HTTP_VERSION:
    case CURLOPT_CRLF:
    case CURLOPT_DNS_CACHE_TIMEOUT:
    case CURLOPT_PROXYPORT:
    case CURLOPT_FTP_USE_EPRT:
    case CURLOPT_HTTPAUTH:
    case CURLOPT_PROXYAUTH:
    case CURLOPT_FTP_CREATE_MISSING_DIRS:
    case CURLOPT_FTPSSLAUTH:
    case CURLOPT_FTP_SSL:
    case CURLOPT_UNRESTRICTED_AUTH:
    case CURLOPT_PORT:
    case CURLOPT_AUTOREFERER:
    case CURLOPT_COOKIESESSION:
    case CURLOPT_TCP_NODELAY:
    case CURLOPT_IPRESOLVE:
    case CURLOPT_FOLLOWLOCATION:
      m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, value.toInt64());
      break;
    case CURLOPT_RETURNTRANSFER:
      m_write.method = value.toBoolean() ? PHP_CURL_RETURN : PHP_CURL_STDOUT;
      break;
    case CURLOPT_BINARYTRANSFER:
      m_write.type = value.toBoolean() ? PHP_CURL_BINARY : PHP_CURL_ASCII;
      break;
    case CURLOPT_PRIVATE:
    case CURLOPT_URL:
    case CURLOPT_PROXY:
    case CURLOPT_USERPWD:
    case CURLOPT_PROXYUSERPWD:
    case CURLOPT_RANGE:
    case CURLOPT_CUSTOMREQUEST:
    case CURLOPT_USERAGENT:
    case CURLOPT_FTPPORT:
    case CURLOPT_COOKIE:
    case CURLOPT_REFERER:
    case CURLOPT_INTERFACE:
    case CURLOPT_KRB4LEVEL:
    case CURLOPT_EGDSOCKET:
    case CURLOPT_CAINFO:
    case CURLOPT_CAPATH:
    case CURLOPT_SSL_CIPHER_LIST:
    case CURLOPT_SSLKEY:
    case CURLOPT_SSLKEYTYPE:
    case CURLOPT_SSLKEYPASSWD:
    case CURLOPT_SSLENGINE:
    case CURLOPT_SSLENGINE_DEFAULT:
    case CURLOPT_SSLCERTTYPE:
    case CURLOPT_ENCODING:
    case CURLOPT_COOKIEJAR:
    case CURLOPT_SSLCERT:
    case CURLOPT_RANDOM_FILE:
    case CURLOPT_COOKIEFILE:
      {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* Strings passed to libcurl as 'char *' arguments, are copied
           by the library... NOTE: before 7.17.0 strings were not copied. */
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, svalue.c_str());
#else
        char *copystr = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(copystr);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, copystr);
#endif
        if (option == CURLOPT_URL) m_url = value;
      }
      break;
    case CURLOPT_FILE:
    case CURLOPT_INFILE:
    case CURLOPT_WRITEHEADER:
    case CURLOPT_STDERR:
      {
        if (!value.isResource()) {
          return false;
        }

        Resource obj = value.toResource();
        if (obj.isNull() || obj.getTyped<File>(true) == NULL) {
          return false;
        }

        switch (option) {
          case CURLOPT_FILE:
            m_write.fp = obj;
            m_write.method = PHP_CURL_FILE;
            break;
          case CURLOPT_WRITEHEADER:
            m_write_header.fp = obj;
            m_write_header.method = PHP_CURL_FILE;
            break;
          case CURLOPT_INFILE:
            m_read.fp = obj;
            m_emptyPost = false;
            break;
          default: {
            if (obj.getTyped<PlainFile>(true) == NULL) {
              return false;
            }
            FILE *fp = obj.getTyped<PlainFile>()->getStream();
            if (!fp) {
              return false;
            }
            m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, fp);
            break;
          }
        }
      }
      break;
    case CURLOPT_WRITEFUNCTION:
      m_write.callback = value;
      m_write.method = PHP_CURL_USER;
      break;
    case CURLOPT_READFUNCTION:
      m_read.callback = value;
      m_read.method = PHP_CURL_USER;
      m_emptyPost = false;
      break;
    case CURLOPT_HEADERFUNCTION:
      m_write_header.callback = value;
      m_write_header.method = PHP_CURL_USER;
      break;
    case CURLOPT_POSTFIELDS:
      m_emptyPost = false;
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_httppost *first = NULL;
        curl_httppost *last  = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();
          const char *postval = val.data();

          /* The arguments after _NAMELENGTH and _CONTENTSLENGTH
           * must be explicitly cast to long in curl_formadd
           * use since curl needs a long not an int. */
          if (*postval == '@') {
            ++postval;
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_FILE, postval,
               CURLFORM_END);
          } else {
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_COPYCONTENTS, postval,
               CURLFORM_CONTENTSLENGTH,(long)val.size(),
               CURLFORM_END);
          }
        }

        if (m_error_no != CURLE_OK) {
          return false;
        }

        m_to_free->post.push_back(first);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_HTTPPOST, first);

      } else {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS,
           but we have to provide size before */
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_COPYPOSTFIELDS,
                                      svalue.c_str());
#else
        char *post = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(post);

        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDS, post);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
#endif
      }
      break;
    case CURLOPT_HTTPHEADER:
    case CURLOPT_QUOTE:
    case CURLOPT_HTTP200ALIASES:
    case CURLOPT_POSTQUOTE:
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_slist *slist = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();

          slist = curl_slist_append(slist, val.c_str());
          if (!slist) {
            raise_warning("Could not build curl_slist");
            return false;
          }
        }

        m_to_free->slist.push_back(slist);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, slist);

      } else {
        raise_warning("You must pass either an object or an array with "
                      "the CURLOPT_HTTPHEADER, CURLOPT_QUOTE, "
                      "CURLOPT_HTTP200ALIASES and CURLOPT_POSTQUOTE "
                      "arguments");
        return false;
      }
      break;

    case CURLINFO_HEADER_OUT:
      if (value.toInt64() == 1) {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, curl_debug);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, (void *)this);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 1);
      } else {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, NULL);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, NULL);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 0);
      }
      break;

    case CURLOPT_FB_TLS_VER_MAX:
      {
        int64_t val = value.toInt64();
        if (value.isInteger() &&
            (val == CURLOPT_FB_TLS_VER_MAX_1_0 ||
             val == CURLOPT_FB_TLS_VER_MAX_1_1 ||
             val == CURLOPT_FB_TLS_VER_MAX_NONE)) {
            m_opts.set(int64_t(option), value);
        } else {
          raise_warning("You must pass CURLOPT_FB_TLS_VER_MAX_1_0, "
                        "CURLOPT_FB_TLS_VER_MAX_1_1 or "
                        "CURLOPT_FB_TLS_VER_MAX_NONE with "
                        "CURLOPT_FB_TLS_VER_MAX");
        }
      }
      break;
    case CURLOPT_FB_TLS_CIPHER_SPEC:
      if (value.isString() && !value.toString().empty()) {
        m_opts.set(int64_t(option), value);
      } else {
        raise_warning("CURLOPT_FB_TLS_CIPHER_SPEC requires a non-empty string");
      }
      break;

    default:
      m_error_no = CURLE_FAILED_INIT;
      throw_invalid_argument("option: %ld", option);
      break;
    }

    m_opts.set(int64_t(option), value);

    return m_error_no == CURLE_OK;
  }
Example #20
0
static Variant HHVM_FUNCTION(mysql_set_charset, const String& charset,
                   const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return init_null();
  return !mysql_set_character_set(conn, charset.data());
}
Example #21
0
Variant HHVM_FUNCTION(bindec, const Variant& binary_string) {
  String str = binary_string.toString();
  return string_base_to_numeric(str.data(), str.size(), 2);
}
Example #22
0
static bool HHVM_FUNCTION(mysql_select_db, const String& db,
                   const Variant& link_identifier /* = uninit_null() */) {
  MYSQL *conn = MySQL::GetConn(link_identifier);
  if (!conn) return false;
  return mysql_select_db(conn, db.data()) == 0;
}
Example #23
0
Variant HHVM_FUNCTION(octdec, const Variant& octal_string) {
  String str = octal_string.toString();
  return string_base_to_numeric(str.data(), str.size(), 8);
}
Example #24
0
static Variant HHVM_FUNCTION(mysql_result, const Resource& result, int row,
                                    const Variant& field /* = 0 */) {
  MySQLResult *res = php_mysql_extract_result(result);
  if (res == NULL) return false;

  MYSQL_RES *mysql_result = NULL;
  MYSQL_ROW sql_row = NULL;
  unsigned long *sql_row_lengths = NULL;

  if (res->isLocalized()) {
    if (!res->seekRow(row)) return false;
    if (!res->fetchRow()) return false;
  } else {
    mysql_result = res->get();
    if (row < 0 || row >= (int)mysql_num_rows(mysql_result)) {
      raise_warning("Unable to jump to row %d on MySQL result index %d",
                      row, result->o_getId());
      return false;
    }
    mysql_data_seek(mysql_result, row);

    sql_row = mysql_fetch_row(mysql_result);
    if (!sql_row) {
      return false;
    }
    sql_row_lengths = mysql_fetch_lengths(mysql_result);
    if (!sql_row_lengths) {
      return false;
    }
  }

  int field_offset = 0;
  if (!field.isNull()) {
    if (field.isString()) {
      String sfield = field.toString();
      const char *tmp = strchr(sfield.data(), '.');
      String table_name, field_name;
      if (tmp) {
        int pos = tmp - sfield.data();
        table_name = sfield.substr(0, pos);
        field_name = sfield.substr(pos + 1);
      } else {
        field_name = sfield;
      }

      int i = 0;
      bool found = false;
      res->seekField(0);
      while (i < res->getFieldCount()) {
        MySQLFieldInfo *info = res->getFieldInfo(i);
        if ((table_name.empty() || table_name.same(info->table)) &&
            field_name.same(info->name)) {
          field_offset = i;
          found = true;
          break;
        }
        i++;
      }
      if (!found) { /* no match found */
        raise_warning("%s%s%s not found in MySQL result index %d",
                        table_name.data(), (table_name.empty() ? "" : "."),
                        field_name.data(), result->o_getId());
        return false;
      }
    } else {
      field_offset = field.toInt32();
      if (field_offset < 0 ||
          field_offset >= (int)res->getFieldCount()) {
        raise_warning("Bad column offset specified");
        return false;
      }
    }
  }

  if (res->isLocalized()) {
    Variant f = res->getField(field_offset);
    if (!f.isNull()) {
      return f.toString();
    }
  } else {
    if (sql_row[field_offset]) {
      return String(sql_row[field_offset], sql_row_lengths[field_offset],
                    CopyString);
    }
  }
  return init_null();
}
Example #25
0
static void xslt_ext_function_php(xmlXPathParserContextPtr ctxt,
                                  int nargs,
                                  int type) {
  XSLTProcessorData *intern = nullptr;
  int error = 0;

  xsltTransformContextPtr tctxt = xsltXPathGetTransformContext (ctxt);
  if (tctxt == nullptr) {
    xsltGenericError(xsltGenericErrorContext,
      "xsltExtFunctionTest: failed to get the transformation context\n"
    );
    error = 1;
  } else {
    intern = (XSLTProcessorData*)tctxt->_private;
    if (intern == nullptr) {
      xsltGenericError(xsltGenericErrorContext,
        "xsltExtFunctionTest: failed to get the internal object\n"
      );
      error = 1;
    } else {
      if (intern->m_registerPhpFunctions == 0) {
        xsltGenericError(xsltGenericErrorContext,
          "xsltExtFunctionTest: PHP Object did not register PHP functions\n"
        );
        error = 1;
      }
    }
  }

  xmlXPathObjectPtr obj;
  if (error == 1) {
    for (int i = nargs - 1; i >= 0; i--) {
      obj = valuePop(ctxt);
      xmlXPathFreeObject(obj);
    }
    return;
  }

  Array args;
  // Reverse order to pop values off ctxt stack
  for (int i = nargs - 2; i >= 0; i--) {
    Variant arg;
    obj = valuePop(ctxt);
    if (obj == nullptr) {
      args.prepend(init_null());
      continue;
    }
    switch (obj->type) {
    case XPATH_STRING:
      arg = String((char*)obj->stringval, CopyString);
      break;
    case XPATH_BOOLEAN:
      arg = (bool)obj->boolval;
      break;
    case XPATH_NUMBER:
      arg = (double)obj->floatval;
      break;
    case XPATH_NODESET:
      if (type == 1) {
        char *str = (char*)xmlXPathCastToString(obj);
        arg = String(str, CopyString);
        xmlFree(str);
      } else if (type == 2) {
        arg = Array::Create();
        if (obj->nodesetval && obj->nodesetval->nodeNr > 0) {
          for (int j = 0; j < obj->nodesetval->nodeNr; j++) {
            // TODO: not sure this is the right thing to do.
            xmlNodePtr node = obj->nodesetval->nodeTab[j];

            if (node->type == XML_ELEMENT_NODE) {
              Object element = newNode(s_DOMElement,
                                       xmlCopyNode(node, /*extended*/ 1));
              arg.toArrRef().append(element);
            } else if (node->type == XML_ATTRIBUTE_NODE) {
              Object attribute =
                newNode(s_DOMAttr,
                        (xmlNodePtr)xmlCopyProp(nullptr, (xmlAttrPtr)node));
              arg.toArrRef().append(attribute);
            } else if (node->type == XML_TEXT_NODE) {
              Object text =
                newNode(s_DOMText,
                        (xmlNodePtr)xmlNewText(xmlNodeGetContent(node)));
              arg.toArrRef().append(text);
            } else {
              raise_warning("Unhandled node type '%d'", node->type);
              // Use a generic DOMNode as fallback for now.
              Object nodeobj = newNode(s_DOMNode,
                                       xmlCopyNode(node, /*extended*/ 1));
              arg.toArrRef().append(nodeobj);
            }
          }
        }
      }
      break;
    default:
      arg = String((char*)xmlXPathCastToString(obj), CopyString);
    }
    xmlXPathFreeObject(obj);
    args.prepend(arg);
  }

  obj = valuePop(ctxt);
  if ((obj == nullptr) || (obj->stringval == nullptr)) {
    raise_warning("Handler name must be a string");
    xmlXPathFreeObject(obj);
    // Push an empty string to get an xslt result.
    valuePush(ctxt, xmlXPathNewString((xmlChar*)""));
    return;
  }
  String handler((char*)obj->stringval, CopyString);
  xmlXPathFreeObject(obj);

  if (!is_callable(handler)) {
    raise_warning("Unable to call handler %s()", handler.data());
    // Push an empty string to get an xslt result.
    valuePush(ctxt, xmlXPathNewString((xmlChar*)""));
  } else if (intern->m_registerPhpFunctions == 2 &&
             !intern->m_registered_phpfunctions.exists(handler)) {
    raise_warning("Not allowed to call handler '%s()'", handler.data());
    // Push an empty string to get an xslt result.
    valuePush(ctxt, xmlXPathNewString((xmlChar*)""));
  } else {
    Variant retval = vm_call_user_func(handler, args);
    if (retval.isObject() &&
        retval.getObjectData()->instanceof(s_DOMNode)) {
      ObjectData *retval_data = retval.asCObjRef().get();
      xmlNode* nodep = Native::data<DOMNode>(retval_data)->nodep();
      valuePush(ctxt, xmlXPathNewNodeSet(nodep));
      intern->m_usedElements.prepend(retval);
    } else if (retval.is(KindOfBoolean)) {
      valuePush(ctxt, xmlXPathNewBoolean(retval.toBoolean()));
    } else if (retval.isObject()) {
      raise_warning("A PHP Object cannot be converted to an XPath-string");
      // Push an empty string to get an xslt result.
      valuePush(ctxt, xmlXPathNewString((xmlChar*)""));
    } else {
      String sretval = retval.toString();
      valuePush(ctxt, xmlXPathNewString((xmlChar*)sretval.data()));
    }
  }
}
Example #26
0
Variant HHVM_FUNCTION(readline_info, const String& varname /* = null */,
                                     const String& newvalue /* = null */) {
  if (varname.isNull()) {
    ArrayInit ret(12, ArrayInit::Map{});
    ret.add(s_line_buffer, convert_null_to_empty(rl_line_buffer));
    ret.add(s_point, rl_point);
    ret.add(s_end, rl_end);
#ifndef USE_EDITLINE
    ret.add(s_mark, rl_mark);
    ret.add(s_done, rl_done);
    ret.add(s_pending_input, rl_pending_input);
    ret.add(s_prompt, convert_null_to_empty(rl_prompt));
    ret.add(s_terminal_name, convert_null_to_empty(rl_terminal_name));
#endif
#if HAVE_ERASE_EMPTY_LINE
    ret.add(s_erase_empty_line, rl_erase_empty_line);
#endif
    ret.add(s_library_version, convert_null_to_empty(rl_library_version));
    ret.add(s_readline_name, convert_null_to_empty(rl_readline_name));
    ret.add(s_attempted_completion_over, rl_attempted_completion_over);
    return ret.toArray();
  } else {
    Variant oldval;
    if (varname == s_line_buffer) {
      oldval = String(convert_null_to_empty(rl_line_buffer));
      if (!newvalue.isNull() && oldval.toString() != newvalue) {
        Lock lock(info_lock);
        raise_warning(
          "This probably isn't doing what you expect it to do, " \
          "this buffer is set for EVERY request."
        );
        free(_rl_line_buffer);
        _rl_line_buffer = strdup(newvalue.data());
        rl_line_buffer = _rl_line_buffer;
      }
      return oldval;
    } else if (varname == s_point) {
      return rl_point;
    } else if (varname == s_end) {
      return rl_end;
#ifndef USE_EDITLINE
    } else if (varname == s_mark) {
      return rl_mark;
    } else if (varname == s_done) {
      oldval = rl_done;
      if (!newvalue.isNull()) {
        rl_done = newvalue.toInt64();
      }
      return oldval;
    } else if (varname == s_pending_input) {
      oldval = rl_pending_input;
      if (!newvalue.isNull()) {
        rl_pending_input = newvalue.toInt64();
      }
      return oldval;
    } else if (varname == s_prompt) {
      return convert_null_to_empty(rl_prompt);
#endif
#if HAVE_ERASE_EMPTY_LINE
    } else if (varname == s_erase_empty_line) {
      oldval = rl_erase_empty_line;
      if (!newvalue.isNull()) {
        rl_erase_empty_line = newvalue.toInt64();
      }
      return oldval;
#endif
    } else if (varname == s_library_version) {
      return convert_null_to_empty(rl_library_version);
    } else if (varname == s_readline_name) {
      oldval = String(convert_null_to_empty(rl_readline_name));
      if (!newvalue.isNull() && oldval.toString() != newvalue) {
        Lock lock(info_lock);
        raise_warning(
          "This probably isn't doing what you expect it to do, " \
          "this name is set for EVERY request."
        );
        free(_rl_readline_name);
        _rl_readline_name = strdup(newvalue.data());
        rl_readline_name = _rl_readline_name;
      }
      return oldval;
    } else if (varname == s_attempted_completion_over) {
      oldval = rl_attempted_completion_over;
      if (!newvalue.isNull()) {
        rl_attempted_completion_over = newvalue.toInt64();
      }
      return oldval;
    }
  }
  return null_variant;
}
Example #27
0
Variant c_DebuggerClientCmdUser::t_ask(int _argc, CStrRef format,
                                CArrRef _argv /* = null_array */) {
  TRACE(5, "c_DebuggerClientCmdUser::t_ask\n");
  String ret = format_string(*m_client, _argc, format, _argv);
  return String::FromChar(m_client->ask("%s", ret.data()));
}
Example #28
0
static bool HHVM_FUNCTION(readline_add_history, const String& line) {
  add_history(line.data());
  return true;
}
Example #29
0
void binary_serialize(int8_t thrift_typeID, PHPOutputTransport& transport,
                      CVarRef value, CArrRef fieldspec) {
  // At this point the typeID (and field num, if applicable) should've already
  // been written to the output so all we need to do is write the payload.
  switch (thrift_typeID) {
    case T_STOP:
    case T_VOID:
      return;
    case T_STRUCT: {
      if (!value.is(KindOfObject)) {
        throw_tprotocolexception("Attempt to send non-object "
                                 "type as a T_STRUCT", INVALID_DATA);
      }
      binary_serialize_spec(value, transport,
                            f_hphp_get_static_property(toObject(value)->
                                                       o_getClassName(),
                                                       "_TSPEC").toArray());
    } return;
    case T_BOOL:
      transport.writeI8(value.toBoolean() ? 1 : 0);
      return;
    case T_BYTE:
      transport.writeI8(value.toByte());
      return;
    case T_I16:
      transport.writeI16(value.toInt16());
      return;
    case T_I32:
      transport.writeI32(value.toInt32());
      return;
    case T_I64:
    case T_U64:
      transport.writeI64(value.toInt64());
      return;
    case T_DOUBLE: {
      union {
        int64_t c;
        double d;
      } a;
      a.d = value.toDouble();
      transport.writeI64(a.c);
    } return;
    //case T_UTF7:
    case T_UTF8:
    case T_UTF16:
    case T_STRING: {
        String sv = value.toString();
        transport.writeString(sv.data(), sv.size());
    } return;
    case T_MAP: {
      Array ht = value.toArray();
      uint8_t keytype = fieldspec.rvalAt(s_ktype,
                                         AccessFlags::Error_Key).toByte();
      transport.writeI8(keytype);
      uint8_t valtype = fieldspec.rvalAt(s_vtype,
                                         AccessFlags::Error_Key).toByte();
      transport.writeI8(valtype);

      Array valspec = fieldspec.rvalAt(s_val,
                                       AccessFlags::Error_Key).toArray();

      transport.writeI32(ht.size());
      for (ArrayIter key_ptr = ht.begin(); !key_ptr.end(); ++key_ptr) {
        binary_serialize_hashtable_key(keytype, transport, key_ptr.first());
        binary_serialize(valtype, transport, key_ptr.second(), valspec);
      }
    } return;
    case T_LIST: {
      Array ht = value.toArray();
      Variant val;

      uint8_t valtype = fieldspec.rvalAt(s_etype,
                                         AccessFlags::Error_Key).toInt64();
      transport.writeI8(valtype);
      Array valspec = fieldspec.rvalAt(s_elem,
                                       AccessFlags::Error_Key).toArray();
      transport.writeI32(ht.size());
      for (ArrayIter key_ptr = ht.begin(); !key_ptr.end(); ++key_ptr) {
        binary_serialize(valtype, transport, key_ptr.second(), valspec);
      }
    } return;
    case T_SET: {
      Array ht = value.toArray();

      uint8_t keytype = fieldspec.rvalAt(s_etype,
                                         AccessFlags::Error_Key).toByte();
      transport.writeI8(keytype);

      transport.writeI32(ht.size());
      for (ArrayIter key_ptr = ht.begin(); !key_ptr.end(); ++key_ptr) {
        binary_serialize_hashtable_key(keytype, transport, key_ptr.first());
      }
    } return;
  };
  char errbuf[128];
  sprintf(errbuf, "Unknown thrift typeID %d", thrift_typeID);
  throw_tprotocolexception(String(errbuf, CopyString), INVALID_DATA);
}
Example #30
0
void PDOConnection::persistentSave() {
  String serialized = f_serialize(def_stmt_ctor_args);
  serialized_def_stmt_ctor_args = std::string(serialized.data(),
    serialized.size());
  def_stmt_ctor_args.releaseForSweep(); // we're called from requestShutdown
}