Array c_Memcache::t_getstats(CStrRef type /* = null_string */, int slabid /* = 0 */, int limit /* = 100 */) { if (!memcached_server_count(&m_memcache)) { return NULL; } char extra_args[30] = {0}; if (slabid) { snprintf(extra_args, sizeof(extra_args), "%s %d %d", type.c_str(), slabid, limit); } else if (!type.empty()) { snprintf(extra_args, sizeof(extra_args), "%s", type.c_str()); } memcached_server_instance_st instance = memcached_server_instance_by_position(&m_memcache, 0); memcached_stat_st stats; if (memcached_stat_servername(&stats, extra_args, instance->hostname, instance->port) != MEMCACHED_SUCCESS) { return NULL; } memcached_return_t ret; return memcache_build_stats(&m_memcache, &stats, &ret); }
Array f_get_class_vars(CStrRef class_name) { ClassInfo::PropertyVec properties; ClassInfo::GetClassProperties(properties, class_name); CStrRef context = FrameInjection::GetClassName(true); const ClassInfo *cls = NULL; if (!context.empty()) { cls = ClassInfo::FindClass(context); } Array ret = Array::Create(); // PHP has instance variables appear before static variables... for (unsigned int i = 0; i < properties.size(); i++) { if (!(properties[i]->attribute & ClassInfo::IsStatic) && properties[i]->isVisible(cls)) { ret.set(properties[i]->name, get_class_var_init(class_name.c_str(), properties[i]->name)); } } for (unsigned int i = 0; i < properties.size(); i++) { if (properties[i]->attribute & ClassInfo::IsStatic && properties[i]->isVisible(cls)) { ret.set(properties[i]->name, get_static_property(class_name.c_str(), properties[i]->name)); } } return ret; }
void VariableSerializer::writeSerializedProperty(CStrRef prop, const ClassInfo *cls) { String res = prop; const ClassInfo *origCls = cls; if (cls) { ClassInfo::PropertyInfo *p = cls->getPropertyInfo(prop.c_str()); // Try to find defining class while (!p && cls && cls->getParentClass()) { cls = ClassInfo::FindClass(cls->getParentClass()); if (cls) p = cls->getPropertyInfo(prop); } if (p) { const ClassInfo *dcls = p->owner; ClassInfo::Attribute a = p->attribute; if (a & ClassInfo::IsProtected) { res = String("\0*\0", 3, AttachLiteral) + prop; } else if (a & ClassInfo::IsPrivate && cls == origCls) { const char *clsname = dcls->getName(); int clsLen = strlen(clsname); int headerLen = clsLen + 2; int totalLen = headerLen + prop.size() + 1; char *buf = (char*)malloc(totalLen); buf[0] = '\0'; memcpy(buf + 1, clsname, clsLen); buf[clsLen + 1] = '\0'; memcpy(buf + headerLen, prop.c_str(), prop.size()); buf[totalLen - 1] = '\0'; res = String(buf, totalLen - 1, AttachString); } } } write(res); }
Variant f_socket_sendto(CObjRef socket, CStrRef buf, int len, int flags, CStrRef addr, int port /* = 0 */) { Socket *sock = socket.getTyped<Socket>(); if (len > buf.size()) { len = buf.size(); } int retval; switch (sock->getType()) { case AF_UNIX: { struct sockaddr_un s_un; memset(&s_un, 0, sizeof(s_un)); s_un.sun_family = AF_UNIX; snprintf(s_un.sun_path, 108, "%s", addr.data()); retval = sendto(sock->fd(), buf.data(), len, flags, (struct sockaddr *)&s_un, SUN_LEN(&s_un)); } break; case AF_INET: { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons((unsigned short) port); if (!php_set_inet_addr(&sin, addr.c_str(), sock)) { return false; } retval = sendto(sock->fd(), buf.data(), len, flags, (struct sockaddr *)&sin, sizeof(sin)); } break; case AF_INET6: { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons((unsigned short) port); if (!php_set_inet6_addr(&sin6, addr.c_str(), sock)) { return false; } retval = sendto(sock->fd(), buf.data(), len, flags, (struct sockaddr *)&sin6, sizeof(sin6)); } break; default: raise_warning("Unsupported socket type %d", sock->getType()); return false; } if (retval == -1) { SOCKET_ERROR(sock, "unable to write to socket", errno); return false; } return retval; }
bool Transport::moveUploadedFile(CStrRef filename, CStrRef destination) { if (!is_uploaded_file(filename.c_str())) { Logger::Error("%s is not an uploaded file.", filename.c_str()); return false; } return moveUploadedFileHelper(filename, destination); }
void c_SpoofChecker::t_setallowedlocales(CStrRef localesList) { UErrorCode status = U_ZERO_ERROR; uspoof_setAllowedLocales( m_spoof_checker, localesList.c_str(), &status); if (U_FAILURE(status)) { throw Exception( "Could not set allowed locales to [%s], error %d (%s)", localesList.c_str(), status, u_errorName(status)); } }
String BaseExecutionContext::getenv(CStrRef name) const { if (m_envs.exists(name)) { return m_envs[name]; } char *value = ::getenv(name.data()); if (value) { return String(value, CopyString); } if (RuntimeOption::EnvVariables.find(name.c_str()) != RuntimeOption::EnvVariables.end()) { return String(RuntimeOption::EnvVariables[name.c_str()].data(), CopyString); } return String(); }
bool c_Memcache::t_connect(CStrRef host, int port /*= 0*/, int timeout /*= 0*/, int timeoutms /*= 0*/) { memcached_return_t ret; if (!host.empty() && host[0] == '/') { ret = memcached_server_add_unix_socket(&m_memcache, host.c_str()); } else { ret = memcached_server_add(&m_memcache, host.c_str(), port); } return (ret == MEMCACHED_SUCCESS); }
// Move a file if and only if it was created by an upload bool Transport::moveUploadedFileHelper(CStrRef filename, CStrRef destination) { // Do access check. String dest = File::TranslatePath(destination); if (Util::rename(filename.c_str(), dest.c_str()) < 0) { Logger::Error("Unable to move uploaded file %s to %s: %s.", filename.c_str(), dest.c_str(), Util::safe_strerror(errno).c_str()); return false; } Logger::Verbose("Successfully moved uploaded file %s to %s.", filename.c_str(), dest.c_str()); return true; }
bool UrlFile::open(CStrRef url, CStrRef mode) { const char* modestr = mode.c_str(); if (strchr(modestr, '+') || strchr(modestr, 'a') || strchr(modestr, 'w')) { std::string msg = "cannot open a url stream for write/append operation: "; msg += url.c_str(); m_error = msg; return false; } HttpClient http(m_timeout, m_maxRedirect); m_response.reset(); HeaderMap *pHeaders = nullptr; HeaderMap requestHeaders; if (!m_headers.empty()) { pHeaders = &requestHeaders; for (ArrayIter iter(m_headers); iter; ++iter) { requestHeaders[string(iter.first().toString().data())]. push_back(iter.second().toString().data()); } } int code; vector<String> responseHeaders; if (m_get) { code = http.get(url.c_str(), m_response, pHeaders, &responseHeaders); } else { code = http.post(url.c_str(), m_postData.data(), m_postData.size(), m_response, pHeaders, &responseHeaders); } SystemGlobals *g = (SystemGlobals*)get_global_variables(); Variant &r = g->GV(http_response_header); r = Array::Create(); for (unsigned int i = 0; i < responseHeaders.size(); i++) { r.append(responseHeaders[i]); } m_responseHeaders = r; if (code == 200) { m_name = (std::string) url; m_data = const_cast<char*>(m_response.data()); m_len = m_response.size(); return true; } else { m_error = http.getLastError().c_str(); return false; } }
String f_system(CStrRef command, VRefParam return_var /* = null */) { ShellExecContext ctx; FILE *fp = ctx.exec(command.c_str()); if (!fp) return ""; StringBuffer sbuf; if (fp) { sbuf.read(fp); } Array lines = StringUtil::Explode(sbuf.detach(), "\n"); int ret = ctx.exit(); if (WIFEXITED(ret)) ret = WEXITSTATUS(ret); return_var = ret; int count = lines.size(); if (count > 0 && lines[count - 1].toString().empty()) { count--; // remove explode()'s last empty line } for (int i = 0; i < count; i++) { echo(lines[i]); echo("\n"); } if (!count || lines.empty()) { return String(); } return StringUtil::Trim(lines[count - 1], StringUtil::TrimRight); }
Variant f_bzcompress(CStrRef source, int blocksize /* = 4 */, int workfactor /* = 0 */) { char *dest = NULL; int error; unsigned int source_len, dest_len; source_len = source.length(); dest_len = source.length() + (0.01*source.length()) + 600; if (!(dest = (char *)malloc(dest_len + 1))) { return BZ_MEM_ERROR; } error = BZ2_bzBuffToBuffCompress(dest, &dest_len, (char *) source.c_str(), source_len, blocksize, 0, workfactor); if (error != BZ_OK) { free(dest); return error; } else { // this is to shrink the allocation, since we probably over allocated dest = (char *)realloc(dest, dest_len + 1); dest[dest_len] = '\0'; String ret = String(dest, dest_len, AttachString); return ret; } }
bool c_Memcached::getMultiImpl(CStrRef server_key, CArrRef keys, bool enableCas, Array *returnValue) { vector<const char*> keysCopy; keysCopy.reserve(keys.size()); vector<size_t> keysLengthCopy; keysLengthCopy.reserve(keys.size()); for (ArrayIter iter(keys); iter; ++iter) { Variant vKey = iter.second(); if (!vKey.isString()) continue; StringData *key = vKey.getStringData(); if (key->empty()) continue; keysCopy.push_back(key->data()); keysLengthCopy.push_back(key->size()); if (returnValue) returnValue->set(String(key), null_variant, true); } if (keysCopy.size() == 0) { m_impl->rescode = q_Memcached_RES_BAD_KEY_PROVIDED; return false; } memcached_behavior_set(&m_impl->memcached, MEMCACHED_BEHAVIOR_SUPPORT_CAS, enableCas ? 1 : 0); const char *myServerKey = server_key.empty() ? NULL : server_key.c_str(); size_t myServerKeyLen = server_key.length(); return handleError(memcached_mget_by_key(&m_impl->memcached, myServerKey, myServerKeyLen, keysCopy.data(), keysLengthCopy.data(), keysCopy.size())); }
String f_exec(CStrRef command, VRefParam output /* = null */, VRefParam return_var /* = null */) { ShellExecContext ctx; FILE *fp = ctx.exec(command.c_str()); if (!fp) return ""; StringBuffer sbuf; sbuf.read(fp); Array lines = StringUtil::Explode(sbuf.detach(), "\n"); int ret = ctx.exit(); if (WIFEXITED(ret)) ret = WEXITSTATUS(ret); return_var = ret; int count = lines.size(); if (count > 0 && lines[count - 1].toString().empty()) { count--; // remove explode()'s last empty line } if (!output.is(KindOfArray)) { output = Array(ArrayData::Create()); } for (int i = 0; i < count; i++) { output.append(lines[i]); } if (!count || lines.empty()) { return String(); } return StringUtil::Trim(lines[count - 1], StringUtil::TrimRight); }
bool Transport::splitHeader(CStrRef header, String &name, const char *&value) { int pos = header.find(':'); if (pos != String::npos) { name = header.substr(0, pos); value = header.data() + pos; do { value++; } while (*value == ' '); return true; } // header("HTTP/1.0 404 Not Found"); // header("HTTP/1.0 404"); if (strncasecmp(header.data(), "http/", 5) == 0) { int pos1 = header.find(' '); if (pos1 != String::npos) { int pos2 = header.find(' ', pos1 + 1); if (pos2 == String::npos) pos2 = header.size(); if (pos2 - pos1 > 1) { setResponse(atoi(header.data() + pos1), getResponseInfo().empty() ? "splitHeader" : getResponseInfo().c_str() ); return false; } } } throw InvalidArgumentException("header", header.c_str()); }
bool c_XMLReader::t_open(CStrRef uri, CStrRef encoding /*= null_string*/, int64 options /*= 0*/) { INSTANCE_METHOD_INJECTION_BUILTIN(XMLReader, XMLReader::open); if (m_ptr) { t_close(); } if (uri.empty()) { raise_warning("Empty string supplied as input"); return false; } String valid_file = _xmlreader_get_valid_file_path(uri.c_str()); xmlTextReaderPtr reader = NULL; if (!valid_file.empty()) { reader = xmlReaderForFile(valid_file.data(), encoding.data(), options); } if (reader == NULL) { raise_warning("Unable to open source data"); return false; } m_ptr = reader; return true; }
bool UrlFile::open(CStrRef url, CStrRef mode) { if (strchr(mode, '+') || strchr(mode, 'a') || strchr(mode, 'w')) { string msg("cannot open a url stream for write/append operation: "); msg += url.c_str(); raise_warning(msg.c_str()); return false; } HttpClient http(m_timeout, m_maxRedirect); StringBuffer response; HeaderMap *pHeaders = NULL; HeaderMap requestHeaders; if (!m_headers.empty()) { pHeaders = &requestHeaders; for (ArrayIter iter(m_headers); iter; ++iter) { requestHeaders[string(iter.first().toString().data())]. push_back(iter.second().toString().data()); } } int code; vector<String> responseHeaders; if (m_get) { code = http.get(url.c_str(), response, pHeaders, &responseHeaders); } else { code = http.post(url.c_str(), m_postData.data(), m_postData.size(), response, pHeaders, &responseHeaders); } SystemGlobals *g = (SystemGlobals*)get_global_variables(); Variant &r = g->gv_http_response_header; r = Array::Create(); for (unsigned int i = 0; i < responseHeaders.size(); i++) { r.append(responseHeaders[i]); } if (code == 200) { int len = m_len; m_name = url; m_data = response.detach(len); m_len = len; m_malloced = true; return true; } else { return false; } }
bool c_Memcached::setOperationImpl(SetOperation op, CStrRef server_key, CStrRef key, CVarRef value, int expiration) { m_impl->rescode = q_Memcached_RES_SUCCESS; if (key.empty()) { m_impl->rescode = q_Memcached_RES_BAD_KEY_PROVIDED; return false; } vector<char> payload; uint32 flags; toPayload(value, payload, flags); CStrRef myServerKey = server_key.empty() ? key : server_key; return handleError(op(&m_impl->memcached, myServerKey.c_str(), myServerKey.length(), key.c_str(), key.length(), payload.data(), payload.size(), expiration, flags)); }
bool c_Memcached::t_casbykey(double cas_token, CStrRef server_key, CStrRef key, CVarRef value, int expiration /*= 0*/) { INSTANCE_METHOD_INJECTION_BUILTIN(Memcached, Memcached::casbykey); m_impl->rescode = q_Memcached_RES_SUCCESS; if (key.empty()) { m_impl->rescode = q_Memcached_RES_BAD_KEY_PROVIDED; return false; } vector<char> payload; uint32 flags; toPayload(value, payload, flags); CStrRef myServerKey = server_key.empty() ? key : server_key; return handleError(memcached_cas_by_key(&m_impl->memcached, myServerKey.c_str(), myServerKey.length(), key.c_str(), key.length(), payload.data(), payload.size(), expiration, flags, (uint64)cas_token)); }
String f_shell_exec(CStrRef cmd) { ShellExecContext ctx; FILE *fp = ctx.exec(cmd.c_str()); if (!fp) return ""; StringBuffer sbuf; sbuf.read(fp); return sbuf.detach(); }
Variant c_Memcached::t_getbykey(CStrRef server_key, CStrRef key, CVarRef cache_cb /*= null_variant*/, VRefParam cas_token /*= null_variant*/) { INSTANCE_METHOD_INJECTION_BUILTIN(Memcached, Memcached::getbykey); m_impl->rescode = q_Memcached_RES_SUCCESS; if (key.empty()) { m_impl->rescode = q_Memcached_RES_BAD_KEY_PROVIDED; return false; } memcached_behavior_set(&m_impl->memcached, MEMCACHED_BEHAVIOR_SUPPORT_CAS, cas_token.isReferenced() ? 1 : 0); const char *myServerKey = server_key.empty() ? NULL : server_key.c_str(); size_t myServerKeyLen = server_key.length(); const char *myKey = key.c_str(); size_t myKeyLen = key.length(); memcached_return status = memcached_mget_by_key(&m_impl->memcached, myServerKey, myServerKeyLen, &myKey, &myKeyLen, 1); if (!handleError(status)) return false; Variant returnValue; MemcachedResultWrapper result(&m_impl->memcached); if (!memcached_fetch_result(&m_impl->memcached, &result.value, &status)) { if (status == MEMCACHED_END) status = MEMCACHED_NOTFOUND; if (status == MEMCACHED_NOTFOUND && !cache_cb.isNull()) { status = doCacheCallback(cache_cb, key, returnValue); if (!handleError(status)) return false; if (cas_token.isReferenced()) cas_token = 0.0; return returnValue; } handleError(status); return false; } if (!toObject(returnValue, result.value)) { m_impl->rescode = q_Memcached_RES_PAYLOAD_FAILURE; return false; } if (cas_token.isReferenced()) { cas_token = (double) memcached_result_cas(&result.value); } return returnValue; }
bool c_SpoofChecker::t_areconfusable( CStrRef s1, CStrRef s2, VRefParam issuesFound) { UErrorCode status = U_ZERO_ERROR; int32_t ret = uspoof_areConfusableUTF8( m_spoof_checker, s1.data(), s1.length(), s2.data(), s2.length(), &status); if (U_FAILURE(status)) { throw Exception( "Could not check [%s] and [%s] for confusability, error %d (%s)", s1.c_str(), s2.c_str(), status, u_errorName(status)); } issuesFound = ret; return ret != 0; }
String StringUtil::CEncode(CStrRef input, CStrRef charlist) { String chars = charlist; if (chars.isNull()) { chars = String("\\\x00\x01..\x1f\x7f..\xff", 10, CopyString); } if (input.empty() || chars.empty()) return input; int len = input.size(); char *ret = string_addcslashes(input.c_str(), len, chars.data(), chars.size()); return String(ret, len, AttachString); }
bool c_Memcache::t_delete(CStrRef key, int expire /*= 0*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } memcached_return_t ret = memcached_delete(&m_memcache, key.c_str(), key.length(), expire); return (ret == MEMCACHED_SUCCESS); }
bool RequestEvalState::declareConstant(CStrRef name, CVarRef val) { RequestEvalState *self = s_res.get(); if (self->m_constants.exists(name)) return false; self->m_constants.set(name, val); ClassInfo::ConstantInfo &ci = self->m_constantInfos[name.c_str()]; // Only need to set value really. ci.name = NULL; ci.valueLen = 0; ci.valueText = NULL; ci.setValue(val); return true; }
String f_uniqid(CStrRef prefix /* = null_string */, bool more_entropy /* = false */) { if (!more_entropy) { usleep(1); } struct timeval tv; gettimeofday((struct timeval *)&tv, NULL); int sec = (int)tv.tv_sec; int usec = (int)(tv.tv_usec % 0x100000); char uniqid[256]; if (more_entropy) { snprintf(uniqid, sizeof(uniqid), "%s%08x%05x%.8F", prefix.c_str(), sec, usec, math_combined_lcg() * 10); } else { snprintf(uniqid, sizeof(uniqid), "%s%08x%05x", prefix.c_str(), sec, usec); } return String(uniqid, CopyString); }
bool ZipFile::open(CStrRef filename, CStrRef 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; } return m_innerFile->open(filename, mode) && (m_gzFile = gzdopen(dup(m_innerFile->fd()), mode.data())); }
void TaintWarning::WarnIfTainted(CStrRef s, const taint_t bit) { const TaintData& td = s.get()->getTaintDataRefConst(); if (!(td.getTaint() & bit)) { return; } bool force_warning = false; std::string buf, aux; buf = "Using a "; switch (bit) { case TAINT_BIT_HTML: buf += "HTML-unsafe (tainted)"; if (TaintTracer::IsTraceEnabled(TAINT_BIT_TRACE_HTML)) { force_warning = true; aux = TaintTracer::ExtractTrace(td.getTaintTrace()); } break; case TAINT_BIT_MUTATED: buf += "non-static (tainted)"; break; case TAINT_BIT_SQL: buf += "SQL-unsafe (tainted)"; break; case TAINT_BIT_SHELL: buf += "shell-unsafe (tainted)"; break; case TAINT_BIT_ALL: buf += "tainted"; break; default: return; } buf += " string!\n"; if (RuntimeOption::EnableTaintWarnings || force_warning) { buf += aux; buf += "\n"; buf += "---begin output---\n"; buf += s.c_str(); buf += "\n"; buf += "----end output----\n"; ZeroCount(bit); raise_warning(buf); } else { IncCount(bit); } }
bool c_Memcache::t_addserver(CStrRef host, int port /* = 11211 */, bool persistent /* = false */, int weight /* = 0 */, int timeout /* = 0 */, int retry_interval /* = 0 */, bool status /* = true */, CVarRef failure_callback /* = null_variant */, int timeoutms /* = 0 */) { memcached_return_t ret; if (!host.empty() && host[0] == '/') { ret = memcached_server_add_unix_socket_with_weight(&m_memcache, host.c_str(), weight); } else { ret = memcached_server_add_with_weight(&m_memcache, host.c_str(), port, weight); } if (ret == MEMCACHED_SUCCESS) { return true; } return false; }
Variant invoke_file(CStrRef s, bool once, LVariableTable* variables, const char *currentDir) { assert(!variables); // this LVariableTable is unused in HHVM { Variant r; if (eval_invoke_file_hook(r, s, once, variables, currentDir)) { return r; } } if (s.empty()) return vm_default_invoke_file(once); return throw_missing_file(s.c_str()); }